file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/4/0x8737d5288703019F3355AE2a4981051A13CF7Aaa/sources/contracts/FundMe.sol
Map the address calling this function with the amount of ether they sent
function fund() public payable { uint256 minimumUsd = 50 * 10 ** 8; require(getConversionRate(msg.value) >= minimumUsd, "You needs spends more ETH!"); }
13,364,157
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IArweaveMarket} from "./interfaces/IArweaveMarket.sol"; import {IMarketMediator} from "./interfaces/IMarketMediator.sol"; import {IArbitrable} from "./interfaces/IArbitrable.sol"; import {IArbitrator} from "./interfaces/IArbitrator.sol"; contract ArweaveMarketMediator is IMarketMediator, IArbitrable, Ownable { address public market; address public arbitrator; bytes public arbitrationExtraData; Dispute[] public disputes; mapping(uint256 => uint256) public requestToDispute; mapping(uint256 => uint256) public arbitratorDisputeToDispute; uint256 disputeWindow; modifier onlyMarket() { require( msg.sender == market, "MarketMediator::onlyMarket:Sender is not market" ); _; } modifier onlyArbitrator() { require( msg.sender == arbitrator, "MarketMediator::onlyArbitrator:Sender is not arbitrator" ); _; } constructor( address _arbitrator, bytes memory _arbitrationExtraData, uint256 _disputeWindow ) { arbitrator = _arbitrator; arbitrationExtraData = _arbitrationExtraData; disputeWindow = _disputeWindow; } function initMarket(address _market) external onlyOwner { require( market == address(0), "MarketMediator::initMarket:Market already initialised" ); market = _market; } // trust market not to dispute same request twice function createDispute(uint256 _requestId) external override onlyMarket { uint256 disputeId = disputes.length; Dispute memory dispute; dispute.requestId = _requestId; dispute.deadline = block.timestamp + disputeWindow; disputes.push(dispute); requestToDispute[_requestId] = disputeId; emit DisputeCreated(disputeId, _requestId); } function setDisputeWinner( uint256 _disputeId, IArweaveMarket.DisputeWinner _winner ) external onlyOwner { Dispute storage dispute = disputes[_disputeId]; require( !dispute.resolved, "MarketMediator::setDisputeWinner:Dispute already resolved" ); require( dispute.deadline >= block.timestamp, "MarketMediator::setDisputeWinner:Deadline has been reached" ); require( !dispute.escalatedToArbitrator, "MarketMediator::setDisputeWinner:Dispute has been escalated to arbitrator" ); dispute.winner = _winner; } function escalateDispute(uint256 _disputeId) external payable { Dispute storage dispute = disputes[_disputeId]; require( !dispute.resolved, "MarketMediator::escalateDispute:Dispute already resolved" ); require( dispute.deadline >= block.timestamp, "MarketMediator::escalateDispute:Deadline has been reached" ); require( !dispute.escalatedToArbitrator, "MarketMediator::escalateDispute:Dispute has been escalated to arbitrator" ); dispute.escalatedToArbitrator = true; uint256 cost = getArbitrationCost(); require( msg.value == cost, "MarketMediator::escalateDispute:Invalid msg.value" ); uint256 arbitratorDisputeId = IArbitrator(arbitrator).createDispute{ value: cost }(2, arbitrationExtraData); dispute.arbitratorDisputeId = arbitratorDisputeId; arbitratorDisputeToDispute[arbitratorDisputeId] = _disputeId; emit DisputeEscalated(_disputeId); } // arbitrable spec function rule(uint256 _disputeID, uint256 _ruling) external override onlyArbitrator { uint256 disputeId = arbitratorDisputeToDispute[_disputeID]; _ruleDispute(disputeId, IArweaveMarket.DisputeWinner(_ruling)); emit Ruling(IArbitrator(arbitrator), _disputeID, _ruling); // ERC792 Arbitrable event } function resolveDispute(uint256 _disputeId) public { Dispute storage dispute = disputes[_disputeId]; require( !dispute.resolved, "MarketMediator::resolveDispute:Dispute already resolved" ); require( dispute.deadline < block.timestamp, "MarketMediator::resolveDispute:Deadline has not been reached" ); if (dispute.escalatedToArbitrator) { require( dispute.arbitratorRuled, "MarketMediator::resolveDispute:Arbitrator has not ruled yet" ); } dispute.resolved = true; IArweaveMarket(market).resolveDispute( disputes[_disputeId].requestId, dispute.winner ); emit DisputeResolved(_disputeId, dispute.winner); } function _ruleDispute( uint256 _disputeId, IArweaveMarket.DisputeWinner _winner ) internal { Dispute storage dispute = disputes[_disputeId]; require( dispute.escalatedToArbitrator, "MarketMediator::_ruleDispute:Dispute is not escalated" ); require( !dispute.arbitratorRuled, "MarketMediator::_ruleDispute:Dispute is already ruled" ); dispute.winner = _winner; dispute.arbitratorRuled = true; } function setArbitrationExtraData(bytes calldata _extraData) external onlyOwner { arbitrationExtraData = _extraData; } function getArbitrationCost() public view returns (uint256) { return IArbitrator(arbitrator).arbitrationCost(arbitrationExtraData); } function getDisputeIdFromRequestId(uint256 _requestId) public view returns (uint256) { return requestToDispute[_requestId]; } function getRequestIdFromDisputeId(uint256 _disputeId) public view returns (uint256) { return disputes[_disputeId].requestId; } function getDisputesLength() public view returns (uint256) { return disputes.length; } function getMarket() public view override returns (address) { return market; } }
trust market not to dispute same request twice
function createDispute(uint256 _requestId) external override onlyMarket { uint256 disputeId = disputes.length; Dispute memory dispute; dispute.requestId = _requestId; dispute.deadline = block.timestamp + disputeWindow; disputes.push(dispute); requestToDispute[_requestId] = disputeId; emit DisputeCreated(disputeId, _requestId); }
6,411,609
./full_match/43114/0x7f45cb159561F8f139C5971a75a0a4210F751Adc/sources/project:/contracts/Comptroller.sol
Add the market to the borrower's "assets in" for liquidity calculations cToken The market to enter borrower The address of the account to modify return Success indicator for whether the market was entered/ market is not listed, cannot join already joined
function addToMarketInternal( CToken cToken, address borrower ) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { return Error.NO_ERROR; } accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; }
4,522,573
pragma solidity >=0.4.17 <0.7.0; pragma experimental ABIEncoderV2; import "../../node_modules/@openzeppelin/contracts/token/ERC721/ERC721Full.sol"; contract Item is ERC721Full { string[] public ids; constructor() ERC721Full('Item', 'ITEM') public {} function mint(string memory _item, string memory _uri) public returns (uint){ // uint _id = ids.push(_item); _mint(msg.sender, _id); _setTokenURI(_id, _uri); return _id; } } contract SupplyChain2 { struct SupplyChainNode { address addr; uint nodeId; //These inventories will hold the IDs of the tokens in them uint[] inventory; uint[] received; uint[] flagged; } // struct Item { // string itemType; // uint itemId; // uint[2] puf; //One integer to hold the PUF value with the decimal point removed // //a second to hold the index of the decimal point // } mapping (address => SupplyChainNode) nodeOf; address admin; uint constant CHAINSIZE = 5; SupplyChainNode[CHAINSIZE] public chain; modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOrigin() { require(nodeOf[msg.sender].nodeId == 0); _; } function isSelfOrAdmin(address a) public returns (bool) { if (msg.sender == a) { return true; } else if (msg.sender == admin) { return true; } return false; } function getChain() public returns (address[] memory) { address[] memory toReturn = new address[](CHAINSIZE); for(uint i = 0; i < CHAINSIZE; i++){ toReturn[i] = chain[i].addr; } return toReturn; } modifier onlyThis(address a) { require(isSelfOrAdmin(a)); _; } constructor() public payable { admin = msg.sender; } function register(address a, uint loc) public payable onlyAdmin { //chain.length++; //chain[chain.length-1].addr = a; //chain[chain.length-1].nodeId = id; chain[loc].addr = a; chain[loc].nodeId = loc; nodeOf[a] = chain[loc]; } // function createItem(string memory i, uint id, uint[2] memory p) public payable { // nodeOf[msg.sender].inventory.length++; // nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1].itemType = i; // nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1].itemId = id; // nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1].puf = p; // // } function flagItem(address a, uint _id) public { for(uint i = 0; i < nodeOf[a].received.length; i++) { if(nodeOf[a].received[i] == _id) { nodeOf[a].flagged.length++; nodeOf[a].flagged[nodeOf[a].flagged.length-1] = _id; nodeOf[a].received[i] = nodeOf[a].received[nodeOf[a].received.length-1]; delete nodeOf[a].received[nodeOf[a].received.length-1]; } } for(uint i = 0; i < nodeOf[a].inventory.length; i++) { if(nodeOf[a].inventory[i] == _id) { nodeOf[a].flagged.length++; nodeOf[a].flagged[nodeOf[a].flagged.length-1] = _id; nodeOf[a].inventory[i] = nodeOf[a].inventory[nodeOf[a].inventory.length-1]; delete nodeOf[a].inventory[nodeOf[a].inventory.length-1]; } } } function confirmItem(address a, uint _id) public { for(uint i = 0; i < nodeOf[a].received.length; i++) { if(nodeOf[a].received[i] == _id) { nodeOf[a].inventory.length++; nodeOf[a].inventory[nodeOf[a].inventory.length-1] = _id; nodeOf[a].received[i] = nodeOf[a].received[nodeOf[a].received.length-1]; delete nodeOf[a].received[nodeOf[a].received.length-1]; } } } function getInventory(address s) public onlyThis(s) returns (uint[] memory) { uint[] memory toReturn = new uint[](nodeOf[s].inventory.length); for(uint i = 0; i < nodeOf[s].inventory.length; i++){ toReturn[i] = nodeOf[s].inventory[i]; } return toReturn; } function getReceived(address s) public onlyThis(s) returns (uint[] memory) { uint[] memory toReturn = new uint[](nodeOf[s].received.length); for(uint i = 0; i < nodeOf[s].received.length; i++){ toReturn[i] = nodeOf[s].received[i]; } return toReturn; } function getFlagged(address s) public onlyThis(s) returns (uint[] memory) { uint[] memory toReturn = new uint[](nodeOf[s].flagged.length); for(uint i = 0; i < nodeOf[s].flagged.length; i++){ toReturn[i] = nodeOf[s].flagged[i]; } return toReturn; } function addItem(uint256 a) public payable { nodeOf[msg.sender].inventory.length++; nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1] = a; } // function removeItem(Item memory a) public payable { // for(uint i = 0; i < nodeOf[msg.sender].inventory.length; i++) { // if(nodeOf[msg.sender].inventory[i].itemId == a.itemId) { // for(uint j = i+1; j < nodeOf[msg.sender].inventory.length; j++) { // nodeOf[msg.sender].inventory[j-1]=nodeOf[msg.sender].inventory[j]; // } // nodeOf[msg.sender].inventory.length--; // } // } // } function passItem(address s, address t, uint id) public onlyThis(s) payable { for(uint i = 0; i < nodeOf[s].inventory.length; i++) { if(nodeOf[s].inventory[i] == id) { nodeOf[t].received.length++; nodeOf[t].received[nodeOf[t].received.length-1] = id; nodeOf[s].inventory[i] = nodeOf[s].inventory[nodeOf[s].inventory.length-1]; delete nodeOf[s].inventory[nodeOf[s].inventory.length-1]; nodeOf[s].inventory.length--; } } } }
function createItem(string memory i, uint id, uint[2] memory p) public payable { nodeOf[msg.sender].inventory.length++; nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1].itemType = i; nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1].itemId = id; nodeOf[msg.sender].inventory[nodeOf[msg.sender].inventory.length-1].puf = p; }
function flagItem(address a, uint _id) public { for(uint i = 0; i < nodeOf[a].received.length; i++) { if(nodeOf[a].received[i] == _id) { nodeOf[a].flagged.length++; nodeOf[a].flagged[nodeOf[a].flagged.length-1] = _id; nodeOf[a].received[i] = nodeOf[a].received[nodeOf[a].received.length-1]; delete nodeOf[a].received[nodeOf[a].received.length-1]; } } for(uint i = 0; i < nodeOf[a].inventory.length; i++) { if(nodeOf[a].inventory[i] == _id) { nodeOf[a].flagged.length++; nodeOf[a].flagged[nodeOf[a].flagged.length-1] = _id; nodeOf[a].inventory[i] = nodeOf[a].inventory[nodeOf[a].inventory.length-1]; delete nodeOf[a].inventory[nodeOf[a].inventory.length-1]; } } }
15,881,451
pragma solidity ^0.4.24; import "./DestructibleMiniMeTokenFactory.sol"; import "./Ownable.sol"; /* Copyright 2018, Will Harborne @ Ethfinex */ /// @title ProposalManager Contract /// @author Will Harborne @ Ethfinex contract TokenListingManager is Ownable { address public constant NECTAR_TOKEN = 0xCc80C051057B774cD75067Dc48f8987C4Eb97A5e; address public constant TOKEN_FACTORY = 0x6EB97237B8bc26E8057793200207bB0a2A83C347; uint public constant MAX_CANDIDATES = 20; struct TokenProposal { address[] consideredTokens; uint startBlock; uint startTime; uint duration; address votingToken; uint[] yesVotes; // criteria values // 0. only first one win the vote; // 1. top N (number in extraData) win the vote; // 2. All over N (number in extra data) votes win the vote; uint criteria; uint extraData; } TokenProposal[] public tokenBatches; DestructibleMiniMeTokenFactory public tokenFactory; address public nectarToken; mapping(address => bool) public admins; modifier onlyAdmins() { require(isAdmin(msg.sender)); _; } constructor(address _tokenFactory, address _nectarToken) public { tokenFactory = DestructibleMiniMeTokenFactory(_tokenFactory); nectarToken = _nectarToken; admins[msg.sender] = true; } /// @notice Admins are able to approve proposal that someone submitted /// @param _tokens the list of tokens in consideration during this period /// @param _duration number of days for voting /// @param _criteria number that determines how winner is selected /// @param _extraData extra data for criteria parameter function startTokenVotes(address[] _tokens, uint _duration, uint _criteria, uint _extraData) public onlyAdmins { require(_tokens.length <= MAX_CANDIDATES); if (_criteria == 1) { // in other case all tokens would be winners require(_extraData < _tokens.length); } uint _proposalId = tokenBatches.length; if (_proposalId > 0) { TokenProposal memory op = tokenBatches[_proposalId - 1]; DestructibleMiniMeToken(op.votingToken).recycle(); } tokenBatches.length++; TokenProposal storage p = tokenBatches[_proposalId]; p.duration = _duration * (1 days); p.consideredTokens = _tokens; p.yesVotes = new uint[](_tokens.length); p.votingToken = tokenFactory.createDestructibleCloneToken( nectarToken, getBlockNumber(), appendUintToString("EfxTokenVotes-", _proposalId), MiniMeToken(nectarToken).decimals(), appendUintToString("EVT-", _proposalId), true); p.startTime = now; p.startBlock = getBlockNumber(); p.criteria = _criteria; p.extraData = _extraData; emit NewTokens(_proposalId); } /// @notice Vote for specific token with yes /// @param _tokenIndex is the position from 0-9 in the token array of the chosen token function vote(uint _tokenIndex, uint _amount) public { // voting only on the most recent set of proposed tokens require(tokenBatches.length > 0); uint _proposalId = tokenBatches.length - 1; require(_tokenIndex < 10); TokenProposal memory p = tokenBatches[_proposalId]; require(now < p.startTime + p.duration); uint amount = DestructibleMiniMeToken(p.votingToken).balanceOf(msg.sender); require(amount >= _amount); require(DestructibleMiniMeToken(p.votingToken).transferFrom(msg.sender, address(this), _amount)); tokenBatches[_proposalId].yesVotes[_tokenIndex] += _amount; emit Vote(_proposalId, msg.sender, tokenBatches[_proposalId].consideredTokens[_tokenIndex], _amount); } function getWinners(uint _proposalId) public view returns(address[] winners) { require(_proposalId < tokenBatches.length); TokenProposal memory p = tokenBatches[_proposalId]; // there is only one winner in criteria 0 if (p.criteria == 0) { winners = new address[](1); uint max = 0; for (uint i=0; i < p.consideredTokens.length; i++) { if (p.yesVotes[i] > p.yesVotes[max]) { max = i; } } winners[0] = p.consideredTokens[max]; } // there is N winners in criteria 1 if (p.criteria == 1) { uint[] memory indexesWithMostVotes = new uint[](p.extraData); winners = new address[](p.extraData); // for each token we check if he has more votes than last one, // if it has we put it in array and always keep array sorted for (i = 0; i < p.consideredTokens.length; i++) { uint last = p.extraData - 1; if (p.yesVotes[i] > p.yesVotes[indexesWithMostVotes[last]]) { indexesWithMostVotes[last] = i; for (uint j=last; j > 0; j--) { if (p.yesVotes[indexesWithMostVotes[j]] > p.yesVotes[indexesWithMostVotes[j-1]]) { uint help = indexesWithMostVotes[j]; indexesWithMostVotes[j] = indexesWithMostVotes[j-1]; indexesWithMostVotes[j-1] = help; } } } } for (i = 0; i < p.extraData; i++) { winners[i] = p.consideredTokens[indexesWithMostVotes[i]]; } } // everybody who has over N votes are winners in criteria 2 if (p.criteria == 2) { uint numOfTokens = 0; for (i = 0; i < p.consideredTokens.length; i++) { if (p.yesVotes[i] > p.extraData) { numOfTokens++; } } winners = new address[](numOfTokens); uint count = 0; for (i = 0; i < p.consideredTokens.length; i++) { if (p.yesVotes[i] > p.extraData) { winners[count] = p.consideredTokens[i]; count++; } } } } /// @notice Get number of proposals so you can know which is the last one function numberOfProposals() public view returns(uint) { return tokenBatches.length; } /// @notice Any admin is able to add new admin /// @param _newAdmin Address of new admin function addAdmin(address _newAdmin) public onlyAdmins { admins[_newAdmin] = true; } /// @notice Only owner is able to remove admin /// @param _admin Address of current admin function removeAdmin(address _admin) public onlyOwner { admins[_admin] = false; } /// @notice Get data about specific proposal /// @param _proposalId Id of proposal function proposal(uint _proposalId) public view returns( uint _startBlock, uint _startTime, uint _duration, bool _active, bool _finalized, uint[] _votes, address[] _tokens, address _votingToken, bool _hasBalance ) { require(_proposalId < tokenBatches.length); TokenProposal memory p = tokenBatches[_proposalId]; _startBlock = p.startBlock; _startTime = p.startTime; _duration = p.duration; _finalized = (_startTime+_duration < now); _active = !_finalized && (p.startBlock < getBlockNumber()); _votes = p.yesVotes; _tokens = p.consideredTokens; _votingToken = p.votingToken; _hasBalance = (p.votingToken == 0x0) ? false : (DestructibleMiniMeToken(p.votingToken).balanceOf(msg.sender) > 0); } function isAdmin(address _admin) public view returns(bool) { return admins[_admin]; } function proxyPayment(address ) public payable returns(bool) { return false; } function onTransfer(address, address, uint ) public pure returns(bool) { return true; } function onApprove(address, address, uint ) public pure returns(bool) { return true; } function getBlockNumber() internal constant returns (uint) { return block.number; } function appendUintToString(string inStr, uint v) private pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; if (v == 0) { reversed[i++] = byte(48); } else { while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } } bytes memory inStrb = bytes(inStr); bytes memory s = new bytes(inStrb.length + i); uint j; for (j = 0; j < inStrb.length; j++) { s[j] = inStrb[j]; } for (j = 0; j < i; j++) { s[j + inStrb.length] = reversed[i - 1 - j]; } str = string(s); } event Vote(uint indexed idProposal, address indexed _voter, address chosenToken, uint amount); event NewTokens(uint indexed idProposal); }
there is only one winner in criteria 0 there is N winners in criteria 1 for each token we check if he has more votes than last one, if it has we put it in array and always keep array sorted everybody who has over N votes are winners in criteria 2
function getWinners(uint _proposalId) public view returns(address[] winners) { require(_proposalId < tokenBatches.length); TokenProposal memory p = tokenBatches[_proposalId]; if (p.criteria == 0) { winners = new address[](1); uint max = 0; for (uint i=0; i < p.consideredTokens.length; i++) { if (p.yesVotes[i] > p.yesVotes[max]) { max = i; } } winners[0] = p.consideredTokens[max]; } if (p.criteria == 1) { uint[] memory indexesWithMostVotes = new uint[](p.extraData); winners = new address[](p.extraData); for (i = 0; i < p.consideredTokens.length; i++) { uint last = p.extraData - 1; if (p.yesVotes[i] > p.yesVotes[indexesWithMostVotes[last]]) { indexesWithMostVotes[last] = i; for (uint j=last; j > 0; j--) { if (p.yesVotes[indexesWithMostVotes[j]] > p.yesVotes[indexesWithMostVotes[j-1]]) { uint help = indexesWithMostVotes[j]; indexesWithMostVotes[j] = indexesWithMostVotes[j-1]; indexesWithMostVotes[j-1] = help; } } } } for (i = 0; i < p.extraData; i++) { winners[i] = p.consideredTokens[indexesWithMostVotes[i]]; } } if (p.criteria == 2) { uint numOfTokens = 0; for (i = 0; i < p.consideredTokens.length; i++) { if (p.yesVotes[i] > p.extraData) { numOfTokens++; } } winners = new address[](numOfTokens); uint count = 0; for (i = 0; i < p.consideredTokens.length; i++) { if (p.yesVotes[i] > p.extraData) { winners[count] = p.consideredTokens[i]; count++; } } } }
12,830,021
./full_match/1/0xB5b20179cB694226b5E26d84d1e3E677aB330de4/sources/contracts/diamond/IDiamondFacet.sol
Kam Amini <kam@qomet.tech> Use at your own risk NOTE: The override MUST remain 'pure'. NOTE: The override MUST remain 'pure'. NOTE: The override MUST remain 'pure'. NOTE: The override MUST remain 'pure'.
interface IDiamondFacet is IERC165 { function getFacetName() external pure returns (string memory); function getFacetVersion() external pure returns (string memory); function getFacetPI() external pure returns (string[] memory); function getFacetProtectedPI() external pure returns (string[] memory); }
2,928,854
//SPDX-License-Identifier: Open Source pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title CGFMWallet: Crypto Gifts For Minors Wallet /// @author Hico /// @notice This contract has not been audited /// @dev No side effects contract Wallet is Ownable { address[] public approvers; uint public quorum; uint constant public MAX_APPROVER_COUNT = 10; address payable public beneficiary; uint public creationTime = block.timestamp; bool public stopped = false; struct Transfer { uint id; uint amount; address payable to; uint approvals; bool sent; } Transfer[] public transfers; mapping(address => mapping(uint => bool)) private approvals; event EthReceived(address user, uint indexed amount); event WithdrawalRequested(uint indexed amount, address to); event WithdrawalApproved(uint indexed id); /// @notice Create Ownable MultiSig Timelock wallet with chosen approvers and amount of approvals needed for quorum /// @dev /// @param _approvers addresses which are approvers of the Multi-Sig /// @param _quorum amount of approvers needed to send transfer /// @param _beneficiary only address which can request a 'send transfer' and 'close wallet' function. constructor(address[] memory _approvers, uint _quorum, address payable _beneficiary) validRequirement(_approvers.length, _quorum) { approvers = _approvers; quorum = _quorum; beneficiary = _beneficiary; } /// @notice Can send Eth to this wallet without any data /// @dev Receive function receive() external payable { emit EthReceived(msg.sender, msg.value); } /// @notice The function that is executed if not other fucntion matches the call /// @dev Fallback function fallback() external payable {} /// @notice Get the address list of approvers /// @dev /// @return Addresses of approvers function getApprovers() external view returns(address[] memory) { return approvers; } /// @notice Get the list and details of transfers /// @dev /// @return Transfers list function getTransfers() external view returns(Transfer[] memory) { return transfers; } /// @notice When the contract turns 16, only beneficiary may request to withdraw Eth /// @dev /// @param amount is the amount of Eth the beneficiary wants to withdraw /// @param to is the address that the beneficiary wants to send Eth to function createTransfer(uint amount, address payable to) external onlyBeneficiary() stopInEmergency() timeLock16() { require(address(this).balance > 0, 'There is zero Ether in this wallet'); emit WithdrawalRequested(amount, to); transfers.push(Transfer( transfers.length, amount, to, 0, false )); } /// @notice Approvers can approve a transfer request /// @dev /// @param id is the indexed transaction id number function approveTransfer(uint id) public onlyApprover() stopInEmergency() timeLock16() { require(transfers[id].sent == false, 'Transfer has already been sent'); require(approvals[msg.sender][id] == false, 'Cannot approve transfer for the second time'); emit WithdrawalApproved(id); approvals[msg.sender][id] = true; transfers[id].approvals++; if(transfers[id].approvals >= quorum) { transfers[id].sent = true; address payable to = transfers[id].to; uint amount = transfers[id].amount; to.transfer(amount); } } /// @notice View balance of this contract /// @dev /// @return Balance of this contract function getBalance() view public returns(uint) { return address(this).balance; } /// @notice Toggle contract active by limiting certain functions /// @dev Circuit breaker function toggleContractActive() onlyOwner public { stopped = !stopped; } /// @notice Beneficiary can choose to withdraw all Eth and close this contract /// @dev Selfdestruct function /// @return Balance of this address function closeWallet() public onlyBeneficiary() timeLock18() returns(uint) { selfdestruct(beneficiary); return(address(this).balance); } modifier validRequirement(uint approverCount, uint _quorom) { require(approverCount <= MAX_APPROVER_COUNT && _quorom <= approverCount && _quorom != 0 && approverCount != 0); _; } modifier onlyApprover() { bool allowed = false; for(uint i = 0; i < approvers.length; i++) { if(approvers[i] == msg.sender) { allowed = true; } } require(allowed == true, 'Valid approvers only.'); _; } modifier onlyBeneficiary() { require(msg.sender == beneficiary, "You are not the Beneficiary of this contract!"); _; } modifier timeLock16() { require(block.timestamp > (creationTime + 835 weeks), 'Beneficiary is not 16 years old.'); _; } modifier timeLock18() { require(block.timestamp > (creationTime + 939 weeks), 'Beneficiary is not 18 years old.'); _; } modifier stopInEmergency() { require(!stopped, 'This contract is currently stopped'); _; } }
When the contract turns 16, only beneficiary may request to withdraw Eth amount is the amount of Eth the beneficiary wants to withdraw to is the address that the beneficiary wants to send Eth to
function createTransfer(uint amount, address payable to) external onlyBeneficiary() stopInEmergency() timeLock16() { require(address(this).balance > 0, 'There is zero Ether in this wallet'); emit WithdrawalRequested(amount, to); transfers.push(Transfer( transfers.length, amount, to, 0, false )); }
12,839,980
./full_match/1/0xC9e4fe1AeD8D8c62cE884DE17428dD419C127810/sources/src/Token.sol
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `requestedDecrease`. NOTE: Although this function is designed to avoid double spending with {approval}, it can still be frontrunned, preventing any attempt of allowance reduction./
function decreaseAllowance( address spender, uint256 requestedDecrease ) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); if (currentAllowance < requestedDecrease) { revert("ERC20: decreased allowance below zero"); } unchecked { _approve(owner, spender, currentAllowance - requestedDecrease); } return true; }
4,896,667
./partial_match/1/0x061888246A29fEB9bb3f168CD8589B3Cf4115668/sources/YodlRouterV1.sol
Calculates exchange rates from a given price feed At most we can have 2 price feeds. We will use a zero address to determine if we need to inverse a singular price feeds. For multiple price feeds, we will always pass them in such that we multiply by the first and divide by the second. This works because all of our price feeds have USD as the quote currency. priceFeeds Array of Chainlink price feeds amount Amount to be converted by the price feed exchange rates return converted The amount after conversion return priceFeedsUsed The price feeds in the order they were used return prices The exchange rates from the price feeds/ Inverse the price feed No need to inverse Multiply by the first, divide by the second Will always be A -> USD -> B We will always divide by the second price feed
function exchangeRate( address[2] calldata priceFeeds, uint256 amount ) public view returns ( uint256 converted, address[2] memory priceFeedsUsed, int256[2] memory prices ) { require( priceFeeds[0] != address(0) || priceFeeds[1] != address(0), "invalid pricefeeds" ); bool shouldInverse; AggregatorV3Interface priceFeedOne; if (priceFeeds[0] == address(0)) { shouldInverse = true; priceFeedOne = AggregatorV3Interface(priceFeeds[1]); priceFeedOne = AggregatorV3Interface(priceFeeds[0]); if (priceFeeds[1] != address(0)) { priceFeedTwo = AggregatorV3Interface(priceFeeds[1]); } } (, int256 price, , , ) = priceFeedOne.latestRoundData(); prices[0] = price; if (shouldInverse) { converted = (amount * decimals) / uint256(price); converted = (amount * uint256(price)) / decimals; } if (address(priceFeedTwo) != address(0)) { decimals = uint256(10 ** uint256(priceFeedTwo.decimals())); (, price, , , ) = priceFeedTwo.latestRoundData(); prices[1] = price; converted = (converted * decimals) / uint256(price); } return ( converted, [address(priceFeedOne), address(priceFeedTwo)], prices ); }
15,991,504
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; /** * @title Controller component * @dev For easy access to any core components */ abstract contract Controller is Initializable, UUPSUpgradeable, AccessControlUpgradeable { bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); mapping(address => address) private _admins; // slither-disable-next-line uninitialized-state bool private _paused; // slither-disable-next-line uninitialized-state address public pauseGuardian; /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Controller: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Controller: not paused"); _; } modifier onlyAdmin() { require(hasRole(ROLE_ADMIN, msg.sender), "Controller: not admin"); _; } modifier onlyGuardian() { require(pauseGuardian == msg.sender, "Controller: caller does not have the guardian role"); _; } //When using minimal deploy, do not call initialize directly during deploy, because msg.sender is the proxyFactory address, and you need to call it manually function __Controller_init(address admin_) public initializer { require(admin_ != address(0), "Controller: address zero"); _paused = false; _admins[admin_] = admin_; __UUPSUpgradeable_init(); _setupRole(ROLE_ADMIN, admin_); pauseGuardian = admin_; } function _authorizeUpgrade(address) internal view override onlyAdmin {} /** * @dev Check if the address provided is the admin * @param account Account address */ function isAdmin(address account) public view returns (bool) { return hasRole(ROLE_ADMIN, account); } /** * @dev Add a new admin account * @param account Account address */ function addAdmin(address account) public onlyAdmin { require(account != address(0), "Controller: address zero"); require(_admins[account] == address(0), "Controller: admin already existed"); _admins[account] = account; _setupRole(ROLE_ADMIN, account); } /** * @dev Set pauseGuardian account * @param account Account address */ function setGuardian(address account) public onlyAdmin { pauseGuardian = account; } /** * @dev Renouce the admin from the sender's address */ function renounceAdmin() public { renounceRole(ROLE_ADMIN, msg.sender); delete _admins[msg.sender]; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyGuardian whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyGuardian whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[50] private ______gap; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title AssetManager Interface * @dev Manage the token balances staked by the users and deposited by admins, and invest tokens to the integrated underlying lending protocols. */ interface IAssetManager { /** * @dev Returns the balance of asset manager, plus the total amount of tokens deposited to all the underlying lending protocols. * @param tokenAddress ERC20 token address * @return Lending pool balance */ function getPoolBalance(address tokenAddress) external view returns (uint256); /** * @dev Returns the amount of the lending pool balance minus the amount of total staked. * @param tokenAddress ERC20 token address * @return Amount can be borrowed */ function getLoanableAmount(address tokenAddress) external view returns (uint256); /** * @dev Get the total amount of tokens deposited to all the integrated underlying protocols without side effects. * @param tokenAddress ERC20 token address * @return Total market balance */ function totalSupply(address tokenAddress) external returns (uint256); /** * @dev Get the total amount of tokens deposited to all the integrated underlying protocols, but without side effects. Safe to call anytime, but may not get the most updated number for the current block. Call totalSupply() for that purpose. * @param tokenAddress ERC20 token address * @return Total market balance */ function totalSupplyView(address tokenAddress) external view returns (uint256); /** * @dev Check if there is an underlying protocol available for the given ERC20 token. * @param tokenAddress ERC20 token address * @return Whether is supported */ function isMarketSupported(address tokenAddress) external view returns (bool); /** * @dev Deposit tokens to AssetManager, and those tokens will be passed along to adapters to deposit to integrated asset protocols if any is available. * @param token ERC20 token address * @param amount Deposit amount, in wei * @return Deposited amount */ function deposit(address token, uint256 amount) external returns (bool); /** * @dev Withdraw from AssetManager * @param token ERC20 token address * @param account User address * @param amount Withdraw amount, in wei * @return Withdraw amount */ function withdraw( address token, address account, uint256 amount ) external returns (bool); /** * @dev Add a new ERC20 token to support in AssetManager * @param tokenAddress ERC20 token address */ function addToken(address tokenAddress) external; /** * @dev Remove a ERC20 token to support in AssetManager * @param tokenAddress ERC20 token address */ function removeToken(address tokenAddress) external; /** * @dev Add a new adapter for the underlying lending protocol * @param adapterAddress adapter address */ function addAdapter(address adapterAddress) external; /** * @dev Remove a adapter for the underlying lending protocol * @param adapterAddress adapter address */ function removeAdapter(address adapterAddress) external; /** * @dev For a give token set allowance for all integrated money markets * @param tokenAddress ERC20 token address */ function approveAllMarketsMax(address tokenAddress) external; /** * @dev For a give moeny market set allowance for all underlying tokens * @param adapterAddress Address of adaptor for money market */ function approveAllTokensMax(address adapterAddress) external; /** * @dev Set withdraw sequence * @param newSeq priority sequence of money market indices to be used while withdrawing */ function changeWithdrawSequence(uint256[] calldata newSeq) external; /** * @dev Rebalance the tokens between integrated lending protocols * @param tokenAddress ERC20 token address * @param percentages Proportion */ function rebalance(address tokenAddress, uint256[] calldata percentages) external; /** * @dev Claim the tokens left on AssetManager balance, in case there are tokens get stuck here. * @param tokenAddress ERC20 token address * @param recipient Recipient address */ function claimTokens(address tokenAddress, address recipient) external; /** * @dev Claim the tokens stuck in the integrated adapters * @param index MoneyMarkets array index * @param tokenAddress ERC20 token address * @param recipient Recipient address */ function claimTokensFromAdapter( uint256 index, address tokenAddress, address recipient ) external; /** * @dev Get the number of supported underlying protocols. * @return MoneyMarkets length */ function moneyMarketsCount() external view returns (uint256); /** * @dev Get the count of supported tokens * @return Number of supported tokens */ function supportedTokensCount() external view returns (uint256); /** * @dev Get the supported lending protocol * @param tokenAddress ERC20 token address * @param marketId MoneyMarkets array index * @return tokenSupply */ function getMoneyMarket(address tokenAddress, uint256 marketId) external view returns (uint256, uint256); /** * @dev debt write off * @param tokenAddress ERC20 token address * @param amount WriteOff amount */ function debtWriteOff(address tokenAddress, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title Comptroller Interface * @dev Work with UnionToken and UserManager to calculate the Union rewards based on the staking info from UserManager, and be ready to support multiple UserManagers for various tokens when we support multiple assets. */ interface IComptroller { /** * @dev Get the reward multipier based on the account status * @param account Account address * @return Multiplier number (in wei) */ function getRewardsMultiplier(address account, address token) external view returns (uint256); /** * @dev Withdraw rewards * @return Amount of rewards */ function withdrawRewards(address sender, address token) external returns (uint256); function addFrozenCoinAge( address staker, address token, uint256 lockedStake, uint256 lastRepay ) external; function updateTotalStaked(address token, uint256 totalStaked) external returns (bool); /** * @dev Calculate unclaimed rewards based on blocks * @param account User address * @param futureBlocks Number of blocks in the future * @return Unclaimed rewards */ function calculateRewardsByBlocks( address account, address token, uint256 futureBlocks ) external view returns (uint256); /** * @dev Calculate currently unclaimed rewards * @param account Account address * @return Unclaimed rewards */ function calculateRewards(address account, address token) external view returns (uint256); } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title CreditLimitModel Interface * @dev Calculate the user's credit line based on the trust he receives from the vouchees. */ interface ICreditLimitModel { struct LockedInfo { address staker; uint256 vouchingAmount; uint256 lockedAmount; uint256 availableStakingAmount; } function isCreditLimitModel() external pure returns (bool); function effectiveNumber() external returns (uint256); /** * @notice Calculates the staker locked amount * @return Member credit limit */ function getLockedAmount( LockedInfo[] calldata vouchAmountList, address staker, uint256 amount, bool isIncrease ) external pure returns (uint256); /** * @notice Calculates the member credit limit by vouchs * @return Member credit limit */ function getCreditLimit(uint256[] calldata vouchs) external view returns (uint256); } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; interface IDai { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UToken Interface * @dev Union members can borrow and repay thru this component. */ interface IUToken { /** * @dev Returns the remaining amount that can be borrowed from the market. * @return Remaining total amount */ function getRemainingDebtCeiling() external view returns (uint256); /** * @dev Get the borrowed principle * @param account Member address * @return Borrowed amount */ function getBorrowed(address account) external view returns (uint256); /** * @dev Get the last repay block * @param account Member address * @return Block number */ function getLastRepay(address account) external view returns (uint256); /** * @dev Get member interest index * @param account Member address * @return Interest index */ function getInterestIndex(address account) external view returns (uint256); /** * @dev Check if the member's loan is overdue * @param account Member address * @return Check result */ function checkIsOverdue(address account) external view returns (bool); /** * @dev Get the borrowing interest rate per block * @return Borrow rate */ function borrowRatePerBlock() external view returns (uint256); /** * @dev Get the origination fee * @param amount Amount to be calculated * @return Handling fee */ function calculatingFee(uint256 amount) external view returns (uint256); /** * @dev Calculating member's borrowed interest * @param account Member address * @return Interest amount */ function calculatingInterest(address account) external view returns (uint256); /** * @dev Get a member's current owed balance, including the principle and interest but without updating the user's states. * @param account Member address * @return Borrowed amount */ function borrowBalanceView(address account) external view returns (uint256); /** * @dev Change loan origination fee value * Accept claims only from the admin * @param originationFee_ Fees deducted for each loan transaction */ function setOriginationFee(uint256 originationFee_) external; /** * @dev Update the market debt ceiling to a fixed amount, for example, 1 billion DAI etc. * Accept claims only from the admin * @param debtCeiling_ The debt limit for the whole system */ function setDebtCeiling(uint256 debtCeiling_) external; /** * @dev Update the max loan size * Accept claims only from the admin * @param maxBorrow_ Max loan amount per user */ function setMaxBorrow(uint256 maxBorrow_) external; /** * @dev Update the minimum loan size * Accept claims only from the admin * @param minBorrow_ Minimum loan amount per user */ function setMinBorrow(uint256 minBorrow_) external; /** * @dev Change loan overdue duration, based on the number of blocks * Accept claims only from the admin * @param overdueBlocks_ Maximum late repayment block. The number of arrivals is a default */ function setOverdueBlocks(uint256 overdueBlocks_) external; /** * @dev Change to a different interest rate model * Accept claims only from the admin * @param newInterestRateModel New interest rate model address */ function setInterestRateModel(address newInterestRateModel) external; function setReserveFactor(uint256 reserveFactorMantissa_) external; function supplyRatePerBlock() external returns (uint256); function accrueInterest() external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function mint(uint256 mintAmount) external; function redeem(uint256 redeemTokens) external; function redeemUnderlying(uint256 redeemAmount) external; function addReserves(uint256 addAmount) external; function removeReserves(address receiver, uint256 reduceAmount) external; /** * @dev Borrowing from the market * Accept claims only from the member * Borrow amount must in the range of creditLimit, minLoan, debtCeiling and not overdue * @param amount Borrow amount */ function borrow(uint256 amount) external; /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param amount Repay amount */ function repayBorrow(uint256 amount) external; /** * @dev Repay the loan * Accept claims only from the member * Updated member lastPaymentEpoch only when the repayment amount is greater than interest * @param borrower Borrower address * @param amount Repay amount */ function repayBorrowBehalf(address borrower, uint256 amount) external; /** * @dev Update borrower overdue info * @param account Borrower address */ function updateOverdueInfo(address account) external; /** * @dev debt write off * @param borrower Borrower address * @param amount WriteOff amount */ function debtWriteOff(address borrower, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UnionToken Interface * @dev Mint and distribute UnionTokens. */ interface IUnionToken { /** * @dev Get total supply * @return Total supply */ function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint256 amount) external returns (bool); /** * @dev Determine the prior number of votes for an account as of a block number. Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); /** * @dev Allows to spend owner's Union tokens by the specified spender. * The function can be called by anyone, but requires having allowance parameters * signed by the owner according to EIP712. * @param owner The owner's address, cannot be zero address. * @param spender The spender's address, cannot be zero address. * @param value The allowance amount, in wei. * @param deadline The allowance expiration date (unix timestamp in UTC). * @param v A final byte of signature (ECDSA component). * @param r The first 32 bytes of signature (ECDSA component). * @param s The second 32 bytes of signature (ECDSA component). */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function burnFrom(address account, uint256 amount) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; /** * @title UserManager Interface * @dev Manages the Union members credit lines, and their vouchees and borrowers info. */ interface IUserManager { /** * @dev Check if the account is a valid member * @param account Member address * @return Address whether is member */ function checkIsMember(address account) external view returns (bool); /** * @dev Get member borrowerAddresses * @param account Member address * @return Address array */ function getBorrowerAddresses(address account) external view returns (address[] memory); /** * @dev Get member stakerAddresses * @param account Member address * @return Address array */ function getStakerAddresses(address account) external view returns (address[] memory); /** * @dev Get member backer asset * @param account Member address * @param borrower Borrower address * @return Trust amount, vouch amount, and locked stake amount */ function getBorrowerAsset(address account, address borrower) external view returns ( uint256, uint256, uint256 ); /** * @dev Get member stakers asset * @param account Member address * @param staker Staker address * @return Vouch amount and lockedStake */ function getStakerAsset(address account, address staker) external view returns ( uint256, uint256, uint256 ); /** * @dev Get the member's available credit line * @param account Member address * @return Limit */ function getCreditLimit(address account) external view returns (int256); function totalStaked() external view returns (uint256); function totalFrozen() external view returns (uint256); function getFrozenCoinAge(address staker, uint256 pastBlocks) external view returns (uint256); /** * @dev Add a new member * Accept claims only from the admin * @param account Member address */ function addMember(address account) external; /** * @dev Update the trust amount for exisitng members. * @param borrower Borrower address * @param trustAmount Trust amount */ function updateTrust(address borrower, uint256 trustAmount) external; /** * @dev Apply for membership, and burn UnionToken as application fees * @param newMember New member address */ function registerMember(address newMember) external; /** * @dev Stop vouch for other member. * @param staker Staker address * @param account Account address */ function cancelVouch(address staker, address account) external; /** * @dev Change the credit limit model * Accept claims only from the admin * @param newCreditLimitModel New credit limit model address */ function setCreditLimitModel(address newCreditLimitModel) external; /** * @dev Get the user's locked stake from all his backed loans * @param staker Staker address * @return LockedStake */ function getTotalLockedStake(address staker) external view returns (uint256); /** * @dev Get staker's defaulted / frozen staked token amount * @param staker Staker address * @return Frozen token amount */ function getTotalFrozenAmount(address staker) external view returns (uint256); /** * @dev Update userManager locked info * @param borrower Borrower address * @param amount Borrow or repay amount(Including previously accrued interest) * @param isBorrow True is borrow, false is repay */ function updateLockedData( address borrower, uint256 amount, bool isBorrow ) external; /** * @dev Get the user's deposited stake amount * @param account Member address * @return Deposited stake amount */ function getStakerBalance(address account) external view returns (uint256); /** * @dev Stake * @param amount Amount */ function stake(uint256 amount) external; /** * @dev Unstake * @param amount Amount */ function unstake(uint256 amount) external; /** * @dev Update total frozen * @param account borrower address * @param isOverdue account is overdue */ function updateTotalFrozen(address account, bool isOverdue) external; function batchUpdateTotalFrozen(address[] calldata account, bool[] calldata isOverdue) external; /** * @dev Repay user's loan overdue, called only from the lending market * @param account User address * @param lastRepay Last repay block number */ function repayLoanOverdue( address account, address token, uint256 lastRepay ) external; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../Controller.sol"; import "../interfaces/IAssetManager.sol"; import "../interfaces/ICreditLimitModel.sol"; import "../interfaces/IUserManager.sol"; import "../interfaces/IComptroller.sol"; import "../interfaces/IUnionToken.sol"; import "../interfaces/IDai.sol"; import "../interfaces/IUToken.sol"; /** * @title UserManager Contract * @dev Manages the Union members credit lines, and their vouchees and borrowers info. */ contract UserManager is Controller, IUserManager, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; struct Member { bool isMember; CreditLine creditLine; } //address: member address, uint256: trustAmount struct CreditLine { mapping(address => uint256) borrowers; address[] borrowerAddresses; mapping(address => uint256) stakers; address[] stakerAddresses; mapping(address => uint256) lockedAmount; } struct TrustInfo { address[] stakerAddresses; address[] borrowerAddresses; uint256 effectiveCount; address staker; uint256 vouchingAmount; uint256 stakingAmount; uint256 availableStakingAmount; uint256 lockedStake; uint256 totalLockedStake; } uint256 public constant MAX_TRUST_LIMIT = 100; uint256 public maxStakeAmount; address public stakingToken; address public unionToken; address public assetManager; IUToken public uToken; ICreditLimitModel public creditLimitModel; IComptroller public comptroller; uint256 public newMemberFee; // New member application fee // slither-disable-next-line constable-states uint256 public override totalStaked; // slither-disable-next-line constable-states uint256 public override totalFrozen; mapping(address => Member) private members; // slither-disable-next-line uninitialized-state mapping(address => uint256) public stakers; //1 user address 2 amount mapping(address => uint256) public memberFrozen; //1 user address 2 frozen amount error AddressZero(); error AmountZero(); error ErrorData(); error AuthFailed(); error NotCreditLimitModel(); error ErrorSelfVouching(); error MaxTrustLimitReached(); error TrustAmountTooLarge(); error LockedStakeNonZero(); error NoExistingMember(); error NotEnoughStakers(); error StakeLimitReached(); error AssetManagerDepositFailed(); error AssetManagerWithdrawFailed(); error InsufficientBalance(); error ExceedsTotalStaked(); error NotOverdue(); error ExceedsLocked(); error ExceedsTotalFrozen(); error LengthNotMatch(); error ErrorTotalStake(); modifier onlyMember(address account) { if (!checkIsMember(account)) revert AuthFailed(); _; } modifier onlyMarketOrAdmin() { if (address(uToken) != msg.sender && !isAdmin(msg.sender)) revert AuthFailed(); _; } /** * @dev Update new credit limit model event * @param newCreditLimitModel New credit limit model address */ event LogNewCreditLimitModel(address newCreditLimitModel); /** * @dev Add new member event * @param member New member address */ event LogAddMember(address member); /** * @dev Update vouch for existing member event * @param staker Trustee address * @param borrower The address gets vouched for * @param trustAmount Vouch amount */ event LogUpdateTrust(address indexed staker, address indexed borrower, uint256 trustAmount); /** * @dev New member application event * @param account New member's voucher address * @param borrower New member address */ event LogRegisterMember(address indexed account, address indexed borrower); /** * @dev Cancel vouching for other member event * @param account New member's voucher address * @param borrower The address gets vouched for */ event LogCancelVouch(address indexed account, address indexed borrower); /** * @dev Stake event * @param account The staker's address * @param amount The amount of tokens to stake */ event LogStake(address indexed account, uint256 amount); /** * @dev Unstake event * @param account The staker's address * @param amount The amount of tokens to unstake */ event LogUnstake(address indexed account, uint256 amount); /** * @dev DebtWriteOff event * @param staker The staker's address * @param borrower The borrower's address * @param amount The amount of write off */ event LogDebtWriteOff(address indexed staker, address indexed borrower, uint256 amount); /** * @dev set utoken address * @param uToken new uToken address */ event LogSetUToken(address uToken); /** * @dev set new member fee * @param oldMemberFee old member fee * @param newMemberFee new member fee */ event LogSetNewMemberFee(uint256 oldMemberFee, uint256 newMemberFee); event LogSetMaxStakeAmount(uint256 oldMaxStakeAmount, uint256 newMaxStakeAmount); function __UserManager_init( address assetManager_, address unionToken_, address stakingToken_, address creditLimitModel_, address comptroller_, address admin_ ) public initializer { Controller.__Controller_init(admin_); ReentrancyGuardUpgradeable.__ReentrancyGuard_init(); _setCreditLimitModel(creditLimitModel_); comptroller = IComptroller(comptroller_); assetManager = assetManager_; unionToken = unionToken_; stakingToken = stakingToken_; newMemberFee = 10**18; // Set the default membership fee maxStakeAmount = 5000e18; } function setMaxStakeAmount(uint256 maxStakeAmount_) public onlyAdmin { uint256 oldMaxStakeAmount = maxStakeAmount; maxStakeAmount = maxStakeAmount_; emit LogSetMaxStakeAmount(oldMaxStakeAmount, maxStakeAmount); } function setUToken(address uToken_) public onlyAdmin { if (uToken_ == address(0)) revert AddressZero(); uToken = IUToken(uToken_); emit LogSetUToken(uToken_); } function setNewMemberFee(uint256 amount) public onlyAdmin { uint256 oldMemberFee = newMemberFee; newMemberFee = amount; emit LogSetNewMemberFee(oldMemberFee, newMemberFee); } /** * @dev Change the credit limit model * Accept claims only from the admin * @param newCreditLimitModel New credit limit model address */ function setCreditLimitModel(address newCreditLimitModel) public override onlyAdmin { if (newCreditLimitModel == address(0)) revert AddressZero(); _setCreditLimitModel(newCreditLimitModel); } function _setCreditLimitModel(address newCreditLimitModel) private { if (!ICreditLimitModel(newCreditLimitModel).isCreditLimitModel()) revert NotCreditLimitModel(); creditLimitModel = ICreditLimitModel(newCreditLimitModel); emit LogNewCreditLimitModel(newCreditLimitModel); } /** * @dev Check if the account is a valid member * @param account Member address * @return Address whether is member */ function checkIsMember(address account) public view override returns (bool) { return members[account].isMember; } /** * @dev Get member borrowerAddresses * @param account Member address * @return Address array */ function getBorrowerAddresses(address account) public view override returns (address[] memory) { return members[account].creditLine.borrowerAddresses; } /** * @dev Get member stakerAddresses * @param account Member address * @return Address array */ function getStakerAddresses(address account) public view override returns (address[] memory) { return members[account].creditLine.stakerAddresses; } /** * @dev Get member backer asset * @param account Member address * @param borrower Borrower address * @return trustAmount vouchingAmount lockedStake. Trust amount, vouch amount, and locked stake amount */ function getBorrowerAsset(address account, address borrower) public view override returns ( uint256 trustAmount, uint256 vouchingAmount, uint256 lockedStake ) { trustAmount = members[account].creditLine.borrowers[borrower]; lockedStake = getLockedStake(account, borrower); vouchingAmount = getVouchingAmount(account, borrower); } /** * @dev Get member stakers asset * @param account Member address * @param staker Staker address * @return trustAmount lockedStake vouchingAmount. Vouch amount and lockedStake */ function getStakerAsset(address account, address staker) public view override returns ( uint256 trustAmount, uint256 vouchingAmount, uint256 lockedStake ) { trustAmount = members[account].creditLine.stakers[staker]; lockedStake = getLockedStake(staker, account); vouchingAmount = getVouchingAmount(staker, account); } /** * @dev Get staker locked stake for a borrower * @param staker Staker address * @param borrower Borrower address * @return LockedStake */ function getLockedStake(address staker, address borrower) public view returns (uint256) { return members[staker].creditLine.lockedAmount[borrower]; } /** * @dev Get the user's locked stake from all his backed loans * @param staker Staker address * @return LockedStake */ function getTotalLockedStake(address staker) public view override returns (uint256) { uint256 totalLockedStake = 0; uint256 stakingAmount = stakers[staker]; address[] memory borrowerAddresses = members[staker].creditLine.borrowerAddresses; address borrower; uint256 addressesLength = borrowerAddresses.length; for (uint256 i = 0; i < addressesLength; i++) { borrower = borrowerAddresses[i]; totalLockedStake += getLockedStake(staker, borrower); } if (stakingAmount >= totalLockedStake) { return totalLockedStake; } else { return stakingAmount; } } /** * @dev Get staker's defaulted / frozen staked token amount * @param staker Staker address * @return Frozen token amount */ function getTotalFrozenAmount(address staker) public view override returns (uint256) { TrustInfo memory trustInfo; uint256 totalFrozenAmount = 0; trustInfo.borrowerAddresses = members[staker].creditLine.borrowerAddresses; trustInfo.stakingAmount = stakers[staker]; address borrower; uint256 addressLength = trustInfo.borrowerAddresses.length; for (uint256 i = 0; i < addressLength; i++) { borrower = trustInfo.borrowerAddresses[i]; if (uToken.checkIsOverdue(borrower)) { totalFrozenAmount += getLockedStake(staker, borrower); } } if (trustInfo.stakingAmount >= totalFrozenAmount) { return totalFrozenAmount; } else { return trustInfo.stakingAmount; } } /** * @dev Get the member's available credit line * @param borrower Member address * @return Credit line amount */ function getCreditLimit(address borrower) public view override returns (int256) { TrustInfo memory trustInfo; trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses; // Get the number of effective vouchee, first trustInfo.effectiveCount = 0; uint256 stakerAddressesLength = trustInfo.stakerAddresses.length; uint256[] memory limits = new uint256[](stakerAddressesLength); for (uint256 i = 0; i < stakerAddressesLength; i++) { trustInfo.staker = trustInfo.stakerAddresses[i]; trustInfo.stakingAmount = stakers[trustInfo.staker]; trustInfo.vouchingAmount = getVouchingAmount(trustInfo.staker, borrower); //A vouchingAmount value of 0 means that the amount of stake is 0 or trust is 0. In this case, this data is not used to calculate the credit limit if (trustInfo.vouchingAmount > 0) { //availableStakingAmount is staker‘s free stake amount trustInfo.borrowerAddresses = getBorrowerAddresses(trustInfo.staker); trustInfo.availableStakingAmount = trustInfo.stakingAmount; uint256 totalLockedStake = getTotalLockedStake(trustInfo.staker); if (trustInfo.stakingAmount <= totalLockedStake) { trustInfo.availableStakingAmount = 0; } else { trustInfo.availableStakingAmount = trustInfo.stakingAmount - totalLockedStake; } trustInfo.lockedStake = getLockedStake(trustInfo.staker, borrower); if (trustInfo.vouchingAmount < trustInfo.lockedStake) revert ErrorData(); //The actual effective guarantee amount cannot exceed availableStakingAmount, if (trustInfo.vouchingAmount >= trustInfo.availableStakingAmount + trustInfo.lockedStake) { limits[trustInfo.effectiveCount] = trustInfo.availableStakingAmount; } else { if (trustInfo.vouchingAmount <= trustInfo.lockedStake) { limits[trustInfo.effectiveCount] = 0; } else { limits[trustInfo.effectiveCount] = trustInfo.vouchingAmount - trustInfo.lockedStake; } } trustInfo.effectiveCount += 1; } } uint256[] memory creditlimits = new uint256[](trustInfo.effectiveCount); for (uint256 j = 0; j < trustInfo.effectiveCount; j++) { creditlimits[j] = limits[j]; } return int256(creditLimitModel.getCreditLimit(creditlimits)) - int256(uToken.calculatingInterest(borrower)); } /** * @dev Get vouching amount * @param staker Staker address * @param borrower Borrower address */ function getVouchingAmount(address staker, address borrower) public view returns (uint256) { uint256 totalStake = stakers[staker]; uint256 trustAmount = members[borrower].creditLine.stakers[staker]; return trustAmount > totalStake ? totalStake : trustAmount; } /** * @dev Get the user's deposited stake amount * @param account Member address * @return Deposited stake amount */ function getStakerBalance(address account) public view override returns (uint256) { return stakers[account]; } /** * @dev Add member * Accept claims only from the admin * @param account Member address */ function addMember(address account) public override onlyAdmin { members[account].isMember = true; emit LogAddMember(account); } /** * @dev Update the trust amount for exisitng members. * @param borrower_ Account address * @param trustAmount Trust amount */ function updateTrust(address borrower_, uint256 trustAmount) external override onlyMember(msg.sender) whenNotPaused { if (borrower_ == address(0)) revert AddressZero(); address borrower = borrower_; TrustInfo memory trustInfo; trustInfo.staker = msg.sender; if (trustInfo.staker == borrower) revert ErrorSelfVouching(); if ( members[borrower].creditLine.stakerAddresses.length >= MAX_TRUST_LIMIT || members[trustInfo.staker].creditLine.borrowerAddresses.length >= MAX_TRUST_LIMIT ) revert MaxTrustLimitReached(); trustInfo.borrowerAddresses = members[trustInfo.staker].creditLine.borrowerAddresses; trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses; trustInfo.lockedStake = getLockedStake(trustInfo.staker, borrower); if (trustAmount < trustInfo.lockedStake) revert TrustAmountTooLarge(); uint256 borrowerCount = members[trustInfo.staker].creditLine.borrowerAddresses.length; bool borrowerExist = false; for (uint256 i = 0; i < borrowerCount; i++) { if (trustInfo.borrowerAddresses[i] == borrower) { borrowerExist = true; break; } } uint256 stakerCount = members[borrower].creditLine.stakerAddresses.length; bool stakerExist = false; for (uint256 i = 0; i < stakerCount; i++) { if (trustInfo.stakerAddresses[i] == trustInfo.staker) { stakerExist = true; break; } } if (!borrowerExist) { members[trustInfo.staker].creditLine.borrowerAddresses.push(borrower); } if (!stakerExist) { members[borrower].creditLine.stakerAddresses.push(trustInfo.staker); } members[trustInfo.staker].creditLine.borrowers[borrower] = trustAmount; members[borrower].creditLine.stakers[trustInfo.staker] = trustAmount; emit LogUpdateTrust(trustInfo.staker, borrower, trustAmount); } /** * @dev Stop vouch for other member. * @param staker Staker address * @param borrower borrower address */ function cancelVouch(address staker, address borrower) external override onlyMember(msg.sender) whenNotPaused { if (msg.sender != staker && msg.sender != borrower) revert AuthFailed(); if (getLockedStake(staker, borrower) != 0) revert LockedStakeNonZero(); uint256 stakerCount = members[borrower].creditLine.stakerAddresses.length; bool stakerExist = false; uint256 stakerIndex = 0; for (uint256 i = 0; i < stakerCount; i++) { if (members[borrower].creditLine.stakerAddresses[i] == staker) { stakerExist = true; stakerIndex = i; break; } } uint256 borrowerCount = members[staker].creditLine.borrowerAddresses.length; bool borrowerExist = false; uint256 borrowerIndex = 0; for (uint256 i = 0; i < borrowerCount; i++) { if (members[staker].creditLine.borrowerAddresses[i] == borrower) { borrowerExist = true; borrowerIndex = i; break; } } //delete address if (borrowerExist) { members[staker].creditLine.borrowerAddresses[borrowerIndex] = members[staker].creditLine.borrowerAddresses[ borrowerCount - 1 ]; members[staker].creditLine.borrowerAddresses.pop(); } if (stakerExist) { members[borrower].creditLine.stakerAddresses[stakerIndex] = members[borrower].creditLine.stakerAddresses[ stakerCount - 1 ]; members[borrower].creditLine.stakerAddresses.pop(); } delete members[staker].creditLine.borrowers[borrower]; delete members[borrower].creditLine.stakers[staker]; emit LogCancelVouch(staker, borrower); } function registerMemberWithPermit( address newMember, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public whenNotPaused { IUnionToken unionTokenContract = IUnionToken(unionToken); unionTokenContract.permit(msg.sender, address(this), value, deadline, v, r, s); registerMember(newMember); } /** * @dev Apply for membership, and burn UnionToken as application fees * @param newMember New member address */ function registerMember(address newMember) public override whenNotPaused { if (checkIsMember(newMember)) revert NoExistingMember(); IUnionToken unionTokenContract = IUnionToken(unionToken); uint256 effectiveStakerNumber = 0; address stakerAddress; uint256 addressesLength = members[newMember].creditLine.stakerAddresses.length; for (uint256 i = 0; i < addressesLength; i++) { stakerAddress = members[newMember].creditLine.stakerAddresses[i]; if (checkIsMember(stakerAddress) && getVouchingAmount(stakerAddress, newMember) > 0) effectiveStakerNumber += 1; } if (effectiveStakerNumber < creditLimitModel.effectiveNumber()) revert NotEnoughStakers(); members[newMember].isMember = true; unionTokenContract.burnFrom(msg.sender, newMemberFee); emit LogRegisterMember(msg.sender, newMember); } function updateLockedData( address borrower, uint256 amount, bool isBorrow ) external override onlyMarketOrAdmin { TrustInfo memory trustInfo; trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses; ICreditLimitModel.LockedInfo[] memory lockedInfoList = new ICreditLimitModel.LockedInfo[]( trustInfo.stakerAddresses.length ); uint256 addressesLength = trustInfo.stakerAddresses.length; for (uint256 i = 0; i < addressesLength; i++) { ICreditLimitModel.LockedInfo memory lockedInfo; trustInfo.staker = trustInfo.stakerAddresses[i]; trustInfo.stakingAmount = stakers[trustInfo.staker]; trustInfo.vouchingAmount = getVouchingAmount(trustInfo.staker, borrower); trustInfo.totalLockedStake = getTotalLockedStake(trustInfo.staker); if (trustInfo.stakingAmount <= trustInfo.totalLockedStake) { trustInfo.availableStakingAmount = 0; } else { trustInfo.availableStakingAmount = trustInfo.stakingAmount - trustInfo.totalLockedStake; } lockedInfo.staker = trustInfo.staker; lockedInfo.vouchingAmount = trustInfo.vouchingAmount; lockedInfo.lockedAmount = getLockedStake(trustInfo.staker, borrower); lockedInfo.availableStakingAmount = trustInfo.availableStakingAmount; lockedInfoList[i] = lockedInfo; } uint256 lockedInfoListLength = lockedInfoList.length; for (uint256 i = 0; i < lockedInfoListLength; i++) { members[lockedInfoList[i].staker].creditLine.lockedAmount[borrower] = creditLimitModel.getLockedAmount( lockedInfoList, lockedInfoList[i].staker, amount, isBorrow ); } } /** * @dev Stake * @param amount Amount */ function stake(uint256 amount) public override whenNotPaused nonReentrant { IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken); comptroller.withdrawRewards(msg.sender, stakingToken); uint256 balance = stakers[msg.sender]; if (balance + amount > maxStakeAmount) revert StakeLimitReached(); stakers[msg.sender] = balance + amount; totalStaked += amount; erc20Token.safeTransferFrom(msg.sender, address(this), amount); erc20Token.safeApprove(assetManager, 0); erc20Token.safeApprove(assetManager, amount); if (!IAssetManager(assetManager).deposit(stakingToken, amount)) revert AssetManagerDepositFailed(); emit LogStake(msg.sender, amount); } /** * @dev stakeWithPermit * @param amount Amount */ function stakeWithPermit( uint256 amount, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public whenNotPaused { IDai erc20Token = IDai(stakingToken); erc20Token.permit(msg.sender, address(this), nonce, expiry, true, v, r, s); stake(amount); } /** * @dev Unstake * @param amount Amount */ function unstake(uint256 amount) external override whenNotPaused nonReentrant { IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken); uint256 stakingAmount = stakers[msg.sender]; if (stakingAmount - getTotalLockedStake(msg.sender) < amount) revert InsufficientBalance(); comptroller.withdrawRewards(msg.sender, stakingToken); stakers[msg.sender] = stakingAmount - amount; totalStaked -= amount; if (!IAssetManager(assetManager).withdraw(stakingToken, address(this), amount)) revert AssetManagerWithdrawFailed(); erc20Token.safeTransfer(msg.sender, amount); emit LogUnstake(msg.sender, amount); } function withdrawRewards() external whenNotPaused nonReentrant { comptroller.withdrawRewards(msg.sender, stakingToken); } /** * @dev Repay user's loan overdue, called only from the lending market * @param account User address * @param token The asset token repaying to * @param lastRepay Last repay block number */ function repayLoanOverdue( address account, address token, uint256 lastRepay ) external override whenNotPaused onlyMarketOrAdmin { address[] memory stakerAddresses = getStakerAddresses(account); uint256 addressesLength; for (uint256 i = 0; i < addressesLength; i++) { address staker = stakerAddresses[i]; (, , uint256 lockedStake) = getStakerAsset(account, staker); comptroller.addFrozenCoinAge(staker, token, lockedStake, lastRepay); } } //Only supports sumOfTrust function debtWriteOff(address borrower, uint256 amount) public { if (amount == 0) revert AmountZero(); if (amount > totalStaked) revert ExceedsTotalStaked(); if (!uToken.checkIsOverdue(borrower)) revert NotOverdue(); uint256 lockedAmount = getLockedStake(msg.sender, borrower); if (amount > lockedAmount) revert ExceedsLocked(); _updateTotalFrozen(borrower, true); if (amount > totalFrozen) revert ExceedsTotalFrozen(); comptroller.withdrawRewards(msg.sender, stakingToken); //The borrower is still overdue, do not call comptroller.addFrozenCoinAge stakers[msg.sender] -= amount; totalStaked -= amount; totalFrozen -= amount; if (memberFrozen[borrower] >= amount) { memberFrozen[borrower] -= amount; } else { memberFrozen[borrower] = 0; } members[msg.sender].creditLine.lockedAmount[borrower] = lockedAmount - amount; uint256 trustAmount = members[msg.sender].creditLine.borrowers[borrower]; uint256 newTrustAmount = trustAmount - amount; members[msg.sender].creditLine.borrowers[borrower] = newTrustAmount; members[borrower].creditLine.stakers[msg.sender] = newTrustAmount; IAssetManager(assetManager).debtWriteOff(stakingToken, amount); uToken.debtWriteOff(borrower, amount); emit LogDebtWriteOff(msg.sender, borrower, amount); } /** * @dev Update total frozen * @param account borrower address * @param isOverdue account is overdue */ function updateTotalFrozen(address account, bool isOverdue) external override onlyMarketOrAdmin whenNotPaused { if (totalStaked < totalFrozen) revert ErrorTotalStake(); uint256 effectiveTotalStaked = totalStaked - totalFrozen; comptroller.updateTotalStaked(stakingToken, effectiveTotalStaked); _updateTotalFrozen(account, isOverdue); } function batchUpdateTotalFrozen(address[] calldata accounts, bool[] calldata isOverdues) external override onlyMarketOrAdmin whenNotPaused { if (accounts.length != isOverdues.length) revert LengthNotMatch(); if (totalStaked < totalFrozen) revert ErrorTotalStake(); uint256 effectiveTotalStaked = totalStaked - totalFrozen; comptroller.updateTotalStaked(stakingToken, effectiveTotalStaked); for (uint256 i = 0; i < accounts.length; i++) { if (accounts[i] != address(0)) _updateTotalFrozen(accounts[i], isOverdues[i]); } } function _updateTotalFrozen(address account, bool isOverdue) private { if (isOverdue) { //isOverdue = true, user overdue needs to increase totalFrozen //The sum of the locked amount of all stakers on this borrower, which is the frozen amount that needs to be updated uint256 amount; for (uint256 i = 0; i < members[account].creditLine.stakerAddresses.length; i++) { address staker = members[account].creditLine.stakerAddresses[i]; uint256 lockedStake = getLockedStake(staker, account); amount += lockedStake; } if (memberFrozen[account] == 0) { //I haven’t updated the frozen amount about this borrower before, just increase the amount directly totalFrozen += amount; } else { //I have updated the frozen amount of this borrower before. After increasing the amount, subtract the previously increased value to avoid repeated additions. totalFrozen = totalFrozen + amount - memberFrozen[account]; } //Record the increased value of this borrower this time memberFrozen[account] = amount; } else { //isOverdue = false, the user loan needs to reduce the number of frozen last time to return to normal if (totalFrozen > memberFrozen[account]) { //Minus the frozen amount added last time totalFrozen -= memberFrozen[account]; } else { totalFrozen = 0; } memberFrozen[account] = 0; } } function getFrozenCoinAge(address staker, uint256 pastBlocks) public view override returns (uint256) { uint256 totalFrozenCoinAge = 0; address[] memory borrowerAddresses = getBorrowerAddresses(staker); uint256 addressLength = borrowerAddresses.length; for (uint256 i = 0; i < addressLength; i++) { address borrower = borrowerAddresses[i]; uint256 blocks = block.number - uToken.getLastRepay(borrower); if (uToken.checkIsOverdue(borrower)) { (, , uint256 lockedStake) = getStakerAsset(borrower, staker); if (pastBlocks >= blocks) { totalFrozenCoinAge = totalFrozenCoinAge + (lockedStake * blocks); } else { totalFrozenCoinAge = totalFrozenCoinAge + (lockedStake * pastBlocks); } } } return totalFrozenCoinAge; } }
Get total supply return Total supply/ Determine the prior number of votes for an account as of a block number. Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ Allows to spend owner's Union tokens by the specified spender. The function can be called by anyone, but requires having allowance parameters signed by the owner according to EIP712. owner The owner's address, cannot be zero address. spender The spender's address, cannot be zero address. value The allowance amount, in wei. deadline The allowance expiration date (unix timestamp in UTC). v A final byte of signature (ECDSA component). r The first 32 bytes of signature (ECDSA component). s The second 32 bytes of signature (ECDSA component)./SPDX-License-Identifier: UNLICENSED UserManager Interface Manages the Union members credit lines, and their vouchees and borrowers info./
interface IUserManager { function checkIsMember(address account) external view returns (bool); function getBorrowerAddresses(address account) external view returns (address[] memory); function getStakerAddresses(address account) external view returns (address[] memory); function getBorrowerAsset(address account, address borrower) external view returns ( uint256, uint256, uint256 ); function getStakerAsset(address account, address staker) external view returns ( uint256, uint256, uint256 ); function getCreditLimit(address account) external view returns (int256); function totalStaked() external view returns (uint256); function totalFrozen() external view returns (uint256); function getFrozenCoinAge(address staker, uint256 pastBlocks) external view returns (uint256); function addMember(address account) external; function updateTrust(address borrower, uint256 trustAmount) external; function registerMember(address newMember) external; function cancelVouch(address staker, address account) external; function setCreditLimitModel(address newCreditLimitModel) external; function getTotalLockedStake(address staker) external view returns (uint256); function getTotalFrozenAmount(address staker) external view returns (uint256); function updateLockedData( address borrower, uint256 amount, bool isBorrow ) external; function getStakerBalance(address account) external view returns (uint256); function stake(uint256 amount) external; function unstake(uint256 amount) external; function updateTotalFrozen(address account, bool isOverdue) external; function batchUpdateTotalFrozen(address[] calldata account, bool[] calldata isOverdue) external; function repayLoanOverdue( address account, address token, uint256 lastRepay ) external; }
528,771
./full_match/8453/0xF3377062069d0C3E86dd553cC22a6Fcc2B3306a5/sources/IERC20.sol
Interface of the TRC20 standard as defined in the EIP. Does not include the optional functions; to access them see {TRC20Detailed}./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity ^0.8.1; }
11,560,536
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; /// @title: David Ariew X Tatler China import "../ERC721ProjectUpgradeable.sol"; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // '########:::::'###::::'##::::'##:'####:'########::::::::'###::::'########::'####:'########:'##:::::'##::::'##::::'##::::'########::::'###::::'########:'##:::::::'########:'########::::::'######::'##::::'##:'####:'##::: ##::::'###:::: // // ##.... ##:::'## ##::: ##:::: ##:. ##:: ##.... ##::::::'## ##::: ##.... ##:. ##:: ##.....:: ##:'##: ##::::. ##::'##:::::... ##..::::'## ##:::... ##..:: ##::::::: ##.....:: ##.... ##::::'##... ##: ##:::: ##:. ##:: ###:: ##:::'## ##::: // // ##:::: ##::'##:. ##:: ##:::: ##:: ##:: ##:::: ##:::::'##:. ##:: ##:::: ##:: ##:: ##::::::: ##: ##: ##:::::. ##'##::::::::: ##:::::'##:. ##::::: ##:::: ##::::::: ##::::::: ##:::: ##:::: ##:::..:: ##:::: ##:: ##:: ####: ##::'##:. ##:: // // ##:::: ##:'##:::. ##: ##:::: ##:: ##:: ##:::: ##::::'##:::. ##: ########::: ##:: ######::: ##: ##: ##::::::. ###:::::::::: ##::::'##:::. ##:::: ##:::: ##::::::: ######::: ########::::: ##::::::: #########:: ##:: ## ## ##:'##:::. ##: // // ##:::: ##: #########:. ##:: ##::: ##:: ##:::: ##:::: #########: ##.. ##:::: ##:: ##...:::: ##: ##: ##:::::: ## ##::::::::: ##:::: #########:::: ##:::: ##::::::: ##...:::: ##.. ##:::::: ##::::::: ##.... ##:: ##:: ##. ####: #########: // // ##:::: ##: ##.... ##::. ## ##:::: ##:: ##:::: ##:::: ##.... ##: ##::. ##::: ##:: ##::::::: ##: ##: ##::::: ##:. ##:::::::: ##:::: ##.... ##:::: ##:::: ##::::::: ##::::::: ##::. ##::::: ##::: ##: ##:::: ##:: ##:: ##:. ###: ##.... ##: // // ########:: ##:::: ##:::. ###::::'####: ########::::: ##:::: ##: ##:::. ##:'####: ########:. ###. ###::::: ##:::. ##::::::: ##:::: ##:::: ##:::: ##:::: ########: ########: ##:::. ##::::. ######:: ##:::: ##:'####: ##::. ##: ##:::: ##: // // ........:::..:::::..:::::...:::::....::........::::::..:::::..::..:::::..::....::........:::...::...::::::..:::::..::::::::..:::::..:::::..:::::..:::::........::........::..:::::..::::::......:::..:::::..::....::..::::..::..:::::..:: // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// contract DavidAriewXTatlerChina is ERC721ProjectUpgradeable { /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() public initializer { _initialize("David Ariew X Tatler China", "DavidAriewXTatlerChina"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "./access/AdminControlUpgradeable.sol"; import "./core/ERC721ProjectCoreUpgradeable.sol"; /** * @dev ERC721Project implementation */ abstract contract ERC721ProjectUpgradeable is Initializable, AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable, UUPSUpgradeable { function _initialize(string memory _name, string memory _symbol) internal initializer { __AdminControl_init(); __ERC721_init(_name, _symbol); __ERC721ProjectCore_init(); __UUPSUpgradeable_init(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { _approveTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IProjectCore-registerManager}. */ function registerManager(address manager, string calldata baseURI) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, false); } /** * @dev See {IProjectCore-registerManager}. */ function registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) external override adminRequired nonBlacklistRequired(manager) { _registerManager(manager, baseURI, baseURIIdentical); } /** * @dev See {IProjectCore-unregisterManager}. */ function unregisterManager(address manager) external override adminRequired { _unregisterManager(manager); } /** * @dev See {IProjectCore-blacklistManager}. */ function blacklistManager(address manager) external override adminRequired { _blacklistManager(manager); } /** * @dev See {IProjectCore-managerSetBaseTokenURI}. */ function managerSetBaseTokenURI(string calldata uri) external override managerRequired { _managerSetBaseTokenURI(uri, false); } /** * @dev See {IProjectCore-managerSetBaseTokenURI}. */ function managerSetBaseTokenURI(string calldata uri, bool identical) external override managerRequired { _managerSetBaseTokenURI(uri, identical); } /** * @dev See {IProjectCore-managerSetTokenURIPrefix}. */ function managerSetTokenURIPrefix(string calldata prefix) external override managerRequired { _managerSetTokenURIPrefix(prefix); } /** * @dev See {IProjectCore-managerSetTokenURI}. */ function managerSetTokenURI(uint256 tokenId, string calldata uri) external override managerRequired { _managerSetTokenURI(tokenId, uri); } /** * @dev See {IProjectCore-managerSetTokenURI}. */ function managerSetTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override managerRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _managerSetTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {IProjectCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri) external override adminRequired { _setBaseTokenURI(uri); } /** * @dev See {IProjectCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {IProjectCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired { _setTokenURI(tokenId, uri); } /** * @dev See {IProjectCore-setTokenURI}. */ function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {IProjectCore-setMintPermissions}. */ function setMintPermissions(address manager, address permissions) external override adminRequired { _setMintPermissions(manager, permissions); } /** * @dev See {IERC721ProjectCore-adminMint}. */ function adminMint(address to, string calldata uri) external virtual override nonReentrant adminRequired returns (uint256) { return _adminMint(to, uri); } /** * @dev See {IERC721ProjectCore-adminMintBatch}. */ function adminMintBatch(address to, uint16 count) external virtual override nonReentrant adminRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _adminMint(to, ""); } return tokenIds; } /** * @dev See {IERC721ProjectCore-adminMintBatch}. */ function adminMintBatch(address to, string[] calldata uris) external virtual override nonReentrant adminRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint256 i = 0; i < uris.length; i++) { tokenIds[i] = _adminMint(to, uris[i]); } return tokenIds; } /** * @dev Mint token with no manager */ function _adminMint(address to, string memory uri) internal virtual returns (uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; // Track the manager that minted the token _tokensManager[tokenId] = address(this); _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintBase(to, tokenId); return tokenId; } /** * @dev See {IERC721ProjectCore-managerMint}. */ function managerMint(address to, string calldata uri) external virtual override nonReentrant managerRequired returns (uint256) { return _managerMint(to, uri); } /** * @dev See {IERC721ProjectCore-managerMintBatch}. */ function managerMintBatch(address to, uint16 count) external virtual override nonReentrant managerRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _managerMint(to, ""); } return tokenIds; } /** * @dev See {IERC721ProjectCore-managerMintBatch}. */ function managerMintBatch(address to, string[] calldata uris) external virtual override nonReentrant managerRequired returns (uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint256 i = 0; i < uris.length; i++) { tokenIds[i] = _managerMint(to, uris[i]); } } /** * @dev Mint token via manager */ function _managerMint(address to, string memory uri) internal virtual returns (uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; _checkMintPermissions(to, tokenId); // Track the manager that minted the token _tokensManager[tokenId] = msg.sender; _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintManager(to, tokenId); return tokenId; } /** * @dev See {IERC721ProjectCore-tokenManager}. */ function tokenManager(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenManager(tokenId); } /** * @dev See {IERC721ProjectCore-burn}. */ function burn(uint256 tokenId) public virtual override nonReentrant { require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); address owner = ownerOf(tokenId); _burn(tokenId); _postBurn(owner, tokenId); } /** * @dev See {IProjectCore-setRoyalties}. */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesManager(address(this), receivers, basisPoints); } /** * @dev See {IProjectCore-setRoyalties}. */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { require(_exists(tokenId), "Nonexistent token"); _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {IProjectCore-setRoyaltiesManager}. */ function setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { _setRoyaltiesManager(manager, receivers, basisPoints); } /** * @dev {See IProjectCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See IProjectCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See IProjectCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyReceivers(tokenId); } /** * @dev {See IProjectCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyBPS(tokenId); } /** * @dev {See IProjectCore-royaltyInfo}. */ function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata ) external view virtual override returns ( address, uint256, bytes memory ) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return _tokenURI(tokenId); } function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./IAdminControlUpgradeable.sol"; abstract contract AdminControlUpgradeable is Initializable, OwnableUpgradeable, IAdminControlUpgradeable, ERC165Upgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // Track registered admins EnumerableSetUpgradeable.AddressSet private _admins; /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __AdminControl_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ERC165_init_unchained(); __AdminControl_init_unchained(); } function __AdminControl_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IAdminControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(isAdmin(_msgSender()), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint256 i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (_admins.add(admin)) { emit AdminApproved(admin, msg.sender); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.remove(admin)) { emit AdminRevoked(admin, msg.sender); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public view override returns (bool) { return (owner() == admin || _admins.contains(admin)); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../managers/ERC721/IERC721ProjectApproveTransferManager.sol"; import "../managers/ERC721/IERC721ProjectBurnableManager.sol"; import "../permissions/ERC721/IERC721ProjectMintPermissions.sol"; import "./IERC721ProjectCoreUpgradeable.sol"; import "./ProjectCoreUpgradeable.sol"; /** * @dev Core ERC721 project implementation */ abstract contract ERC721ProjectCoreUpgradeable is Initializable, ProjectCoreUpgradeable, IERC721ProjectCoreUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * @dev initializer */ function __ERC721ProjectCore_init() internal initializer { __ProjectCore_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ERC721ProjectCore_init_unchained(); } function __ERC721ProjectCore_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ProjectCoreUpgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721ProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IProjectCore-managerSetApproveTransfer}. */ function managerSetApproveTransfer(bool enabled) external override managerRequired { require( !enabled || ERC165CheckerUpgradeable.supportsInterface( msg.sender, type(IERC721ProjectApproveTransferManager).interfaceId ), "Manager must implement IERC721ProjectApproveTransferManager" ); if (_managerApproveTransfers[msg.sender] != enabled) { _managerApproveTransfers[msg.sender] = enabled; emit ManagerApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an manager */ function _setMintPermissions(address manager, address permissions) internal { require(_managers.contains(manager), "ProjectCore: Invalid manager"); require( permissions == address(0x0) || ERC165CheckerUpgradeable.supportsInterface( permissions, type(IERC721ProjectMintPermissions).interfaceId ), "Invalid address" ); if (_managerPermissions[manager] != permissions) { _managerPermissions[manager] = permissions; emit MintPermissionsUpdated(manager, permissions, msg.sender); } } /** * Check if an manager can mint */ function _checkMintPermissions(address to, uint256 tokenId) internal { if (_managerPermissions[msg.sender] != address(0x0)) { IERC721ProjectMintPermissions(_managerPermissions[msg.sender]).approveMint(msg.sender, to, tokenId); } } /** * Override for post mint actions */ function _postMintBase(address, uint256) internal virtual {} /** * Override for post mint actions */ function _postMintManager(address, uint256) internal virtual {} /** * Post-burning callback and metadata cleanup */ function _postBurn(address owner, uint256 tokenId) internal virtual { // Callback to originating manager if needed if (_tokensManager[tokenId] != address(this)) { if ( ERC165CheckerUpgradeable.supportsInterface( _tokensManager[tokenId], type(IERC721ProjectBurnableManager).interfaceId ) ) { IERC721ProjectBurnableManager(_tokensManager[tokenId]).onBurn(owner, tokenId); } } // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Delete token origin manager tracking delete _tokensManager[tokenId]; } /** * Approve a transfer */ function _approveTransfer( address from, address to, uint256 tokenId ) internal { if (_managerApproveTransfers[_tokensManager[tokenId]]) { require( IERC721ProjectApproveTransferManager(_tokensManager[tokenId]).approveTransfer(from, to, tokenId), "ERC721Project: Manager approval failure" ); } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @dev Interface for admin control */ interface IAdminControlUpgradeable is IERC165Upgradeable { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your manager to approve a transfer */ interface IERC721ProjectApproveTransferManager is IERC165 { /** * @dev Set whether or not the project will check the manager for approval of token transfer */ function setApproveTransfer(address project, bool enabled) external; /** * @dev Called by project contract to approve a transfer */ function approveTransfer( address from, address to, uint256 tokenId ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Your manager is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the manager created is * burned */ interface IERC721ProjectBurnableManager is IERC165 { /** * @dev callback handler for burn events */ function onBurn(address owner, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721Project compliant manager contracts. */ interface IERC721ProjectMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint( address manager, address to, uint256 tokenId ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./IProjectCoreUpgradeable.sol"; /** * @dev Core ERC721 project interface */ interface IERC721ProjectCoreUpgradeable is IProjectCoreUpgradeable { /** * @dev mint a token with no manager. Can only be called by an admin. set uri to empty string to use default uri. * Returns tokenId minted */ function adminMint(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no manager. Can only be called by an admin. * Returns tokenId minted */ function adminMintBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no manager. Can only be called by an admin. * Returns tokenId minted */ function adminMintBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered manager. set uri to "" to use default uri * Returns tokenId minted */ function managerMint(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered manager. * Returns tokenIds minted */ function managerMintBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered manager. * Returns tokenId minted */ function managerMintBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered manager's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../managers/ProjectTokenURIManager/IProjectTokenURIManager.sol"; import "./IProjectCoreUpgradeable.sol"; /** * @dev Core project implementation */ abstract contract ProjectCoreUpgradeable is Initializable, IProjectCoreUpgradeable, ReentrancyGuardUpgradeable, ERC165Upgradeable { using StringsUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; /** * External interface identifiers for royalties */ /** * @dev ProjectCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_PROJECTCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d * * => 0x6057361d = 0x6057361d */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; uint256 _tokenCount; // Track registered managers data EnumerableSetUpgradeable.AddressSet internal _managers; EnumerableSetUpgradeable.AddressSet internal _blacklistedManagers; mapping(address => address) internal _managerPermissions; mapping(address => bool) internal _managerApproveTransfers; // For tracking which manager a token was minted by mapping(uint256 => address) internal _tokensManager; // The baseURI for a given manager mapping(address => string) private _managerBaseURI; mapping(address => bool) private _managerBaseURIIdentical; // The prefix for any tokens with a uri configured mapping(address => string) private _managerURIPrefix; // Mapping for individual token URIs mapping(uint256 => string) internal _tokenURIs; // Royalty configurations mapping(address => address payable[]) internal _managerRoyaltyReceivers; mapping(address => uint256[]) internal _managerRoyaltyBPS; mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * @dev initializer */ function __ProjectCore_init() internal initializer { __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ProjectCore_init_unchained(); _tokenCount = 0; } function __ProjectCore_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_PROJECTCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered managers to call the specified function */ modifier managerRequired() { require(_managers.contains(msg.sender), "Must be registered manager"); _; } /** * @dev Only allows non-blacklisted managers */ modifier nonBlacklistRequired(address manager) { require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); _; } /** * @dev totalSupply */ function totalSupply() public view override returns (uint256) { return _tokenCount; } /** * @dev See {IProjectCore-getManagers}. */ function getManagers() external view override returns (address[] memory managers) { managers = new address[](_managers.length()); for (uint256 i = 0; i < _managers.length(); i++) { managers[i] = _managers.at(i); } return managers; } /** * @dev Register an manager */ function _registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) internal { require(manager != address(this), "Project: Invalid"); require(manager.isContract(), "Project: Manager must be a contract"); if (_managers.add(manager)) { _managerBaseURI[manager] = baseURI; _managerBaseURIIdentical[manager] = baseURIIdentical; emit ManagerRegistered(manager, msg.sender); } } /** * @dev Unregister an manager */ function _unregisterManager(address manager) internal { if (_managers.remove(manager)) { emit ManagerUnregistered(manager, msg.sender); } } /** * @dev Blacklist an manager */ function _blacklistManager(address manager) internal { require(manager != address(this), "Cannot blacklist yourself"); if (_managers.remove(manager)) { emit ManagerUnregistered(manager, msg.sender); } if (_blacklistedManagers.add(manager)) { emit ManagerBlacklisted(manager, msg.sender); } } /** * @dev Set base token uri for an manager */ function _managerSetBaseTokenURI(string calldata uri, bool identical) internal { _managerBaseURI[msg.sender] = uri; _managerBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an manager */ function _managerSetTokenURIPrefix(string calldata prefix) internal { _managerURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an manager */ function _managerSetTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensManager[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no manager */ function _setBaseTokenURI(string memory uri) internal { _managerBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no manager */ function _setTokenURIPrefix(string calldata prefix) internal { _managerURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no manager */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensManager[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address manager = _tokensManager[tokenId]; require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); // 1. if tokenURI is stored in this contract, use it with managerURIPrefix if any if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_managerURIPrefix[manager]).length != 0) { return string(abi.encodePacked(_managerURIPrefix[manager], _tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } // 2. if URI is controlled by manager, retrieve it from manager if (ERC165CheckerUpgradeable.supportsInterface(manager, type(IProjectTokenURIManager).interfaceId)) { return IProjectTokenURIManager(manager).tokenURI(address(this), tokenId); } // 3. use managerBaseURI with id or not if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else { return _managerBaseURI[manager]; } } /** * Get token manager */ function _tokenManager(uint256 tokenId) internal view returns (address manager) { manager = _tokensManager[tokenId]; require(manager != address(this), "No manager for token"); require(!_blacklistedManagers.contains(manager), "Manager blacklisted"); return manager; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_managerRoyaltyReceivers[_tokensManager[tokenId]].length > 0) { return _managerRoyaltyReceivers[_tokensManager[tokenId]]; } return _managerRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_managerRoyaltyBPS[_tokensManager[tokenId]].length > 0) { return _managerRoyaltyBPS[_tokensManager[tokenId]]; } return _managerRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) internal view returns ( address receiver, uint256 amount, bytes memory data ) { address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000, data); } /** * Set royalties for a token */ function _setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an manager */ function _setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _managerRoyaltyReceivers[manager] = receivers; _managerRoyaltyBPS[manager] = basisPoints; if (manager == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ManagerRoyaltiesUpdated(manager, receivers, basisPoints); } } uint256[36] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; /** * @dev Core project interface */ interface IProjectCoreUpgradeable is IERC165Upgradeable { event ManagerRegistered(address indexed manager, address indexed sender); event ManagerUnregistered(address indexed manager, address indexed sender); event ManagerBlacklisted(address indexed manager, address indexed sender); event MintPermissionsUpdated(address indexed manager, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ManagerRoyaltiesUpdated(address indexed manager, address payable[] receivers, uint256[] basisPoints); event ManagerApproveTransferUpdated(address indexed manager, bool enabled); /** * @dev totalSupply */ function totalSupply() external view returns (uint256); /** * @dev gets address of all managers */ function getManagers() external view returns (address[] memory); /** * @dev add an manager. Can only be called by contract owner or admin. * manager address must point to a contract implementing IProjectManager. * Returns True if newly added, False if already added. */ function registerManager(address manager, string calldata baseURI) external; /** * @dev add an manager. Can only be called by contract owner or admin. * manager address must point to a contract implementing IProjectManager. * Returns True if newly added, False if already added. */ function registerManager( address manager, string calldata baseURI, bool baseURIIdentical ) external; /** * @dev add an manager. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterManager(address manager) external; /** * @dev blacklist an manager. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified manager. It will also unregister the manager if needed. * Returns True if removed, False if already removed. */ function blacklistManager(address manager) external; /** * @dev set the baseTokenURI of an manager. Can only be called by manager. */ function managerSetBaseTokenURI(string calldata uri) external; /** * @dev set the baseTokenURI of an manager. Can only be called by manager. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function managerSetBaseTokenURI(string calldata uri, bool identical) external; /** * @dev set the common prefix of an manager. Can only be called by manager. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function managerSetTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token manager. Can only be called by manager that minted token. */ function managerSetTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token manager for multiple tokens. Can only be called by manager that minted token. */ function managerSetTokenURI(uint256[] calldata tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no manager. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no manager. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no manager. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no manager. Can only be called by owner/admin. */ function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an manager. Used to control minting. */ function setMintPermissions(address manager, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be manager) gets approval * from the manager before transferring */ function managerSetApproveTransfer(bool enabled) external; /** * @dev get the manager of a given token */ function tokenManager(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Set royalties of an manager */ function setRoyaltiesManager( address manager, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo( uint256 tokenId, uint256 value, bytes calldata data ) external view returns ( address, uint256, bytes memory ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your manager to have overloadable URI's */ interface IProjectTokenURIManager is IERC165 { /** * Get the uri for a given project/tokenId */ function tokenURI(address project, uint256 tokenId) external view returns (string memory); }
Returns true if `account` supports the {IERC165} interface,/ Any contract that implements ERC165 must explicitly indicate support of InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
function supportsERC165(address account) internal view returns (bool) { return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); }
12,006,517
./full_match/1/0x70B56ABaBf0d7bB58DD92bf5e8A5eA4cEEea9879/sources/contracts/DemApples.sol
Set the teams address
function setTheTeam(address _theTeam) external onlyOwner { theTeam = _theTeam; }
17,044,764
./partial_match/1/0x6efA260a268e4AfAcf7fb91A6BF5f5B37379BF61/sources/BasketManager.sol
Negates the isolation of a given bAsset _bAsset Address of the bAsset/
function negateIsolation(address _bAsset) external managerOrGovernor { (bool exists, uint256 i) = _isAssetInBasket(_bAsset); require(exists, "bAsset must exist"); BassetStatus currentStatus = basket.bassets[i].status; if(currentStatus == BassetStatus.BrokenBelowPeg || currentStatus == BassetStatus.BrokenAbovePeg || currentStatus == BassetStatus.Blacklisted) { basket.bassets[i].status = BassetStatus.Normal; emit BassetStatusChanged(_bAsset, BassetStatus.Normal); } }
4,466,195
pragma solidity ^0.5.12; /** * @title CToken Mock - simulating a compound market. * @dev This contract implements the required interfaces to mock compound markets * while not providing all interfaces there. This mock is extremely simple and ignores * many of the subtleties with the real compound contracts. For example the non-linear * relationship between Dai deposited and cDai minted. Rather, this contract assumes * the simplest linear relationship between variables to keep things as simple as possible. * The values returned represent the expected state changes for each function for each token. */ import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; contract CTokenMock is Initializable, ERC20 { // collateral asset = DAI IERC20 public token; // Internal counters uint256 public supplyRatePerBlock; uint256 public getCash; uint256 public totalReserves; uint256 public exchangeRateStored; function initialize(address tokenAddress) public initializer { token = IERC20(tokenAddress); supplyRatePerBlock = 0; getCash = 0; totalReserves = 0; exchangeRateStored = 0; } // Feed in initial values to seed the compound market. function seed( uint256 _supplyRatePerBlock, uint256 _getCash, uint256 _totalReserves, uint256 _exchangeRateStored, uint256 _totalSupply, address mintRecipient ) public { supplyRatePerBlock = _supplyRatePerBlock; getCash = _getCash; totalReserves = _totalReserves; exchangeRateStored = _exchangeRateStored; _mint(mintRecipient, _totalSupply); } /** * @dev msg.sender account which shall supply the asset, and own the minted cTokens. * @param mintAmount : The amount of the asset to be supplied, in units of the underlying asset. * @return uint 256: 0 on success, otherwise an Error codes */ function mint(uint256 mintAmount) public returns (uint256) { // get amount of cToken to mint // mintTokens = mintAmount / exchangeRate uint256 numerator = mintAmount.mul(1e18); uint256 scaledNumerator = numerator.mul(1e18); uint256 rational = scaledNumerator.div(exchangeRateStored); _mint(msg.sender, rational.div(1e18)); return 0; } function redeem(uint256 redeemTokens) public returns (uint256) { uint256 senderBalance = balanceOf(msg.sender); transfer(msg.sender, senderBalance); return 0; } function redeemUnderlying(uint256 redeemAmount) public returns (uint256) { return 0; } function setSupplyRatePerBlock(uint256 _supplyRatePerBlock) public { supplyRatePerBlock = _supplyRatePerBlock; } function setGetCash(uint256 _getCash) public { getCash = _getCash; } function setTotalReserves(uint256 _setTotalReserves) public { totalReserves = _setTotalReserves; } function setexchangeRateStored(uint256 _exchangeRateStored) public { exchangeRateStored = _exchangeRateStored; } }
msg.sender account which shall supply the asset, and own the minted cTokens. mintAmount : The amount of the asset to be supplied, in units of the underlying asset. return uint 256: 0 on success, otherwise an Error codes/ get amount of cToken to mint mintTokens = mintAmount / exchangeRate
function mint(uint256 mintAmount) public returns (uint256) { uint256 numerator = mintAmount.mul(1e18); uint256 scaledNumerator = numerator.mul(1e18); uint256 rational = scaledNumerator.div(exchangeRateStored); _mint(msg.sender, rational.div(1e18)); return 0; }
12,924,673
pragma solidity ^0.4.18; contract DataSourceInterface { function isDataSource() public pure returns (bool); function getGroupResult(uint matchId) external; function getRoundOfSixteenTeams(uint index) external; function getRoundOfSixteenResult(uint matchId) external; function getQuarterResult(uint matchId) external; function getSemiResult(uint matchId) external; function getFinalTeams() external; function getYellowCards() external; function getRedCards() external; } /** * @title DataLayer. * @author CryptoCup Team (https://cryptocup.io/about) */ contract DataLayer{ uint256 constant WCCTOKEN_CREATION_LIMIT = 5000000; uint256 constant STARTING_PRICE = 45 finney; /// Epoch times based on when the prices change. uint256 constant FIRST_PHASE = 1527476400; uint256 constant SECOND_PHASE = 1528081200; uint256 constant THIRD_PHASE = 1528686000; uint256 constant WORLD_CUP_START = 1528945200; DataSourceInterface public dataSource; address public dataSourceAddress; address public adminAddress; uint256 public deploymentTime = 0; uint256 public gameFinishedTime = 0; //set this to now when oraclize was called. uint32 public lastCalculatedToken = 0; uint256 public pointsLimit = 0; uint32 public lastCheckedToken = 0; uint32 public winnerCounter = 0; uint32 public lastAssigned = 0; uint256 public auxWorstPoints = 500000000; uint32 public payoutRange = 0; uint32 public lastPrizeGiven = 0; uint256 public prizePool = 0; uint256 public adminPool = 0; uint256 public finalizedTime = 0; enum teamState { None, ROS, QUARTERS, SEMIS, FINAL } enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished } /** * groups1 scores of the first half of matches (8 bits each) * groups2 scores of the second half of matches (8 bits each) * brackets winner&#39;s team ids of each round (5 bits each) * timeStamp creation timestamp * extra number of yellow and red cards (16 bits each) */ struct Token { uint192 groups1; uint192 groups2; uint160 brackets; uint64 timeStamp; uint32 extra; } struct GroupResult{ uint8 teamOneGoals; uint8 teamTwoGoals; } struct BracketPhase{ uint8[16] roundOfSixteenTeamsIds; mapping (uint8 => bool) teamExists; mapping (uint8 => teamState) middlePhaseTeamsIds; uint8[4] finalsTeamsIds; } struct Extras { uint16 yellowCards; uint16 redCards; } // List of all tokens Token[] tokens; GroupResult[48] groupsResults; BracketPhase bracketsResults; Extras extraResults; // List of all tokens that won uint256[] sortedWinners; // List of the worst tokens (they also win) uint256[] worstTokens; pointsValidationState public pValidationState = pointsValidationState.Unstarted; mapping (address => uint256[]) public tokensOfOwnerMap; mapping (uint256 => address) public ownerOfTokenMap; mapping (uint256 => address) public tokensApprovedMap; mapping (uint256 => uint256) public tokenToPayoutMap; mapping (uint256 => uint16) public tokenToPointsMap; event LogTokenBuilt(address creatorAddress, uint256 tokenId, Token token); event LogDataSourceCallbackList(uint8[] result); event LogDataSourceCallbackInt(uint8 result); event LogDataSourceCallbackTwoInt(uint8 result, uint8 result2); } ///Author Dieter Shirley (https://github.com/dete) contract ERC721 { event LogTransfer(address from, address to, uint256 tokenId); event LogApproval(address owner, address approved, uint256 tokenId); function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); } /** * @title AccessControlLayer * @author CryptoCup Team (https://cryptocup.io/about) * @dev Containes basic admin modifiers to restrict access to some functions. Allows * for pauseing, and setting emergency stops. */ contract AccessControlLayer is DataLayer{ bool public paused = false; bool public finalized = false; bool public saleOpen = true; /** * @dev Main modifier to limit access to delicate functions. */ modifier onlyAdmin() { require(msg.sender == adminAddress); _; } /** * @dev Modifier that checks that the contract is not paused */ modifier isNotPaused() { require(!paused); _; } /** * @dev Modifier that checks that the contract is paused */ modifier isPaused() { require(paused); _; } /** * @dev Modifier that checks that the contract has finished successfully */ modifier hasFinished() { require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days))); _; } /** * @dev Modifier that checks that the contract has finalized */ modifier hasFinalized() { require(finalized); _; } /** * @dev Checks if pValidationState is in the provided stats * @param state State required to run */ modifier checkState(pointsValidationState state){ require(pValidationState == state); _; } /** * @dev Transfer contract&#39;s ownership * @param _newAdmin Address to be set */ function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); adminAddress = _newAdmin; } /** * @dev Sets the contract pause state * @param state True to pause */ function setPauseState(bool state) external onlyAdmin { paused = state; } /** * @dev Sets the contract to finalized * @param state True to finalize */ function setFinalized(bool state) external onlyAdmin { paused = state; finalized = state; if(finalized == true) finalizedTime = now; } } /** * @title CryptoCupToken, main implemantations of the ERC721 standard * @author CryptoCup Team (https://cryptocup.io/about) */ contract CryptocupToken is AccessControlLayer, ERC721 { //FUNCTIONALTIY /** * @notice checks if a user owns a token * @param userAddress - The address to check. * @param tokenId - ID of the token that needs to be verified. * @return true if the userAddress provided owns the token. */ function _userOwnsToken(address userAddress, uint256 tokenId) internal view returns (bool){ return ownerOfTokenMap[tokenId] == userAddress; } /** * @notice checks if the address provided is approved for a given token * @param userAddress * @param tokenId * @return true if it is aproved */ function _tokenIsApproved(address userAddress, uint256 tokenId) internal view returns (bool) { return tokensApprovedMap[tokenId] == userAddress; } /** * @notice transfers the token specified from sneder address to receiver address. * @param fromAddress the sender address that initially holds the token. * @param toAddress the receipient of the token. * @param tokenId ID of the token that will be sent. */ function _transfer(address fromAddress, address toAddress, uint256 tokenId) internal { require(tokensOfOwnerMap[toAddress].length < 100); require(pValidationState == pointsValidationState.Unstarted); tokensOfOwnerMap[toAddress].push(tokenId); ownerOfTokenMap[tokenId] = toAddress; uint256[] storage tokenArray = tokensOfOwnerMap[fromAddress]; for (uint256 i = 0; i < tokenArray.length; i++){ if(tokenArray[i] == tokenId){ tokenArray[i] = tokenArray[tokenArray.length-1]; } } delete tokenArray[tokenArray.length-1]; tokenArray.length--; delete tokensApprovedMap[tokenId]; } /** * @notice Approve the address for a given token * @param tokenId - ID of token to be approved * @param userAddress - Address that will be approved */ function _approve(uint256 tokenId, address userAddress) internal { tokensApprovedMap[tokenId] = userAddress; } /** * @notice set token owner to an address * @dev sets token owner on the contract data structures * @param ownerAddress address to be set * @param tokenId Id of token to be used */ function _setTokenOwner(address ownerAddress, uint256 tokenId) internal{ tokensOfOwnerMap[ownerAddress].push(tokenId); ownerOfTokenMap[tokenId] = ownerAddress; } //ERC721 INTERFACE function name() public view returns (string){ return "Cryptocup"; } function symbol() public view returns (string){ return "CC"; } function balanceOf(address userAddress) public view returns (uint256 count) { return tokensOfOwnerMap[userAddress].length; } function transfer(address toAddress,uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(toAddress != address(this)); require(_userOwnsToken(msg.sender, tokenId)); _transfer(msg.sender, toAddress, tokenId); LogTransfer(msg.sender, toAddress, tokenId); } function transferFrom(address fromAddress, address toAddress, uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(toAddress != address(this)); require(_tokenIsApproved(msg.sender, tokenId)); require(_userOwnsToken(fromAddress, tokenId)); _transfer(fromAddress, toAddress, tokenId); LogTransfer(fromAddress, toAddress, tokenId); } function approve( address toAddress, uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(_userOwnsToken(msg.sender, tokenId)); _approve(tokenId, toAddress); LogApproval(msg.sender, toAddress, tokenId); } function totalSupply() public view returns (uint) { return tokens.length; } function ownerOf(uint256 tokenId) external view returns (address ownerAddress) { ownerAddress = ownerOfTokenMap[tokenId]; require(ownerAddress != address(0)); } function tokensOfOwner(address ownerAddress) external view returns(uint256[] tokenIds) { tokenIds = tokensOfOwnerMap[ownerAddress]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title GameLogicLayer, contract in charge of everything related to calculating points, asigning * winners, and distributing prizes. * @author CryptoCup Team (https://cryptocup.io/about) */ contract GameLogicLayer is CryptocupToken{ using SafeMath for *; uint8 TEAM_RESULT_MASK_GROUPS = 15; uint160 RESULT_MASK_BRACKETS = 31; uint16 EXTRA_MASK_BRACKETS = 65535; uint16 private lastPosition; uint16 private superiorQuota; uint16[] private payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500]; uint32[] private payoutDistribution; event LogGroupDataArrived(uint matchId, uint8 result, uint8 result2); event LogRoundOfSixteenArrived(uint id, uint8 result); event LogMiddlePhaseArrived(uint matchId, uint8 result); event LogFinalsArrived(uint id, uint8[4] result); event LogExtrasArrived(uint id, uint16 result); //ORACLIZE function dataSourceGetGroupResult(uint matchId) external onlyAdmin{ dataSource.getGroupResult(matchId); } function dataSourceGetRoundOfSixteen(uint index) external onlyAdmin{ dataSource.getRoundOfSixteenTeams(index); } function dataSourceGetRoundOfSixteenResult(uint matchId) external onlyAdmin{ dataSource.getRoundOfSixteenResult(matchId); } function dataSourceGetQuarterResult(uint matchId) external onlyAdmin{ dataSource.getQuarterResult(matchId); } function dataSourceGetSemiResult(uint matchId) external onlyAdmin{ dataSource.getSemiResult(matchId); } function dataSourceGetFinals() external onlyAdmin{ dataSource.getFinalTeams(); } function dataSourceGetYellowCards() external onlyAdmin{ dataSource.getYellowCards(); } function dataSourceGetRedCards() external onlyAdmin{ dataSource.getRedCards(); } /** * @notice sets a match result to the contract storage * @param matchId id of match to check * @param result number of goals the first team scored * @param result2 number of goals the second team scored */ function dataSourceCallbackGroup(uint matchId, uint8 result, uint8 result2) public { require (msg.sender == dataSourceAddress); require (matchId >= 0 && matchId <= 47); groupsResults[matchId].teamOneGoals = result; groupsResults[matchId].teamTwoGoals = result2; LogGroupDataArrived(matchId, result, result2); } /** * @notice sets the sixteen teams that made it through groups to the contract storage * @param id index of sixteen teams * @param result results to be set */ function dataSourceCallbackRoundOfSixteen(uint id, uint8 result) public { require (msg.sender == dataSourceAddress); bracketsResults.roundOfSixteenTeamsIds[id] = result; bracketsResults.teamExists[result] = true; LogRoundOfSixteenArrived(id, result); } function dataSourceCallbackTeamId(uint matchId, uint8 result) public { require (msg.sender == dataSourceAddress); teamState state = bracketsResults.middlePhaseTeamsIds[result]; if (matchId >= 48 && matchId <= 55){ if (state < teamState.ROS) bracketsResults.middlePhaseTeamsIds[result] = teamState.ROS; } else if (matchId >= 56 && matchId <= 59){ if (state < teamState.QUARTERS) bracketsResults.middlePhaseTeamsIds[result] = teamState.QUARTERS; } else if (matchId == 60 || matchId == 61){ if (state < teamState.SEMIS) bracketsResults.middlePhaseTeamsIds[result] = teamState.SEMIS; } LogMiddlePhaseArrived(matchId, result); } /** * @notice sets the champion, second, third and fourth teams to the contract storage * @param id * @param result ids of the four teams */ function dataSourceCallbackFinals(uint id, uint8[4] result) public { require (msg.sender == dataSourceAddress); uint256 i; for(i = 0; i < 4; i++){ bracketsResults.finalsTeamsIds[i] = result[i]; } LogFinalsArrived(id, result); } /** * @notice sets the number of cards to the contract storage * @param id 101 for yellow cards, 102 for red cards * @param result amount of cards */ function dataSourceCallbackExtras(uint id, uint16 result) public { require (msg.sender == dataSourceAddress); if (id == 101){ extraResults.yellowCards = result; } else if (id == 102){ extraResults.redCards = result; } LogExtrasArrived(id, result); } /** * @notice check if prediction for a match winner is correct * @param realResultOne amount of goals team one scored * @param realResultTwo amount of goals team two scored * @param tokenResultOne amount of goals team one was predicted to score * @param tokenResultTwo amount of goals team two was predicted to score * @return */ function matchWinnerOk(uint8 realResultOne, uint8 realResultTwo, uint8 tokenResultOne, uint8 tokenResultTwo) internal pure returns(bool){ int8 realR = int8(realResultOne - realResultTwo); int8 tokenR = int8(tokenResultOne - tokenResultTwo); return (realR > 0 && tokenR > 0) || (realR < 0 && tokenR < 0) || (realR == 0 && tokenR == 0); } /** * @notice get points from a single match * @param matchIndex * @param groupsPhase token predictions * @return 10 if predicted score correctly, 3 if predicted only who would win * and 0 if otherwise */ function getMatchPointsGroups (uint256 matchIndex, uint192 groupsPhase) internal view returns(uint16 matchPoints) { uint8 tokenResultOne = uint8(groupsPhase & TEAM_RESULT_MASK_GROUPS); uint8 tokenResultTwo = uint8((groupsPhase >> 4) & TEAM_RESULT_MASK_GROUPS); uint8 teamOneGoals = groupsResults[matchIndex].teamOneGoals; uint8 teamTwoGoals = groupsResults[matchIndex].teamTwoGoals; if (teamOneGoals == tokenResultOne && teamTwoGoals == tokenResultTwo){ matchPoints += 10; } else { if (matchWinnerOk(teamOneGoals, teamTwoGoals, tokenResultOne, tokenResultTwo)){ matchPoints += 3; } } } /** * @notice calculates points from the last two matches * @param brackets token predictions * @return amount of points gained from the last two matches */ function getFinalRoundPoints (uint160 brackets) internal view returns(uint16 finalRoundPoints) { uint8[3] memory teamsIds; for (uint i = 0; i <= 2; i++){ brackets = brackets >> 5; //discard 4th place teamsIds[2-i] = uint8(brackets & RESULT_MASK_BRACKETS); } if (teamsIds[0] == bracketsResults.finalsTeamsIds[0]){ finalRoundPoints += 100; } if (teamsIds[2] == bracketsResults.finalsTeamsIds[2]){ finalRoundPoints += 25; } if (teamsIds[0] == bracketsResults.finalsTeamsIds[1]){ finalRoundPoints += 50; } if (teamsIds[1] == bracketsResults.finalsTeamsIds[0] || teamsIds[1] == bracketsResults.finalsTeamsIds[1]){ finalRoundPoints += 50; } } /** * @notice calculates points for round of sixteen, quarter-finals and semifinals * @param size amount of matches in round * @param round ros, qf, sf or f * @param brackets predictions * @return amount of points */ function getMiddleRoundPoints(uint8 size, teamState round, uint160 brackets) internal view returns(uint16 middleRoundResults){ uint8 teamId; for (uint i = 0; i < size; i++){ teamId = uint8(brackets & RESULT_MASK_BRACKETS); if (uint(bracketsResults.middlePhaseTeamsIds[teamId]) >= uint(round) ) { middleRoundResults+=60; } brackets = brackets >> 5; } } /** * @notice calculates points for correct predictions of group winners * @param brackets token predictions * @return amount of points */ function getQualifiersPoints(uint160 brackets) internal view returns(uint16 qualifiersPoints){ uint8 teamId; for (uint256 i = 0; i <= 15; i++){ teamId = uint8(brackets & RESULT_MASK_BRACKETS); if (teamId == bracketsResults.roundOfSixteenTeamsIds[15-i]){ qualifiersPoints+=30; } else if (bracketsResults.teamExists[teamId]){ qualifiersPoints+=25; } brackets = brackets >> 5; } } /** * @notice calculates points won by yellow and red cards predictions * @param extras token predictions * @return amount of points */ function getExtraPoints(uint32 extras) internal view returns(uint16 extraPoints){ uint16 redCards = uint16(extras & EXTRA_MASK_BRACKETS); extras = extras >> 16; uint16 yellowCards = uint16(extras); if (redCards == extraResults.redCards){ extraPoints+=20; } if (yellowCards == extraResults.yellowCards){ extraPoints+=20; } } /** * @notice calculates total amount of points for a token * @param t token to calculate points for * @return total amount of points */ function calculateTokenPoints (Token memory t) internal view returns(uint16 points){ //Groups phase 1 uint192 g1 = t.groups1; for (uint256 i = 0; i <= 23; i++){ points+=getMatchPointsGroups(23-i, g1); g1 = g1 >> 8; } //Groups phase 2 uint192 g2 = t.groups2; for (i = 0; i <= 23; i++){ points+=getMatchPointsGroups(47-i, g2); g2 = g2 >> 8; } uint160 bracketsLocal = t.brackets; //Brackets phase 1 points+=getFinalRoundPoints(bracketsLocal); bracketsLocal = bracketsLocal >> 20; //Brackets phase 2 points+=getMiddleRoundPoints(4, teamState.QUARTERS, bracketsLocal); bracketsLocal = bracketsLocal >> 20; //Brackets phase 3 points+=getMiddleRoundPoints(8, teamState.ROS, bracketsLocal); bracketsLocal = bracketsLocal >> 40; //Brackets phase 4 points+=getQualifiersPoints(bracketsLocal); //Extras points+=getExtraPoints(t.extra); } /** * @notice Sets the points of all the tokens between the last chunk set and the amount given. * @dev This function uses all the data collected earlier by oraclize to calculate points. * @param amount The amount of tokens that should be analyzed. */ function calculatePointsBlock(uint32 amount) external{ require (gameFinishedTime == 0); require(amount + lastCheckedToken <= tokens.length); for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) { uint16 points = calculateTokenPoints(tokens[i]); tokenToPointsMap[i] = points; if(worstTokens.length == 0 || points <= auxWorstPoints){ if(worstTokens.length != 0 && points < auxWorstPoints){ worstTokens.length = 0; } if(worstTokens.length < 100){ auxWorstPoints = points; worstTokens.push(i); } } } lastCalculatedToken += amount; } /** * @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the * percentage of the pot each position gets, last position is the percentage of the pot the last position gets, * and superior quota is the total amount OF winners that are given a prize. * @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game */ function setPayoutDistributionId () internal { if(tokens.length < 101){ payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 10; }else if(tokens.length < 201){ payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 20; }else if(tokens.length < 301){ payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 30; }else if(tokens.length < 501){ payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 50; }else if(tokens.length < 1001){ payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0]; lastPosition = 4000; superiorQuota = 100; }else if(tokens.length < 2001){ payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0]; lastPosition = 2500; superiorQuota = 200; }else if(tokens.length < 3001){ payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0]; lastPosition = 2500; superiorQuota = 300; }else if(tokens.length < 5001){ payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0]; lastPosition = 2000; superiorQuota = 500; }else if(tokens.length < 10001){ payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0]; lastPosition = 1500; superiorQuota = 1000; }else if(tokens.length < 25001){ payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0]; lastPosition = 1000; superiorQuota = 2500; } else { payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70]; lastPosition = 900; superiorQuota = 5000; } } /** * @notice Sets the id of the last token that will be given a prize. * @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts * needed to just the winners and not the whole array of tokens. * @param tokenId last token id */ function setLimit(uint256 tokenId) external onlyAdmin{ require(tokenId < tokens.length); require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet); pointsLimit = tokenId; pValidationState = pointsValidationState.LimitSet; lastCheckedToken = 0; lastCalculatedToken = 0; winnerCounter = 0; setPayoutDistributionId(); } /** * @notice Sets the 10th percentile of the sorted array of points * @param amount tokens in a chunk */ function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){ require(amount + lastCheckedToken <= tokens.length); uint256 points = tokenToPointsMap[pointsLimit]; for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){ if(tokenToPointsMap[i] > points || (tokenToPointsMap[i] == points && i <= pointsLimit)){ winnerCounter++; } } lastCheckedToken += amount; if(lastCheckedToken == tokens.length){ require(superiorQuota == winnerCounter); pValidationState = pointsValidationState.LimitCalculated; } } /** * @notice Checks if the order given offchain coincides with the order of the actual previously calculated points * in the smart contract. * @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that * could occur from doing all the sorting onchain. * @param sortedChunk chunk sorted by points */ function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ require(sortedChunk.length + sortedWinners.length <= winnerCounter); for(uint256 i=0;i < sortedChunk.length-1;i++){ uint256 id = sortedChunk[i]; uint256 sigId = sortedChunk[i+1]; require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId)); } if(sortedWinners.length != 0){ uint256 id2 = sortedWinners[sortedWinners.length-1]; uint256 sigId2 = sortedChunk[0]; require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] || (tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2)); } for(uint256 j=0;j < sortedChunk.length;j++){ sortedWinners.push(sortedChunk[j]); } if(sortedWinners.length == winnerCounter){ require(sortedWinners[sortedWinners.length-1] == pointsLimit); pValidationState = pointsValidationState.OrderChecked; } } /** * @notice If anything during the point calculation and sorting part should fail, this function can reset * data structures to their initial position, so as to */ function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ sortedWinners.length = newLength; } /** * @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside * tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens * tie inside of the first 30 tokens, the prize will be summed and divided equally. */ function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){ uint256 percent = 0; uint[] memory tokensEquals = new uint[](30); uint16 tokenEqualsCounter = 0; uint256 currentTokenId; uint256 currentTokenPoints; uint256 lastTokenPoints; uint32 counter = 0; uint256 maxRange = 13; if(tokens.length < 201){ maxRange = 10; } while(payoutRange < maxRange){ uint256 inRangecounter = payDistributionAmount[payoutRange]; while(inRangecounter > 0){ currentTokenId = sortedWinners[counter]; currentTokenPoints = tokenToPointsMap[currentTokenId]; inRangecounter--; //Special case for the last one if(inRangecounter == 0 && payoutRange == maxRange - 1){ if(currentTokenPoints == lastTokenPoints){ percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; }else{ tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange]; } } if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){ //Fix second condition for(uint256 i=0;i < tokenEqualsCounter;i++){ tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter); } percent = 0; tokensEquals = new uint[](30); tokenEqualsCounter = 0; } percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; counter++; lastTokenPoints = currentTokenPoints; } payoutRange++; } pValidationState = pointsValidationState.TopWinnersAssigned; lastPrizeGiven = counter; } /** * @notice Sets prize percentage to every address that wins from the position 30th onwards * @dev If there are less than 300 tokens playing, then this function will set nothing. * @param amount tokens in a chunk */ function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){ require(lastPrizeGiven + amount <= winnerCounter); uint16 inRangeCounter = payDistributionAmount[payoutRange]; for(uint256 i = 0; i < amount; i++){ if (inRangeCounter == 0){ payoutRange++; inRangeCounter = payDistributionAmount[payoutRange]; } uint256 tokenId = sortedWinners[i + lastPrizeGiven]; tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange]; inRangeCounter--; } //i + amount prize was not given yet, so amount -1 lastPrizeGiven += amount; payDistributionAmount[payoutRange] = inRangeCounter; if(lastPrizeGiven == winnerCounter){ pValidationState = pointsValidationState.WinnersAssigned; return; } } /** * @notice Sets prizes for last tokens and sets prize pool amount */ function setLastPositions() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){ for(uint256 j = 0;j < worstTokens.length;j++){ uint256 tokenId = worstTokens[j]; tokenToPayoutMap[tokenId] += lastPosition.div(worstTokens.length); } uint256 balance = address(this).balance; adminPool = balance.mul(25).div(100); prizePool = balance.mul(75).div(100); pValidationState = pointsValidationState.Finished; gameFinishedTime = now; } } /** * @title CoreLayer * @author CryptoCup Team (https://cryptocup.io/about) * @notice Main contract */ contract CoreLayer is GameLogicLayer { function CoreLayer() public { adminAddress = msg.sender; deploymentTime = now; } /** * @dev Only accept eth from the admin */ function() external payable { require(msg.sender == adminAddress); } function isDataSourceCallback() public pure returns (bool){ return true; } /** * @notice Builds ERC721 token with the predictions provided by the user. * @param groups1 - First half of the group matches scores encoded in a uint192. * @param groups2 - Second half of the groups matches scores encoded in a uint192. * @param brackets - Bracket information encoded in a uint160. * @param extra - Extra information (number of red cards and yellow cards) encoded in a uint32. * @dev An automatic timestamp is added for internal use. */ function buildToken(uint192 groups1, uint192 groups2, uint160 brackets, uint32 extra) external payable isNotPaused { Token memory token = Token({ groups1: groups1, groups2: groups2, brackets: brackets, timeStamp: uint64(now), extra: extra }); require(msg.value >= _getTokenPrice()); require(msg.sender != address(0)); require(tokens.length < WCCTOKEN_CREATION_LIMIT); require(tokensOfOwnerMap[msg.sender].length < 100); require(now < WORLD_CUP_START); //World cup Start uint256 tokenId = tokens.push(token) - 1; require(tokenId == uint256(uint32(tokenId))); _setTokenOwner(msg.sender, tokenId); LogTokenBuilt(msg.sender, tokenId, token); } /** * @param tokenId - ID of token to get. * @return Returns all the valuable information about a specific token. */ function getToken(uint256 tokenId) external view returns (uint192 groups1, uint192 groups2, uint160 brackets, uint64 timeStamp, uint32 extra) { Token storage token = tokens[tokenId]; groups1 = token.groups1; groups2 = token.groups2; brackets = token.brackets; timeStamp = token.timeStamp; extra = token.extra; } /** * @notice Called by the development team once the World Cup has ended (adminPool is set) * @dev Allows dev team to retrieve adminPool */ function adminWithdrawBalance() external onlyAdmin { adminAddress.transfer(adminPool); adminPool = 0; } /** * @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens * owned by the caller of this function. * @dev If the caller has no prize, the function will revert costing no gas to the caller. */ function withdrawPrize() external checkState(pointsValidationState.Finished){ uint256 prize = 0; uint256[] memory tokenList = tokensOfOwnerMap[msg.sender]; for(uint256 i = 0;i < tokenList.length; i++){ prize += tokenToPayoutMap[tokenList[i]]; tokenToPayoutMap[tokenList[i]] = 0; } require(prize > 0); msg.sender.transfer((prizePool.mul(prize)).div(1000000)); } /** * @notice Gets current token price */ function _getTokenPrice() internal view returns(uint256 tokenPrice){ if ( now >= THIRD_PHASE){ tokenPrice = (150 finney); } else if (now >= SECOND_PHASE) { tokenPrice = (110 finney); } else if (now >= FIRST_PHASE) { tokenPrice = (75 finney); } else { tokenPrice = STARTING_PRICE; } require(tokenPrice >= STARTING_PRICE && tokenPrice <= (200 finney)); } /** * @dev Sets the data source contract address * @param _address Address to be set */ function setDataSourceAddress(address _address) external onlyAdmin { DataSourceInterface c = DataSourceInterface(_address); require(c.isDataSource()); dataSource = c; dataSourceAddress = _address; } /** * @notice Testing function to corroborate group data from oraclize call * @param x Id of the match to get * @return uint8 Team 1 goals * @return uint8 Team 2 goals */ function getGroupData(uint x) external view returns(uint8 a, uint8 b){ a = groupsResults[x].teamOneGoals; b = groupsResults[x].teamTwoGoals; } /** * @notice Testing function to corroborate round of sixteen data from oraclize call * @return An array with the ids of the round of sixteen teams */ function getBracketData() external view returns(uint8[16] a){ a = bracketsResults.roundOfSixteenTeamsIds; } /** * @notice Testing function to corroborate brackets data from oraclize call * @param x Team id * @return The place the team reached */ function getBracketDataMiddleTeamIds(uint8 x) external view returns(teamState a){ a = bracketsResults.middlePhaseTeamsIds[x]; } /** * @notice Testing function to corroborate finals data from oraclize call * @return the 4 (four) final teams ids */ function getBracketDataFinals() external view returns(uint8[4] a){ a = bracketsResults.finalsTeamsIds; } /** * @notice Testing function to corroborate extra data from oraclize call * @return amount of yellow and red cards */ function getExtrasData() external view returns(uint16 a, uint16 b){ a = extraResults.yellowCards; b = extraResults.redCards; } //EMERGENCY CALLS //If something goes wrong or fails, these functions will allow retribution for token holders /** * @notice if there is an unresolvable problem, users can call to this function to get a refund. */ function emergencyWithdraw() external hasFinalized{ uint256 balance = STARTING_PRICE * tokensOfOwnerMap[msg.sender].length; delete tokensOfOwnerMap[msg.sender]; msg.sender.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function finishedGameWithdraw() external onlyAdmin hasFinished{ uint256 balance = address(this).balance; adminAddress.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{ require(finalizedTime != 0 && now >= finalizedTime + 10 days ); msg.sender.transfer(address(this).balance); } }
Checks if the order given offchain coincides with the order of the actual previously calculated points in the smart contract. the token sorting is done offchain so as to save on the huge amount of gas and complications that could occur from doing all the sorting onchain. sortedChunk chunk sorted by points/
function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ require(sortedChunk.length + sortedWinners.length <= winnerCounter); for(uint256 i=0;i < sortedChunk.length-1;i++){ uint256 id = sortedChunk[i]; uint256 sigId = sortedChunk[i+1]; require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId)); } if(sortedWinners.length != 0){ uint256 id2 = sortedWinners[sortedWinners.length-1]; uint256 sigId2 = sortedChunk[0]; require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] || (tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2)); } for(uint256 j=0;j < sortedChunk.length;j++){ sortedWinners.push(sortedChunk[j]); } if(sortedWinners.length == winnerCounter){ require(sortedWinners[sortedWinners.length-1] == pointsLimit); pValidationState = pointsValidationState.OrderChecked; } }
7,712,514
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.2 (token/ERC20/ERC20.sol) /**************************************************************************** GameERC20 - Keeps a record the users' balance without minting or burning. - This is "In Game Currency" - Users can convert their "In Game Currency" to ERC20 for a fee. - Users can spend their "In Game Currency" on transactions for a fee. - Users can convert their ERC20 to "In Game Currency" for no fee. - Users can transer their "In Game Currency" to another player for no fee. - Inspired by ColdBloodedCreepz Loomi Token Written by Oliver Straszynski https://github.com/broliver12/ ****************************************************************************/ pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; contract GameERC20 is ERC20, ReentrancyGuard, Ownable { // Control params uint256 public maxSupply; bool public tokenCapSet; bool public isPaused = true; bool public isTransferPaused = true; bool public isDepositPaused = true; bool public isWithdrawPaused = true; // Tax params bool public withdrawTaxCollectionStopped; bool public spendTaxCollectionStopped; uint256 public spendTaxPercent; uint256 public withdrawTaxPercent; uint256 public activeTaxCollectedAmount; uint256 public constant MAX_TAX_VALUE = 100; // Other contracts that are able to interact with token address[] public controllers; mapping(address => bool) private _ctrl; // Amount of in game currency deposited / spent mapping(address => uint256) public depositedAmount; mapping(address => uint256) public spentAmount; // Events event Withdraw(address indexed userAddress, uint256 amount, uint256 tax); event Deposit(address indexed userAddress, uint256 amount); event DepositFor(address indexed caller, address indexed userAddress, uint256 amount); event Spend(address indexed caller, address indexed userAddress, uint256 amount, uint256 tax); event ClaimTax(address indexed caller, address indexed userAddress, uint256 amount); event InternalTransfer(address indexed from, address indexed to, uint256 amount); modifier onlyCtrl() { require(_ctrl[_msgSender()], 'Not Authorised'); _; } modifier notPaused() { require(!isPaused, 'Transfers paused!'); _; } constructor() ERC20('WIGL', 'WIGL') { _ctrl[_msgSender()] = true; withdrawTaxPercent = 25; spendTaxPercent = 25; } // Returns max token supply, reverts if not set. function getMaxSupply() public view returns (uint256) { require(tokenCapSet, 'Max supply is not set'); return maxSupply; } // Returns current IN GAME balance for the specified user. function getUserBalance(address user) public view returns (uint256) { return depositedAmount[user] - spentAmount[user]; } /**************************************************************************** User Actions ****************************************************************************/ // Convert ERC20 to in game currency function depositERC20(uint256 amount) public nonReentrant notPaused { require(!isDepositPaused, 'Deposit Paused'); require(balanceOf(_msgSender()) >= amount, 'Not enough ERC20 WIGL'); _burn(_msgSender(), amount); depositedAmount[_msgSender()] += amount; emit Deposit(_msgSender(), amount); } // Convert in game currency to ERC20 // Tax of withdrawTaxPercent applied on withdraw function withdrawERC20(uint256 amount) public nonReentrant notPaused { require(!isWithdrawPaused, 'Withdraw Paused'); require(getUserBalance(_msgSender()) >= amount, 'Not enough game WIGL'); if (tokenCapSet) require(totalSupply() + amount <= maxSupply, 'Max supply reached'); uint256 tax = withdrawTaxCollectionStopped ? 0 : (amount * withdrawTaxPercent) / 100; spentAmount[_msgSender()] += amount; activeTaxCollectedAmount += tax; _mint(_msgSender(), amount - tax); emit Withdraw(_msgSender(), amount, tax); } // Transfer in game currency to another wallet function transferInGame(address to, uint256 amount) public nonReentrant notPaused { require(!isTransferPaused, 'Transfer Paused'); require(getUserBalance(_msgSender()) >= amount, 'Not enough game WIGL'); spentAmount[_msgSender()] += amount; depositedAmount[to] += amount; emit InternalTransfer(_msgSender(), to, amount); } /**************************************************************************** Controller Actions ****************************************************************************/ // Spend in game currency on an in-ecosystem action. // Tax of withdrawTaxPercent applied on withdraw function spendInGame(address user, uint256 amount) external onlyCtrl nonReentrant { require(getUserBalance(user) >= amount, 'Not enough game WIGL'); uint256 tax = spendTaxCollectionStopped ? 0 : (amount * spendTaxPercent) / 100; spentAmount[user] += amount; activeTaxCollectedAmount += tax; emit Spend(_msgSender(), user, amount, tax); } // "Create" in game currency for user // Does NOT actually mint the token. function mintGameWiglFor(address user, uint256 amount) public onlyCtrl nonReentrant { _depositFor(user, amount); } // "Create" in game currency for users function distributeGameWigl(address[] memory user, uint256[] memory amount) public onlyCtrl nonReentrant { require(user.length == amount.length, 'Arrays not same length'); for (uint256 i; i < user.length; i++) { _depositFor(user[i], amount[i]); } } // Interal helper, "mints" game currency to the specified account function _depositFor(address user, uint256 amount) internal { require(user != address(0), 'Cant deposit to 0 address'); depositedAmount[user] += amount; emit DepositFor(_msgSender(), user, amount); } // Mint ERC20 $WIGL to users // No tax applied function mintFor(address user, uint256 amount) external onlyCtrl nonReentrant { if (tokenCapSet) require(totalSupply() + amount <= maxSupply, 'Max supply reached'); _mint(user, amount); } // Withdraw accumulated tax to user's wallet function claimTax(address user, uint256 amount) public onlyCtrl nonReentrant { require(activeTaxCollectedAmount >= amount, 'Not enough tax to claim'); activeTaxCollectedAmount -= amount; depositedAmount[user] += amount; emit ClaimTax(_msgSender(), user, amount); } /**************************************************************************** Owner Functions ****************************************************************************/ // This function can only be called successfully ONE TIME. // Setting the token cap is IRREVERSIBLE. // It should only be called when the token ecosystem is mature // and balanced. function setTokenCap(uint256 tokenCap) public onlyOwner { require(totalSupply() < tokenCap, 'Too many minted already'); require(!tokenCapSet, 'Token cap already set'); maxSupply = tokenCap; tokenCapSet = true; } function addController(address addr) public onlyOwner { _ctrl[addr] = true; controllers.push(addr); } function removeController(address addr) public onlyOwner { _ctrl[addr] = false; for (uint256 i; i < controllers.length; i++) { if (controllers[i] == addr) { controllers[i] = controllers[controllers.length - 1]; delete controllers[controllers.length - 1]; return; } } } function updateWithdrawTaxPercent(uint256 taxPercent) public onlyOwner { require(taxPercent < MAX_TAX_VALUE, 'Less than 100'); withdrawTaxPercent = taxPercent; } function updateSpendTaxPercent(uint256 taxPercent) public onlyOwner { require(taxPercent < MAX_TAX_VALUE, 'Less than 100'); spendTaxPercent = taxPercent; } function stopTaxCollectionOnWithdraw(bool stop) public onlyOwner { withdrawTaxCollectionStopped = stop; } function stopTaxCollectionOnSpend(bool stop) public onlyOwner { spendTaxCollectionStopped = stop; } function pauseInGameTransactions(bool pause) public onlyOwner { isPaused = pause; } function pauseInGameTransfers(bool pause) public onlyOwner { isTransferPaused = pause; } function pauseInGameWithdraw(bool pause) public onlyOwner { isWithdrawPaused = pause; } function pauseInGameDeposits(bool pause) public onlyOwner { isDepositPaused = pause; } // If someone sends $ETH to the token contract directly, // this function lets us rescue their money, and return it! function rescue() external onlyOwner { payable(owner()).transfer(address(this).balance); } }
If someone sends $ETH to the token contract directly, this function lets us rescue their money, and return it!
function rescue() external onlyOwner { payable(owner()).transfer(address(this).balance); }
12,662,142
./full_match/4/0x743Fbe15CCef1F9aAB28878819cCD9D266698008/sources/BSUD_X6.sol
require(msg.value == BASIC_PRICE 2, "invalid registration value");
function registration(address userAddress, address referrerAddress) private { depositToken.safeTransferFrom(msg.sender, address(this), BASIC_PRICE * 2); require(!isUserExists(userAddress), "user exists"); require(isUserExists(referrerAddress), "referrer not exists"); uint32 size; assembly { size := extcodesize(userAddress) } User memory user = User({ id: lastUserId, referrer: referrerAddress, partnersCount: 0 }); users[userAddress] = user; idToAddress[lastUserId] = userAddress; users[userAddress].referrer = referrerAddress; users[userAddress].activeX6Levels[1] = true; userIds[lastUserId] = userAddress; lastUserId++; users[referrerAddress].partnersCount++; address freeX6Referrer = findFreeX6Referrer(userAddress, 1); users[userAddress].x6Matrix[1].currentReferrer = freeX6Referrer; updateX6Referrer(userAddress, freeX6Referrer, 1); emit Registration(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id); }
670,480
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; import "./libraries/SignedSafeMath.sol"; import "./interfaces/IRewarder.sol"; import "./interfaces/IMasterChef.sol"; /// @notice The (older) MasterChef contract gives out a constant number of SUSHI per Block. /// It is the only address with minting rights for the SUSHI token. /// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token /// that is deposited into the MasterChef V1 (MCV1) contract. /// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. contract MasterChefV2 is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each user. /// `amount` of LP tokens the user has provided. /// `rewardDebt` the amount of SUSHI entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUSHIs to distribute per Block struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of MasterChef (v1). IMasterChef public immutable MASTER_CHEF; /// @notice The SUSHI ERC-20 contract. IERC20 public immutable SUSHI; /// @notice The index of the master pool. uint256 public immutable MASTER_PID; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Address of the ERC-20 for each Pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20; uint256 private constant ACC_SUSHI_PRECISION = 1e12; bytes4 private constant SIG_ON_SUSHI_REWARD = 0xbb6cc2ef; // onSushiReward(uint256,address,uint256) event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare); event LogInit(); /// @param _MASTER_CHEF the SushiSwap MasterChef contract /// @param _sushi the SUSHI Token /// @param _MASTER_PID the pool ID of the dummy token on the base contract constructor(IMasterChef _MASTER_CHEF, IERC20 _sushi, uint256 _MASTER_PID) public { MASTER_CHEF = _MASTER_CHEF; SUSHI = _sushi; MASTER_PID = _MASTER_PID; } /// @notice Deposits a dummy tokens to `MASTER_CHEF`. This is required because `MASTER_CHEF` holds the minting rights for SUSHI. /// Any balance of transaction sender from `dummyToken` is transferred. /// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives. function init(IERC20 dummyToken) external { uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(address(MASTER_CHEF), balance); MASTER_CHEF.deposit(MASTER_PID, balance); emit LogInit(); } /// @notice Returns the number of pools. function poolLength() public view returns (uint256) { return poolInfo.length; } /// @notice Add a new lp to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool /// @param _lpToken address of the LP token /// @param _rewarder address of the reward Contract function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint new AP of the pool /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice View function to see pending SUSHIs on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user address of user function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply); } uint256 _pendingSushi = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256(); return _pendingSushi; } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids pool IDs of all to be updated, make sure to update all active pools function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice calculates the `amount` of SUSHI per block function sushiPerBlock() public view returns (uint256 amount) { amount = uint256(MASTERCHEF_SUSHI_PER_BLOCK) .mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) / MASTER_CHEF.totalAllocPoint(); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool returns the Pool that was updated function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; pool.accSushiPerShare = pool.accSushiPerShare.add((sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare); } } /// @notice Deposit LP tokens to MasterChef for SUSHI allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount to deposit. /// @param to The receiver of `amount`. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); // Interactions lpToken[pid].safeTransferFrom(address(msg.sender), address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MasterChef. /// @param pid The index of the pool. See `poolInfo`. /// @param amount of lp tokens to withdraw. /// @param to Receiver of the lp tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SUSHI rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); if (_pendingSushi == 0) { return; } // Effects user.rewardDebt = accumulatedSushi; // Interactions SUSHI.safeTransfer(to, _pendingSushi); address _rewarder = address(rewarder[pid]); if (_rewarder != address(0)){ // Note: Do it this way because we don't want to fail harvest if only the delegate call fails. // Additionally, forward less gas so that we have enough buffer to complete harvest if the call eats up too much gas. // Forwarding: (63/64 of gasleft by evm convention) minus 5000 // solhint-disable-next-line _rewarder.call{ gas: gasleft() - 5000 }(abi.encodeWithSelector(SIG_ON_SUSHI_REWARD, pid, msg.sender, _pendingSushi)); } emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Harvests SUSHI from `MASTER_CHEF` and pool `MASTER_PID` to this contract. function harvestFromMasterChef () public { MASTER_CHEF.deposit(MASTER_PID, 0); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the lp tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } }
Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. _pid The index of the pool. See `poolInfo`. _allocPoint new AP of the pool _rewarder Address of the rewarder delegate. overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); }
12,881,788
./full_match/137/0x74E7ACAfC758caC65910e5C38E6Ef9ade5fA87A8/sources/contracts/SpotTradingRewardDistributor/SpotTradingRewardDistributor.sol
Interface checker _interfaceId The interface id to check/
function supportsInterface(bytes4 _interfaceId) public view override returns (bool) { return _interfaceId == type(ISpotTradingRewardDistributor).interfaceId || super.supportsInterface(_interfaceId); }
4,721,662
./full_match/80001/0xDC9FB0d4339200b535fFB9752036368541c0eDBC/sources/contracts/interfaces/ILayerZeroMessagingLibrary.sol
send(), messages will be inflight. estimate native fee at the send side--------------------------------------------------------------------------- setConfig / getConfig are User Application (UA) functions to specify Oracle, Relayer, blockConfirmations, libraryVersion
interface ILayerZeroMessagingLibrary { function send(address _userApplication, uint64 _lastNonce, uint16 _chainId, bytes calldata _destination, bytes calldata _payload, address payable refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable; function estimateFees(uint16 _chainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee); function setConfig(uint16 _chainId, address _userApplication, uint _configType, bytes calldata _config) external; function getConfig(uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory); }
9,434,071
pragma solidity 0.4.25; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } pragma solidity 0.4.25; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity 0.4.25; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "./ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor () public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "./ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.4.25; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity 0.4.25; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./TBoxToken.sol"; import "./ISettings.sol"; import "./IToken.sol"; import "./IOracle.sol"; /// @title TBoxManager contract TBoxManager is TBoxToken { // Total packed Ether uint256 public globalETH; // Precision using for USD and commission uint256 public precision = 100000; // The address of the system settings contract ISettings public settings; /// @dev An array containing the Boxes struct for all Boxes in existence. The ID /// of each Box is actually an index into this array. Box[] public boxes; /// @dev The main Box struct. Every Box in TimviSystem is represented by a copy /// of this structure. struct Box { // The collateral Ether amount in wei uint256 collateral; // The number of TMV withdrawn uint256 tmvReleased; } /// @dev The Created event is fired whenever a new Box comes into existence. This includes /// any time a Box is created through the create method. event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased); /// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes /// any time a Box is closed through the close method, but it is also called when // a Box is closed through the closeDust method. event Closed(uint256 indexed id, address indexed owner, address indexed closer); /// @dev The Capitalized event is fired whenever a Box is capitalized. event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth); /// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box /// using withdrawEth method. event EthWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box /// using withdrawTmv method. event TmvWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The EthAdded event is fired whenever Ether is added to a Box /// using addEth method. event EthAdded(uint256 indexed id, uint256 value, address who); /// @dev The TmvAdded event is fired whenever TMV is added to a Box /// using addTmv method. event TmvAdded(uint256 indexed id, uint256 value, address who); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyAdmin() { require(settings.isFeeManager(msg.sender), "You have no access"); _; } /// @dev Throws if Box with specified id does not exist. modifier onlyExists(uint256 _id) { require(_exists(_id), "Box does not exist"); _; } /// @dev Access modifier for token owner-only functionality. modifier onlyApprovedOrOwner(uint256 _id) { require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your"); _; } /// @dev The constructor sets ERC721 token name and symbol. /// @param _settings The address of the system settings contract. constructor(address _settings) TBoxToken("TBoxToken", "TBX") public { settings = ISettings(_settings); } /// @notice The funds are safe. /// @dev Creates Box with max collateral percent. function() external payable { // Redirect to the create method with no tokens to withdraw create(0); } /// @dev Withdraws system fee. function withdrawFee(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); // Fee is the difference between the contract balance and // amount of Ether used in the entire system collateralization uint256 _fees = address(this).balance.sub(globalETH); // Check that the fee is collected require(_fees > 0, "There is no available fees"); // Transfer fee to provided address _beneficiary.transfer(_fees); } /// @dev Checks possibility of the issue of the specified token amount /// for provided Ether collateral and creates new Box /// @param _tokensToWithdraw Number of tokens to withdraw /// @return New Box ID. function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) { // Check that msg.value isn't smaller than minimum deposit require(msg.value >= settings.minDeposit(), "Deposit is very small"); // Calculate collateralization when tokens are needed if (_tokensToWithdraw > 0) { // The number of tokens when collateralization is high uint256 _tokenLimit = overCapWithdrawableTmv(msg.value); // The number of tokens that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit > _maxGlobal) { _tokenLimit = _maxGlobal; } // The number of tokens that can be withdrawn anyway uint256 _local = defaultWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit < _local) { _tokenLimit = _local; } // You can only withdraw available amount require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available"); // Mint TMV tokens to the Box creator IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw); } // The id of the new Box uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Mint TBX token to the Box creator _mint(msg.sender, _id); // Fire the event emit Created(_id, msg.sender, msg.value, _tokensToWithdraw); // return the new Box's ID return _id; } /// @dev Allows the owner or approved user of the Box to close one by burning the /// required number of tokens and return the Box's collateral. /// @param _id A Box ID to close. function close(uint256 _id) external onlyApprovedOrOwner(_id) { // Address of the owner of the Box address _owner = _tokenOwner[_id]; // Burn needed number of tokens uint256 _tokensNeed = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tokensNeed); // Grab a reference to the Box's collateral in storage uint256 _collateral = boxes[_id].collateral; // burn Box token _burn(_owner, _id); // Removes Box delete boxes[_id]; // Send the Box's collateral to the person who made closing happen msg.sender.transfer(_collateral); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows the user to capitalize a Box with the maximum current amount. /// @param _id A Box ID to capitalize. function capitalizeMax(uint256 _id) external { capitalize(_id, maxCapAmount(_id)); } /// @dev Allows the user to capitalize a Box with specified number of tokens. /// @param _id A Box ID to capitalize. /// @param _tmv Specified number of tokens to capitalize. function capitalize(uint256 _id, uint256 _tmv) public validTx { // The maximum number of tokens for which Box can be capitalized uint256 _maxCapAmount = maxCapAmount(_id); // Check the number of tokens require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range"); // Decrease Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv); // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _equivalentETH = _tmv.mul(precision).div(rate()); // Calculate system fee uint256 _fee = _tmv.mul(settings.sysFee()).div(rate()); // Calculate user bonus uint256 _userReward = _tmv.mul(settings.userFee()).div(rate()); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH)); // Decrease global Ether counter globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH)); // burn Box token _burnTMV(msg.sender, _tmv); // Send the Ether equivalent & user benefit to the person who made capitalization happen. msg.sender.transfer(_equivalentETH.add(_userReward)); // Fire the event emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward)); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum amount /// of Ether from the Box. /// @param _id A Box ID. function withdrawEthMax(uint256 _id) external { withdrawEth(_id, withdrawableEth(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified amount /// of Ether from the Box. /// @param _id A Box ID. /// @param _amount The number of Ether to withdraw. function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); require(_amount <= withdrawableEth(_id), "You can't withdraw so much"); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_amount); // Decrease global Ether counter globalETH = globalETH.sub(_amount); // Send the Ether to the person who made capitalization happen msg.sender.transfer(_amount); // Fire the event emit EthWithdrawn(_id, _amount, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum number /// of TMV tokens from the Box. /// @param _id A Box ID. function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) { withdrawTmv(_id, boxWithdrawableTmv(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified number /// of TMV tokens from the Box. /// @param _id A Box ID. /// @param _amount The number of tokens to withdraw. function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); // Check the number of tokens require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much"); // Increase Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount); // Mints tokens to the person who made withdrawing IToken(settings.tmvAddress()).mint(msg.sender, _amount); // Fire the event emit TmvWithdrawn(_id, _amount, msg.sender); } /// @dev Allows anyone to add Ether to a Box. /// @param _id A Box ID. function addEth(uint256 _id) external payable onlyExists(_id) { require(msg.value > 0, "Don't add 0"); // Increase Box collateral boxes[_id].collateral = boxes[_id].collateral.add(msg.value); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Fire the event emit EthAdded(_id, msg.value, msg.sender); } /// @dev Allows anyone to add TMV to a Box. /// @param _id A Box ID. /// @param _amount The number of tokens to add. function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) { require(_amount > 0, "Don't add 0"); // Check the number of tokens require(_amount <= boxes[_id].tmvReleased, "Too much tokens"); // Removes added tokens from the collateralization _burnTMV(msg.sender, _amount); boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount); // Fire the event emit TmvAdded(_id, _amount, msg.sender); } /// @dev Allows anyone to close Box with collateral amount smaller than 3 USD. /// The person who made closing happen will benefit like capitalization. /// @param _id A Box ID. function closeDust(uint256 _id) external onlyExists(_id) validTx { // Check collateral percent of the Box require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable"); // Check collateral amount of the Box require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust"); // Burn needed TMV amount to close uint256 _tmvReleased = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tmvReleased); uint256 _collateral = boxes[_id].collateral; // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _eth = _tmvReleased.mul(precision).div(rate()); // Calculate user bonus uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate()); // The owner of the Box address _owner = ownerOf(_id); // Remove a Box delete boxes[_id]; // Burn Box token _burn(_owner, _id); // Send the Ether equivalent & user benefit to the person who made closing happen msg.sender.transfer(_eth.add(_userReward)); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @dev Burns specified number of TMV tokens. function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Given a Box ID, returns a number of tokens that can be withdrawn. function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; // Number of tokens that can be withdrawn for Box's collateral uint256 _amount = withdrawableTmv(box.collateral); if (box.tmvReleased >= _amount) { return 0; } // Return withdrawable rest return _amount.sub(box.tmvReleased); } /// @dev Given a Box ID, returns an amount of Ether that can be withdrawn. function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) { // Amount of Ether that is not used in collateralization uint256 _avlbl = _freeEth(_id); // Return available Ether to withdraw if (_avlbl == 0) { return 0; } uint256 _rest = boxes[_id].collateral.sub(_avlbl); if (_rest < settings.minDeposit()) { return boxes[_id].collateral.sub(settings.minDeposit()); } else return _avlbl; } /// @dev Given a Box ID, returns amount of ETH that is not used in collateralization. function _freeEth(uint256 _id) internal view returns(uint256) { // Grab a reference to the Box Box memory box = boxes[_id]; // When there are no tokens withdrawn if (box.tmvReleased == 0) { return box.collateral; } // The amount of Ether that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableEth(); uint256 _globalAvailable; if (_maxGlobal > 0) { // The amount of Ether backing the tokens when the system is overcapitalized uint256 _need = overCapFrozenEth(box.tmvReleased); if (box.collateral > _need) { // Free Ether amount when the system is overcapitalized uint256 _free = box.collateral.sub(_need); if (_free > _maxGlobal) { // Store available amount when Box available Ether amount // is more than global available _globalAvailable = _maxGlobal; } // Return available amount of Ether to withdraw when the Box withdrawable // amount of Ether is smaller than global withdrawable amount of Ether else return _free; } } // The amount of Ether backing the tokens by default uint256 _frozen = defaultFrozenEth(box.tmvReleased); if (box.collateral > _frozen) { // Define the biggest number and return available Ether amount uint256 _localAvailable = box.collateral.sub(_frozen); return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable; } else { // Return available Ether amount return _globalAvailable; } } /// @dev Given a Box ID, returns collateral percent. function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; if (box.tmvReleased == 0) { return 10**27; //some unreachable number } uint256 _ethCollateral = box.collateral; // division by 100 is not necessary because to get the percent you need to multiply by 100 return _ethCollateral.mul(rate()).div(box.tmvReleased); } /// @dev Checks if a given address currently has approval for a particular Box. /// @param _spender the address we are confirming Box is approved for. /// @param _tokenId Box ID. function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Returns the global collateralization percent. function globalCollateralization() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (_supply == 0) { return settings.globalTargetCollateralization(); } return globalETH.mul(rate()).div(_supply); } /// @dev Returns the number of tokens that can be safely withdrawn from the system. function globalWithdrawableTmv(uint256 _value) public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value)); return _totalBackedTmv.sub(_supply); } /// @dev Returns Ether amount that can be safely withdrawn from the system. function globalWithdrawableEth() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _need = defaultFrozenEth(_supply); return globalETH.sub(_need); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount by default. function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.globalTargetCollateralization(); return _num.div(_div); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount when the system is overcapitalized. function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.ratio(); return _num.div(_div); } /// @dev Returns Ether amount backing the specified number of tokens by default. function defaultFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.globalTargetCollateralization()).div(rate()); } /// @dev Returns Ether amount backing the specified number of tokens /// when the system is overcapitalized. function overCapFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.ratio()).div(rate()); } /// @dev Returns the number of TMV that can capitalize the specified Box. function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) { uint256 _colP = collateralPercent(_id); require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes"); Box memory box = boxes[_id]; uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate())); uint256 _div = settings.ratio().sub(settings.minStability()); return _num.div(_div); } /// @dev Returns the number of tokens that can be actually withdrawn /// for the specified collateral. function withdrawableTmv(uint256 _collateral) public view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(0); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _amount; } /// @dev Returns the collateral percentage for which tokens can be withdrawn /// for the specified collateral. function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title TBoxClassic Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} } pragma solidity 0.4.25; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } pragma solidity 0.4.25; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity 0.4.25; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "./ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor () public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "./ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.4.25; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity 0.4.25; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./TBoxToken.sol"; import "./ISettings.sol"; import "./IToken.sol"; import "./IOracle.sol"; /// @title TBoxManager contract TBoxManager is TBoxToken { // Total packed Ether uint256 public globalETH; // Precision using for USD and commission uint256 public precision = 100000; // The address of the system settings contract ISettings public settings; /// @dev An array containing the Boxes struct for all Boxes in existence. The ID /// of each Box is actually an index into this array. Box[] public boxes; /// @dev The main Box struct. Every Box in TimviSystem is represented by a copy /// of this structure. struct Box { // The collateral Ether amount in wei uint256 collateral; // The number of TMV withdrawn uint256 tmvReleased; } /// @dev The Created event is fired whenever a new Box comes into existence. This includes /// any time a Box is created through the create method. event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased); /// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes /// any time a Box is closed through the close method, but it is also called when // a Box is closed through the closeDust method. event Closed(uint256 indexed id, address indexed owner, address indexed closer); /// @dev The Capitalized event is fired whenever a Box is capitalized. event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth); /// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box /// using withdrawEth method. event EthWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box /// using withdrawTmv method. event TmvWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The EthAdded event is fired whenever Ether is added to a Box /// using addEth method. event EthAdded(uint256 indexed id, uint256 value, address who); /// @dev The TmvAdded event is fired whenever TMV is added to a Box /// using addTmv method. event TmvAdded(uint256 indexed id, uint256 value, address who); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyAdmin() { require(settings.isFeeManager(msg.sender), "You have no access"); _; } /// @dev Throws if Box with specified id does not exist. modifier onlyExists(uint256 _id) { require(_exists(_id), "Box does not exist"); _; } /// @dev Access modifier for token owner-only functionality. modifier onlyApprovedOrOwner(uint256 _id) { require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your"); _; } /// @dev The constructor sets ERC721 token name and symbol. /// @param _settings The address of the system settings contract. constructor(address _settings) TBoxToken("TBoxToken", "TBX") public { settings = ISettings(_settings); } /// @notice The funds are safe. /// @dev Creates Box with max collateral percent. function() external payable { // Redirect to the create method with no tokens to withdraw create(0); } /// @dev Withdraws system fee. function withdrawFee(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); // Fee is the difference between the contract balance and // amount of Ether used in the entire system collateralization uint256 _fees = address(this).balance.sub(globalETH); // Check that the fee is collected require(_fees > 0, "There is no available fees"); // Transfer fee to provided address _beneficiary.transfer(_fees); } /// @dev Checks possibility of the issue of the specified token amount /// for provided Ether collateral and creates new Box /// @param _tokensToWithdraw Number of tokens to withdraw /// @return New Box ID. function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) { // Check that msg.value isn't smaller than minimum deposit require(msg.value >= settings.minDeposit(), "Deposit is very small"); // Calculate collateralization when tokens are needed if (_tokensToWithdraw > 0) { // The number of tokens when collateralization is high uint256 _tokenLimit = overCapWithdrawableTmv(msg.value); // The number of tokens that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit > _maxGlobal) { _tokenLimit = _maxGlobal; } // The number of tokens that can be withdrawn anyway uint256 _local = defaultWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit < _local) { _tokenLimit = _local; } // You can only withdraw available amount require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available"); // Mint TMV tokens to the Box creator IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw); } // The id of the new Box uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Mint TBX token to the Box creator _mint(msg.sender, _id); // Fire the event emit Created(_id, msg.sender, msg.value, _tokensToWithdraw); // return the new Box's ID return _id; } /// @dev Allows the owner or approved user of the Box to close one by burning the /// required number of tokens and return the Box's collateral. /// @param _id A Box ID to close. function close(uint256 _id) external onlyApprovedOrOwner(_id) { // Address of the owner of the Box address _owner = _tokenOwner[_id]; // Burn needed number of tokens uint256 _tokensNeed = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tokensNeed); // Grab a reference to the Box's collateral in storage uint256 _collateral = boxes[_id].collateral; // burn Box token _burn(_owner, _id); // Removes Box delete boxes[_id]; // Send the Box's collateral to the person who made closing happen msg.sender.transfer(_collateral); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows the user to capitalize a Box with the maximum current amount. /// @param _id A Box ID to capitalize. function capitalizeMax(uint256 _id) external { capitalize(_id, maxCapAmount(_id)); } /// @dev Allows the user to capitalize a Box with specified number of tokens. /// @param _id A Box ID to capitalize. /// @param _tmv Specified number of tokens to capitalize. function capitalize(uint256 _id, uint256 _tmv) public validTx { // The maximum number of tokens for which Box can be capitalized uint256 _maxCapAmount = maxCapAmount(_id); // Check the number of tokens require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range"); // Decrease Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv); // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _equivalentETH = _tmv.mul(precision).div(rate()); // Calculate system fee uint256 _fee = _tmv.mul(settings.sysFee()).div(rate()); // Calculate user bonus uint256 _userReward = _tmv.mul(settings.userFee()).div(rate()); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH)); // Decrease global Ether counter globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH)); // burn Box token _burnTMV(msg.sender, _tmv); // Send the Ether equivalent & user benefit to the person who made capitalization happen. msg.sender.transfer(_equivalentETH.add(_userReward)); // Fire the event emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward)); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum amount /// of Ether from the Box. /// @param _id A Box ID. function withdrawEthMax(uint256 _id) external { withdrawEth(_id, withdrawableEth(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified amount /// of Ether from the Box. /// @param _id A Box ID. /// @param _amount The number of Ether to withdraw. function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); require(_amount <= withdrawableEth(_id), "You can't withdraw so much"); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_amount); // Decrease global Ether counter globalETH = globalETH.sub(_amount); // Send the Ether to the person who made capitalization happen msg.sender.transfer(_amount); // Fire the event emit EthWithdrawn(_id, _amount, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum number /// of TMV tokens from the Box. /// @param _id A Box ID. function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) { withdrawTmv(_id, boxWithdrawableTmv(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified number /// of TMV tokens from the Box. /// @param _id A Box ID. /// @param _amount The number of tokens to withdraw. function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); // Check the number of tokens require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much"); // Increase Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount); // Mints tokens to the person who made withdrawing IToken(settings.tmvAddress()).mint(msg.sender, _amount); // Fire the event emit TmvWithdrawn(_id, _amount, msg.sender); } /// @dev Allows anyone to add Ether to a Box. /// @param _id A Box ID. function addEth(uint256 _id) external payable onlyExists(_id) { require(msg.value > 0, "Don't add 0"); // Increase Box collateral boxes[_id].collateral = boxes[_id].collateral.add(msg.value); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Fire the event emit EthAdded(_id, msg.value, msg.sender); } /// @dev Allows anyone to add TMV to a Box. /// @param _id A Box ID. /// @param _amount The number of tokens to add. function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) { require(_amount > 0, "Don't add 0"); // Check the number of tokens require(_amount <= boxes[_id].tmvReleased, "Too much tokens"); // Removes added tokens from the collateralization _burnTMV(msg.sender, _amount); boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount); // Fire the event emit TmvAdded(_id, _amount, msg.sender); } /// @dev Allows anyone to close Box with collateral amount smaller than 3 USD. /// The person who made closing happen will benefit like capitalization. /// @param _id A Box ID. function closeDust(uint256 _id) external onlyExists(_id) validTx { // Check collateral percent of the Box require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable"); // Check collateral amount of the Box require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust"); // Burn needed TMV amount to close uint256 _tmvReleased = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tmvReleased); uint256 _collateral = boxes[_id].collateral; // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _eth = _tmvReleased.mul(precision).div(rate()); // Calculate user bonus uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate()); // The owner of the Box address _owner = ownerOf(_id); // Remove a Box delete boxes[_id]; // Burn Box token _burn(_owner, _id); // Send the Ether equivalent & user benefit to the person who made closing happen msg.sender.transfer(_eth.add(_userReward)); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @dev Burns specified number of TMV tokens. function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Given a Box ID, returns a number of tokens that can be withdrawn. function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; // Number of tokens that can be withdrawn for Box's collateral uint256 _amount = withdrawableTmv(box.collateral); if (box.tmvReleased >= _amount) { return 0; } // Return withdrawable rest return _amount.sub(box.tmvReleased); } /// @dev Given a Box ID, returns an amount of Ether that can be withdrawn. function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) { // Amount of Ether that is not used in collateralization uint256 _avlbl = _freeEth(_id); // Return available Ether to withdraw if (_avlbl == 0) { return 0; } uint256 _rest = boxes[_id].collateral.sub(_avlbl); if (_rest < settings.minDeposit()) { return boxes[_id].collateral.sub(settings.minDeposit()); } else return _avlbl; } /// @dev Given a Box ID, returns amount of ETH that is not used in collateralization. function _freeEth(uint256 _id) internal view returns(uint256) { // Grab a reference to the Box Box memory box = boxes[_id]; // When there are no tokens withdrawn if (box.tmvReleased == 0) { return box.collateral; } // The amount of Ether that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableEth(); uint256 _globalAvailable; if (_maxGlobal > 0) { // The amount of Ether backing the tokens when the system is overcapitalized uint256 _need = overCapFrozenEth(box.tmvReleased); if (box.collateral > _need) { // Free Ether amount when the system is overcapitalized uint256 _free = box.collateral.sub(_need); if (_free > _maxGlobal) { // Store available amount when Box available Ether amount // is more than global available _globalAvailable = _maxGlobal; } // Return available amount of Ether to withdraw when the Box withdrawable // amount of Ether is smaller than global withdrawable amount of Ether else return _free; } } // The amount of Ether backing the tokens by default uint256 _frozen = defaultFrozenEth(box.tmvReleased); if (box.collateral > _frozen) { // Define the biggest number and return available Ether amount uint256 _localAvailable = box.collateral.sub(_frozen); return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable; } else { // Return available Ether amount return _globalAvailable; } } /// @dev Given a Box ID, returns collateral percent. function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; if (box.tmvReleased == 0) { return 10**27; //some unreachable number } uint256 _ethCollateral = box.collateral; // division by 100 is not necessary because to get the percent you need to multiply by 100 return _ethCollateral.mul(rate()).div(box.tmvReleased); } /// @dev Checks if a given address currently has approval for a particular Box. /// @param _spender the address we are confirming Box is approved for. /// @param _tokenId Box ID. function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Returns the global collateralization percent. function globalCollateralization() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (_supply == 0) { return settings.globalTargetCollateralization(); } return globalETH.mul(rate()).div(_supply); } /// @dev Returns the number of tokens that can be safely withdrawn from the system. function globalWithdrawableTmv(uint256 _value) public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value)); return _totalBackedTmv.sub(_supply); } /// @dev Returns Ether amount that can be safely withdrawn from the system. function globalWithdrawableEth() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _need = defaultFrozenEth(_supply); return globalETH.sub(_need); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount by default. function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.globalTargetCollateralization(); return _num.div(_div); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount when the system is overcapitalized. function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.ratio(); return _num.div(_div); } /// @dev Returns Ether amount backing the specified number of tokens by default. function defaultFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.globalTargetCollateralization()).div(rate()); } /// @dev Returns Ether amount backing the specified number of tokens /// when the system is overcapitalized. function overCapFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.ratio()).div(rate()); } /// @dev Returns the number of TMV that can capitalize the specified Box. function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) { uint256 _colP = collateralPercent(_id); require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes"); Box memory box = boxes[_id]; uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate())); uint256 _div = settings.ratio().sub(settings.minStability()); return _num.div(_div); } /// @dev Returns the number of tokens that can be actually withdrawn /// for the specified collateral. function withdrawableTmv(uint256 _collateral) public view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(0); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _amount; } /// @dev Returns the collateral percentage for which tokens can be withdrawn /// for the specified collateral. function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title TBoxClassic Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} } pragma solidity 0.4.25; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } pragma solidity 0.4.25; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { require(_tokenOwner[tokenId] == address(0)); _tokenOwner[tokenId] = to; _ownedTokensCount[to] = _ownedTokensCount[to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity 0.4.25; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "./ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor () public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenTo(address to, uint256 tokenId) internal { super._addTokenTo(to, tokenId); uint256 length = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); _ownedTokensIndex[tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Reorg all tokens array uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 lastToken = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastToken; _allTokens[lastTokenIndex] = 0; _allTokens.length--; _allTokensIndex[tokenId] = 0; _allTokensIndex[lastToken] = tokenIndex; } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "./ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity 0.4.25; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity 0.4.25; import "./IERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } pragma solidity 0.4.25; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity 0.4.25; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity 0.4.25; /// @title IOracle /// @dev Interface for getting the data from the oracle contract. interface IOracle { function ethUsdPrice() external view returns(uint256); } pragma solidity 0.4.25; /// @title ISettings /// @dev Interface for getting the data from settings contract. interface ISettings { function oracleAddress() external view returns(address); function minDeposit() external view returns(uint256); function sysFee() external view returns(uint256); function userFee() external view returns(uint256); function ratio() external view returns(uint256); function globalTargetCollateralization() external view returns(uint256); function tmvAddress() external view returns(uint256); function maxStability() external view returns(uint256); function minStability() external view returns(uint256); function gasPriceLimit() external view returns(uint256); function isFeeManager(address account) external view returns (bool); function tBoxManager() external view returns(address); } pragma solidity 0.4.25; /// @title IToken /// @dev Interface for interaction with the TMV token contract. interface IToken { function burnLogic(address from, uint256 value) external; function approve(address spender, uint256 value) external; function balanceOf(address who) external view returns (uint256); function mint(address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 tokenId) external; } pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'mul'); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'div'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'sub'); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'add'); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.4.25; import "./TBoxToken.sol"; import "./ISettings.sol"; import "./IToken.sol"; import "./IOracle.sol"; /// @title TBoxManager contract TBoxManager is TBoxToken { // Total packed Ether uint256 public globalETH; // Precision using for USD and commission uint256 public precision = 100000; // The address of the system settings contract ISettings public settings; /// @dev An array containing the Boxes struct for all Boxes in existence. The ID /// of each Box is actually an index into this array. Box[] public boxes; /// @dev The main Box struct. Every Box in TimviSystem is represented by a copy /// of this structure. struct Box { // The collateral Ether amount in wei uint256 collateral; // The number of TMV withdrawn uint256 tmvReleased; } /// @dev The Created event is fired whenever a new Box comes into existence. This includes /// any time a Box is created through the create method. event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased); /// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes /// any time a Box is closed through the close method, but it is also called when // a Box is closed through the closeDust method. event Closed(uint256 indexed id, address indexed owner, address indexed closer); /// @dev The Capitalized event is fired whenever a Box is capitalized. event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth); /// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box /// using withdrawEth method. event EthWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box /// using withdrawTmv method. event TmvWithdrawn(uint256 indexed id, uint256 value, address who); /// @dev The EthAdded event is fired whenever Ether is added to a Box /// using addEth method. event EthAdded(uint256 indexed id, uint256 value, address who); /// @dev The TmvAdded event is fired whenever TMV is added to a Box /// using addTmv method. event TmvAdded(uint256 indexed id, uint256 value, address who); /// @dev Defends against front-running attacks. modifier validTx() { require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyAdmin() { require(settings.isFeeManager(msg.sender), "You have no access"); _; } /// @dev Throws if Box with specified id does not exist. modifier onlyExists(uint256 _id) { require(_exists(_id), "Box does not exist"); _; } /// @dev Access modifier for token owner-only functionality. modifier onlyApprovedOrOwner(uint256 _id) { require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your"); _; } /// @dev The constructor sets ERC721 token name and symbol. /// @param _settings The address of the system settings contract. constructor(address _settings) TBoxToken("TBoxToken", "TBX") public { settings = ISettings(_settings); } /// @notice The funds are safe. /// @dev Creates Box with max collateral percent. function() external payable { // Redirect to the create method with no tokens to withdraw create(0); } /// @dev Withdraws system fee. function withdrawFee(address _beneficiary) external onlyAdmin { require(_beneficiary != address(0), "Zero address, be careful"); // Fee is the difference between the contract balance and // amount of Ether used in the entire system collateralization uint256 _fees = address(this).balance.sub(globalETH); // Check that the fee is collected require(_fees > 0, "There is no available fees"); // Transfer fee to provided address _beneficiary.transfer(_fees); } /// @dev Checks possibility of the issue of the specified token amount /// for provided Ether collateral and creates new Box /// @param _tokensToWithdraw Number of tokens to withdraw /// @return New Box ID. function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) { // Check that msg.value isn't smaller than minimum deposit require(msg.value >= settings.minDeposit(), "Deposit is very small"); // Calculate collateralization when tokens are needed if (_tokensToWithdraw > 0) { // The number of tokens when collateralization is high uint256 _tokenLimit = overCapWithdrawableTmv(msg.value); // The number of tokens that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit > _maxGlobal) { _tokenLimit = _maxGlobal; } // The number of tokens that can be withdrawn anyway uint256 _local = defaultWithdrawableTmv(msg.value); // Determine the higher number of tokens if (_tokenLimit < _local) { _tokenLimit = _local; } // You can only withdraw available amount require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available"); // Mint TMV tokens to the Box creator IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw); } // The id of the new Box uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Mint TBX token to the Box creator _mint(msg.sender, _id); // Fire the event emit Created(_id, msg.sender, msg.value, _tokensToWithdraw); // return the new Box's ID return _id; } /// @dev Allows the owner or approved user of the Box to close one by burning the /// required number of tokens and return the Box's collateral. /// @param _id A Box ID to close. function close(uint256 _id) external onlyApprovedOrOwner(_id) { // Address of the owner of the Box address _owner = _tokenOwner[_id]; // Burn needed number of tokens uint256 _tokensNeed = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tokensNeed); // Grab a reference to the Box's collateral in storage uint256 _collateral = boxes[_id].collateral; // burn Box token _burn(_owner, _id); // Removes Box delete boxes[_id]; // Send the Box's collateral to the person who made closing happen msg.sender.transfer(_collateral); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows the user to capitalize a Box with the maximum current amount. /// @param _id A Box ID to capitalize. function capitalizeMax(uint256 _id) external { capitalize(_id, maxCapAmount(_id)); } /// @dev Allows the user to capitalize a Box with specified number of tokens. /// @param _id A Box ID to capitalize. /// @param _tmv Specified number of tokens to capitalize. function capitalize(uint256 _id, uint256 _tmv) public validTx { // The maximum number of tokens for which Box can be capitalized uint256 _maxCapAmount = maxCapAmount(_id); // Check the number of tokens require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range"); // Decrease Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv); // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _equivalentETH = _tmv.mul(precision).div(rate()); // Calculate system fee uint256 _fee = _tmv.mul(settings.sysFee()).div(rate()); // Calculate user bonus uint256 _userReward = _tmv.mul(settings.userFee()).div(rate()); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH)); // Decrease global Ether counter globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH)); // burn Box token _burnTMV(msg.sender, _tmv); // Send the Ether equivalent & user benefit to the person who made capitalization happen. msg.sender.transfer(_equivalentETH.add(_userReward)); // Fire the event emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward)); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum amount /// of Ether from the Box. /// @param _id A Box ID. function withdrawEthMax(uint256 _id) external { withdrawEth(_id, withdrawableEth(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified amount /// of Ether from the Box. /// @param _id A Box ID. /// @param _amount The number of Ether to withdraw. function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); require(_amount <= withdrawableEth(_id), "You can't withdraw so much"); // Decrease Box's collateral amount boxes[_id].collateral = boxes[_id].collateral.sub(_amount); // Decrease global Ether counter globalETH = globalETH.sub(_amount); // Send the Ether to the person who made capitalization happen msg.sender.transfer(_amount); // Fire the event emit EthWithdrawn(_id, _amount, msg.sender); } /// @notice This allows you not to be tied to the current ETH/USD rate. /// @dev Allows an owner or approved user of the Box to withdraw maximum number /// of TMV tokens from the Box. /// @param _id A Box ID. function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) { withdrawTmv(_id, boxWithdrawableTmv(_id)); } /// @dev Allows an owner or approved user of the Box to withdraw specified number /// of TMV tokens from the Box. /// @param _id A Box ID. /// @param _amount The number of tokens to withdraw. function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx { require(_amount > 0, "Withdrawing zero"); // Check the number of tokens require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much"); // Increase Box TMV withdrawn counter boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount); // Mints tokens to the person who made withdrawing IToken(settings.tmvAddress()).mint(msg.sender, _amount); // Fire the event emit TmvWithdrawn(_id, _amount, msg.sender); } /// @dev Allows anyone to add Ether to a Box. /// @param _id A Box ID. function addEth(uint256 _id) external payable onlyExists(_id) { require(msg.value > 0, "Don't add 0"); // Increase Box collateral boxes[_id].collateral = boxes[_id].collateral.add(msg.value); // Increase global Ether counter globalETH = globalETH.add(msg.value); // Fire the event emit EthAdded(_id, msg.value, msg.sender); } /// @dev Allows anyone to add TMV to a Box. /// @param _id A Box ID. /// @param _amount The number of tokens to add. function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) { require(_amount > 0, "Don't add 0"); // Check the number of tokens require(_amount <= boxes[_id].tmvReleased, "Too much tokens"); // Removes added tokens from the collateralization _burnTMV(msg.sender, _amount); boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount); // Fire the event emit TmvAdded(_id, _amount, msg.sender); } /// @dev Allows anyone to close Box with collateral amount smaller than 3 USD. /// The person who made closing happen will benefit like capitalization. /// @param _id A Box ID. function closeDust(uint256 _id) external onlyExists(_id) validTx { // Check collateral percent of the Box require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable"); // Check collateral amount of the Box require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust"); // Burn needed TMV amount to close uint256 _tmvReleased = boxes[_id].tmvReleased; _burnTMV(msg.sender, _tmvReleased); uint256 _collateral = boxes[_id].collateral; // Calculate the Ether equivalent of tokens according to the logic // where 1 TMV is equal to 1 USD uint256 _eth = _tmvReleased.mul(precision).div(rate()); // Calculate user bonus uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate()); // The owner of the Box address _owner = ownerOf(_id); // Remove a Box delete boxes[_id]; // Burn Box token _burn(_owner, _id); // Send the Ether equivalent & user benefit to the person who made closing happen msg.sender.transfer(_eth.add(_userReward)); // Decrease global Ether counter globalETH = globalETH.sub(_collateral); // Fire the event emit Closed(_id, _owner, msg.sender); } /// @dev Burns specified number of TMV tokens. function _burnTMV(address _from, uint256 _amount) internal { if (_amount > 0) { require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens"); IToken(settings.tmvAddress()).burnLogic(_from, _amount); } } /// @dev Returns current oracle ETH/USD price with precision. function rate() public view returns(uint256) { return IOracle(settings.oracleAddress()).ethUsdPrice(); } /// @dev Given a Box ID, returns a number of tokens that can be withdrawn. function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; // Number of tokens that can be withdrawn for Box's collateral uint256 _amount = withdrawableTmv(box.collateral); if (box.tmvReleased >= _amount) { return 0; } // Return withdrawable rest return _amount.sub(box.tmvReleased); } /// @dev Given a Box ID, returns an amount of Ether that can be withdrawn. function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) { // Amount of Ether that is not used in collateralization uint256 _avlbl = _freeEth(_id); // Return available Ether to withdraw if (_avlbl == 0) { return 0; } uint256 _rest = boxes[_id].collateral.sub(_avlbl); if (_rest < settings.minDeposit()) { return boxes[_id].collateral.sub(settings.minDeposit()); } else return _avlbl; } /// @dev Given a Box ID, returns amount of ETH that is not used in collateralization. function _freeEth(uint256 _id) internal view returns(uint256) { // Grab a reference to the Box Box memory box = boxes[_id]; // When there are no tokens withdrawn if (box.tmvReleased == 0) { return box.collateral; } // The amount of Ether that can be safely withdrawn from the system uint256 _maxGlobal = globalWithdrawableEth(); uint256 _globalAvailable; if (_maxGlobal > 0) { // The amount of Ether backing the tokens when the system is overcapitalized uint256 _need = overCapFrozenEth(box.tmvReleased); if (box.collateral > _need) { // Free Ether amount when the system is overcapitalized uint256 _free = box.collateral.sub(_need); if (_free > _maxGlobal) { // Store available amount when Box available Ether amount // is more than global available _globalAvailable = _maxGlobal; } // Return available amount of Ether to withdraw when the Box withdrawable // amount of Ether is smaller than global withdrawable amount of Ether else return _free; } } // The amount of Ether backing the tokens by default uint256 _frozen = defaultFrozenEth(box.tmvReleased); if (box.collateral > _frozen) { // Define the biggest number and return available Ether amount uint256 _localAvailable = box.collateral.sub(_frozen); return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable; } else { // Return available Ether amount return _globalAvailable; } } /// @dev Given a Box ID, returns collateral percent. function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) { Box memory box = boxes[_id]; if (box.tmvReleased == 0) { return 10**27; //some unreachable number } uint256 _ethCollateral = box.collateral; // division by 100 is not necessary because to get the percent you need to multiply by 100 return _ethCollateral.mul(rate()).div(box.tmvReleased); } /// @dev Checks if a given address currently has approval for a particular Box. /// @param _spender the address we are confirming Box is approved for. /// @param _tokenId Box ID. function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Returns the global collateralization percent. function globalCollateralization() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (_supply == 0) { return settings.globalTargetCollateralization(); } return globalETH.mul(rate()).div(_supply); } /// @dev Returns the number of tokens that can be safely withdrawn from the system. function globalWithdrawableTmv(uint256 _value) public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value)); return _totalBackedTmv.sub(_supply); } /// @dev Returns Ether amount that can be safely withdrawn from the system. function globalWithdrawableEth() public view returns (uint256) { uint256 _supply = IToken(settings.tmvAddress()).totalSupply(); if (globalCollateralization() <= settings.globalTargetCollateralization()) { return 0; } uint256 _need = defaultFrozenEth(_supply); return globalETH.sub(_need); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount by default. function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.globalTargetCollateralization(); return _num.div(_div); } /// @dev Returns the number of tokens that can be withdrawn /// for the specified collateral amount when the system is overcapitalized. function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) { uint256 _num = _collateral.mul(rate()); uint256 _div = settings.ratio(); return _num.div(_div); } /// @dev Returns Ether amount backing the specified number of tokens by default. function defaultFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.globalTargetCollateralization()).div(rate()); } /// @dev Returns Ether amount backing the specified number of tokens /// when the system is overcapitalized. function overCapFrozenEth(uint256 _supply) public view returns (uint256) { return _supply.mul(settings.ratio()).div(rate()); } /// @dev Returns the number of TMV that can capitalize the specified Box. function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) { uint256 _colP = collateralPercent(_id); require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes"); Box memory box = boxes[_id]; uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate())); uint256 _div = settings.ratio().sub(settings.minStability()); return _num.div(_div); } /// @dev Returns the number of tokens that can be actually withdrawn /// for the specified collateral. function withdrawableTmv(uint256 _collateral) public view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(0); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _amount; } /// @dev Returns the collateral percentage for which tokens can be withdrawn /// for the specified collateral. function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); } } pragma solidity 0.4.25; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title TBoxClassic Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} }
Returns the collateral percentage for which tokens can be withdrawn for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) { uint256 _amount = overCapWithdrawableTmv(_collateral); uint256 _maxGlobal = globalWithdrawableTmv(_collateral); if (_amount > _maxGlobal) { _amount = _maxGlobal; } uint256 _local = defaultWithdrawableTmv(_collateral); if (_amount < _local) { _amount = _local; } return _collateral.mul(rate()).div(_amount); }
911,902
./partial_match/1/0x2229dafca41c44ceFf70D8b94aF51406A4D61FFD/sources/CocaCola.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Coca Cola Inu", unicode"CocaCola") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,664,915
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.8.3 https://hardhat.org // File contracts/Math/Math.sol /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File contracts/Curve/IveFXS.sol pragma abicoder v2; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } function commit_transfer_ownership(address addr) external; function apply_transfer_ownership() external; function commit_smart_wallet_checker(address addr) external; function apply_smart_wallet_checker() external; function toggleEmergencyUnlock() external; function recoverERC20(address token_addr, uint256 amount) external; function get_last_user_slope(address addr) external view returns (int128); function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256); function locked__end(address _addr) external view returns (uint256); function checkpoint() external; function deposit_for(address _addr, uint256 _value) external; function create_lock(uint256 _value, uint256 _unlock_time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external view returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external view returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function changeController(address _newController) external; function token() external view returns (address); function supply() external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); function epoch() external view returns (uint256); function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_epoch(address arg0) external view returns (uint256); function slope_changes(uint256 arg0) external view returns (int128); function controller() external view returns (address); function transfersEnabled() external view returns (bool); function emergencyUnlockActive() external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint256); function future_smart_wallet_checker() external view returns (address); function smart_wallet_checker() external view returns (address); function admin() external view returns (address); function future_admin() external view returns (address); } // File contracts/Curve/IFraxGaugeController.sol // https://github.com/swervefi/swerve/edit/master/packages/swerve-contracts/interfaces/IGaugeController.sol interface IFraxGaugeController { struct Point { uint256 bias; uint256 slope; } struct VotedSlope { uint256 slope; uint256 power; uint256 end; } // Public variables function admin() external view returns (address); function future_admin() external view returns (address); function token() external view returns (address); function voting_escrow() external view returns (address); function n_gauge_types() external view returns (int128); function n_gauges() external view returns (int128); function gauge_type_names(int128) external view returns (string memory); function gauges(uint256) external view returns (address); function vote_user_slopes(address, address) external view returns (VotedSlope memory); function vote_user_power(address) external view returns (uint256); function last_user_vote(address, address) external view returns (uint256); function points_weight(address, uint256) external view returns (Point memory); function time_weight(address) external view returns (uint256); function points_sum(int128, uint256) external view returns (Point memory); function time_sum(uint256) external view returns (uint256); function points_total(uint256) external view returns (uint256); function time_total() external view returns (uint256); function points_type_weight(int128, uint256) external view returns (uint256); function time_type_weight(uint256) external view returns (uint256); // Getter functions function gauge_types(address) external view returns (int128); function gauge_relative_weight(address) external view returns (uint256); function gauge_relative_weight(address, uint256) external view returns (uint256); function get_gauge_weight(address) external view returns (uint256); function get_type_weight(int128) external view returns (uint256); function get_total_weight() external view returns (uint256); function get_weights_sum_per_type(int128) external view returns (uint256); // External functions function commit_transfer_ownership(address) external; function apply_transfer_ownership() external; function add_gauge( address, int128, uint256 ) external; function checkpoint() external; function checkpoint_gauge(address) external; function global_emission_rate() external view returns (uint256); function gauge_relative_weight_write(address) external returns (uint256); function gauge_relative_weight_write(address, uint256) external returns (uint256); function add_type(string memory, uint256) external; function change_type_weight(int128, uint256) external; function change_gauge_weight(address, uint256) external; function change_global_emission_rate(uint256) external; function vote_for_gauge_weights(address, uint256) external; } // File contracts/Curve/IFraxGaugeFXSRewardsDistributor.sol interface IFraxGaugeFXSRewardsDistributor { function acceptOwnership() external; function curator_address() external view returns(address); function currentReward(address gauge_address) external view returns(uint256 reward_amount); function distributeReward(address gauge_address) external returns(uint256 weeks_elapsed, uint256 reward_tally); function distributionsOn() external view returns(bool); function gauge_whitelist(address) external view returns(bool); function is_middleman(address) external view returns(bool); function last_time_gauge_paid(address) external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function owner() external view returns(address); function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function setCurator(address _new_curator_address) external; function setGaugeController(address _gauge_controller_address) external; function setGaugeState(address _gauge_address, bool _is_middleman, bool _is_active) external; function setTimelock(address _new_timelock) external; function timelock_address() external view returns(address); function toggleDistributions() external; } // File contracts/Common/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/Math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/Utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/Utils/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Staking/FraxUnifiedFarmTemplate.sol pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ====================== FraxUnifiedFarmTemplate ===================== // ==================================================================== // Migratable Farming contract that accounts for veFXS // Overrideable for UniV3, ERC20s, etc // New for V2 // - Two reward tokens possible // - Can add to existing locked stakes // - Contract is aware of proxied veFXS // - veFXS multiplier formula changed // Apes together strong // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Dennis: github.com/denett // Sam Sun: https://github.com/samczsun // Originally inspired by Synthetix.io, but heavily modified by the Frax team // (Locked, veFXS, and UniV3 portions are new) // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol contract FraxUnifiedFarmTemplate is Owned, ReentrancyGuard { using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS = IveFXS(0xc8418aF6358FFddA74e09Ca9CC3Fe03Ca6aDC5b0); // Frax related address internal frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e; bool internal frax_is_token0; uint256 private fraxPerLPStored; // Constant for various precisions uint256 internal constant MULTIPLIER_PRECISION = 1e18; // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_boost_scale_factor = uint256(4e18); // E18. 4x = 4e18; 100 / scale_factor = % vefxs supply needed for max boost uint256 public vefxs_max_multiplier = uint256(2e18); // E18. 1x = 1e18 uint256 public vefxs_per_frax_for_max_boost = uint256(2e18); // E18. 2e18 means 2 veFXS must be held by the staker per 1 FRAX mapping(address => uint256) internal _vefxsMultiplierStored; mapping(address => bool) internal valid_vefxs_proxies; mapping(address => mapping(address => bool)) internal proxy_allowed_stakers; // Reward addresses, gauge addresses, reward rates, and reward managers mapping(address => address) public rewardManagers; // token addr -> manager addr address[] internal rewardTokens; address[] internal gaugeControllers; address[] internal rewardDistributors; uint256[] internal rewardRatesManual; mapping(address => uint256) public rewardTokenAddrToIdx; // token addr -> token index // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256[] private rewardsPerTokenStored; mapping(address => mapping(uint256 => uint256)) private userRewardsPerTokenPaid; // staker addr -> token id -> paid amount mapping(address => mapping(uint256 => uint256)) private rewards; // staker addr -> token id -> reward amount mapping(address => uint256) internal lastRewardClaimTime; // staker addr -> timestamp // Gauge tracking uint256[] private last_gauge_relative_weights; uint256[] private last_gauge_time_totals; // Balance tracking uint256 internal _total_liquidity_locked; uint256 internal _total_combined_weight; mapping(address => uint256) internal _locked_liquidity; mapping(address => uint256) internal _combined_weights; // List of valid migrators (set by governance) mapping(address => bool) internal valid_migrators; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) internal staker_allowed_migrators; mapping(address => address) public staker_designated_proxies; // Keep public so users can see on the frontend if they have a proxy // Greylists mapping(address => bool) internal greylist; // Admin booleans for emergencies, migrations, and overrides bool public stakesUnlocked; // Release locked stakes in case of emergency bool internal migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool internal withdrawalsPaused; // For emergencies bool internal rewardsCollectionPaused; // For emergencies bool internal stakingPaused; // For emergencies /* ========== STRUCTS ========== */ // In children... /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == 0x8412ebf45bAC1B340BbE8F318b928C466c4E39CA, "Not owner or timelock"); _; } modifier onlyTknMgrs(address reward_token_address) { require(msg.sender == owner || isTokenManagerFor(msg.sender, reward_token_address), "Not owner or tkn mgr"); _; } modifier isMigrating() { require(migrationsOn == true, "Not in migration"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers, address[] memory _rewardDistributors ) Owned(_owner) { // Address arrays rewardTokens = _rewardTokens; gaugeControllers = _gaugeControllers; rewardDistributors = _rewardDistributors; rewardRatesManual = _rewardRatesManual; for (uint256 i = 0; i < _rewardTokens.length; i++){ // For fast token address -> token ID lookups later rewardTokenAddrToIdx[_rewardTokens[i]] = i; // Initialize the stored rewards rewardsPerTokenStored.push(0); // Initialize the reward managers rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; // Push in empty relative weights to initialize the array last_gauge_relative_weights.push(0); // Push in empty time totals to initialize the array last_gauge_time_totals.push(0); } // Other booleans stakesUnlocked = false; // Initialization lastUpdateTime = block.timestamp; periodFinish = block.timestamp + rewardsDuration; } /* ============= VIEWS ============= */ // ------ REWARD RELATED ------ // See if the caller_addr is a manager for the reward token function isTokenManagerFor(address caller_addr, address reward_token_addr) public view returns (bool){ if (caller_addr == owner) return true; // Contract owner else if (rewardManagers[reward_token_addr] == caller_addr) return true; // Reward manager return false; } // All the reward tokens function getAllRewardTokens() external view returns (address[] memory) { return rewardTokens; } // Last time the reward was applicable function lastTimeRewardApplicable() internal view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate() * last_gauge_relative_weights[token_idx]) / 1e18; } else { rwd_rate = rewardRatesManual[token_idx]; } } // Amount of reward tokens per LP token / liquidity unit function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i] + ( ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRates(i) * 1e18) / _total_combined_weight ); } return newRewardsPerTokenStored; } } // Amount of reward tokens an account has earned / accrued // Note: In the edge-case of one of the account's stake expiring since the last claim, this will // return a slightly inflated number function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] > 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) + rewards[account][i]; } } // if (_combined_weights[account] == 0){ // for (uint256 i = 0; i < rewardTokens.length; i++){ // new_earned[i] = 0; // } // } // else { // for (uint256 i = 0; i < rewardTokens.length; i++){ // new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) // + rewards[account][i]; // } // } } // Total reward tokens emitted in the given period function getRewardForDuration() external view returns (uint256[] memory rewards_per_duration_arr) { rewards_per_duration_arr = new uint256[](rewardRatesManual.length); for (uint256 i = 0; i < rewardRatesManual.length; i++){ rewards_per_duration_arr[i] = rewardRates(i) * rewardsDuration; } } // ------ LIQUIDITY AND WEIGHTS ------ // User locked liquidity / LP tokens function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } // Total locked liquidity / LP tokens function lockedLiquidityOf(address account) external view returns (uint256) { return _locked_liquidity[account]; } // Total combined weight function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier and veFXS multiplier function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public virtual view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { revert("Need cCCW logic"); } // ------ LOCK RELATED ------ // Multiplier amount, given the length of the lock function lockMultiplier(uint256 secs) public view returns (uint256) { return Math.min( lock_max_multiplier, uint256(MULTIPLIER_PRECISION) + ( (secs * (lock_max_multiplier - MULTIPLIER_PRECISION)) / lock_time_for_max_multiplier ) ) ; } // ------ FRAX RELATED ------ function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPStored * _locked_liquidity[account]) / MULTIPLIER_PRECISION; } // Meant to be overridden function fraxPerLPToken() public virtual view returns (uint256) { revert("Need fPLPT logic"); } // ------ veFXS RELATED ------ function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account) * vefxs_per_frax_for_max_boost) / MULTIPLIER_PRECISION; } function veFXSMultiplier(address account) public view returns (uint256 vefxs_multiplier) { // Use either the user's or their proxy's veFXS balance uint256 vefxs_bal_to_use = 0; { uint256 vefxs_user_bal = veFXS.balanceOf(account); uint256 vefxs_proxy_bal = veFXS.balanceOf(staker_designated_proxies[account]); vefxs_bal_to_use = (vefxs_user_bal > vefxs_proxy_bal ? vefxs_user_bal : vefxs_proxy_bal); } // First option based on fraction of total veFXS supply, with an added scale factor uint256 mult_optn_1 = (vefxs_bal_to_use * vefxs_max_multiplier * vefxs_boost_scale_factor) / (veFXS.totalSupply() * MULTIPLIER_PRECISION); // Second based on old method, where the amount of FRAX staked comes into play uint256 mult_optn_2; { uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (vefxs_bal_to_use * MULTIPLIER_PRECISION) / veFXS_needed_for_max_boost; mult_optn_2 = (user_vefxs_fraction * vefxs_max_multiplier) / MULTIPLIER_PRECISION; } else mult_optn_2 = 0; // This will happen with the first stake, when user_staked_frax is 0 } // Select the higher of the three vefxs_multiplier = (mult_optn_1 > mult_optn_2 ? mult_optn_1 : mult_optn_2); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; } /* =============== MUTATIVE FUNCTIONS =============== */ // ------ MIGRATIONS ------ // Staker can allow a migrator function stakerToggleMigrator(address migrator_address) external { require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = !staker_allowed_migrators[msg.sender][migrator_address]; } // Staker can allow a veFXS proxy (the proxy will have to toggle them first) function stakerSetVeFXSProxy(address proxy_address) external { require(valid_vefxs_proxies[proxy_address], "Invalid proxy"); require(proxy_allowed_stakers[proxy_address][msg.sender], "Proxy has not allowed you"); staker_designated_proxies[msg.sender] = proxy_address; } // Proxy can allow a staker to use their veFXS balance (the staker will have to reciprocally toggle them too) // Must come before stakerSetVeFXSProxy function proxyToggleStaker(address staker_address) external { require(valid_vefxs_proxies[msg.sender], "Invalid proxy"); proxy_allowed_stakers[msg.sender][staker_address] = !proxy_allowed_stakers[msg.sender][staker_address]; // Disable the staker's set proxy if it was the toggler and is currently on if (staker_designated_proxies[staker_address] == msg.sender){ staker_designated_proxies[staker_address] = address(0); } } // ------ STAKING ------ // In children... // ------ WITHDRAWING ------ // In children... // ------ REWARDS SYNCING ------ function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight - old_combined_weight; _total_combined_weight = _total_combined_weight + weight_diff; _combined_weights[account] = old_combined_weight + weight_diff; } else { uint256 weight_diff = old_combined_weight - new_combined_weight; _total_combined_weight = _total_combined_weight - weight_diff; _combined_weights[account] = old_combined_weight - weight_diff; } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings uint256[] memory earned_arr = earned(account); // Update the rewards array for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } // Update the rewards paid array for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } // ------ REWARDS CLAIMING ------ function _getRewardExtraLogic(address rewardee, address destination_address) internal virtual { revert("Need gREL logic"); } // Two different getReward functions are needed because of delegateCall and msg.sender issues function getReward(address destination_address) external nonReentrant returns (uint256[] memory) { require(rewardsCollectionPaused == false, "Rewards collection paused"); return _getReward(msg.sender, destination_address); } // No withdrawer == msg.sender check needed since this is only internally callable function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256[] memory rewards_before) { // Update the rewards array and distribute rewards rewards_before = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ rewards_before[i] = rewards[rewardee][i]; rewards[rewardee][i] = 0; TransferHelper.safeTransfer(rewardTokens[i], destination_address, rewards_before[i]); } // Handle additional reward logic _getRewardExtraLogic(rewardee, destination_address); // Update the last reward claim time lastRewardClaimTime[rewardee] = block.timestamp; } // ------ FARM SYNCING ------ // If the period expired, renew it function retroCatchUp() internal { // Pull in rewards from the rewards distributor, if applicable for (uint256 i = 0; i < rewardDistributors.length; i++){ address reward_distributor_address = rewardDistributors[i]; if (reward_distributor_address != address(0)) { IFraxGaugeFXSRewardsDistributor(reward_distributor_address).distributeReward(address(this)); } } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 num_periods_elapsed = uint256(block.timestamp - periodFinish) / rewardsDuration; // Floor division to the nearest period // Make sure there are enough tokens to renew the reward period for (uint256 i = 0; i < rewardTokens.length; i++){ require((rewardRates(i) * rewardsDuration * (num_periods_elapsed + 1)) <= ERC20(rewardTokens[i]).balanceOf(address(this)), string(abi.encodePacked("Not enough reward tokens available: ", rewardTokens[i])) ); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish + ((num_periods_elapsed + 1) * rewardsDuration); // Update the rewards and time _updateStoredRewardsAndTime(); // Update the fraxPerLPStored fraxPerLPStored = fraxPerLPToken(); } function _updateStoredRewardsAndTime() internal { // Get the rewards uint256[] memory rewards_per_token = rewardsPerToken(); // Update the rewardsPerTokenStored for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ rewardsPerTokenStored[i] = rewards_per_token[i]; } // Update the last stored time lastUpdateTime = lastTimeRewardApplicable(); } function sync_gauge_weights(bool force_update) public { // Loop through the gauge controllers for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ // Update the gauge_relative_weight last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync() public { // Sync the gauge weight, if applicable sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } function sync_other() external { // Update the fraxPerLPStored fraxPerLPStored = fraxPerLPToken(); } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // ------ FARM SYNCING ------ // In children... // ------ PAUSES AND GREYLISTING ------ function setPauses( bool _stakingPaused, bool _withdrawalsPaused, bool _rewardsCollectionPaused ) external onlyByOwnGov { stakingPaused = _stakingPaused; withdrawalsPaused = _withdrawalsPaused; rewardsCollectionPaused = _rewardsCollectionPaused; } function greylistAddress(address _address) external onlyByOwnGov { greylist[_address] = !(greylist[_address]); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ function unlockStakes() external onlyByOwnGov { stakesUnlocked = !stakesUnlocked; } function toggleMigrations() external onlyByOwnGov { migrationsOn = !migrationsOn; } // Adds supported migrator address function toggleMigrator(address migrator_address) external onlyByOwnGov { valid_migrators[migrator_address] = !valid_migrators[migrator_address]; } // Adds a valid veFXS proxy address function toggleValidVeFXSProxy(address _proxy_addr) external onlyByOwnGov { valid_vefxs_proxies[_proxy_addr] = !valid_vefxs_proxies[_proxy_addr]; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { // Check if the desired token is a reward token bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } // Only the reward managers can take back their reward tokens // Also, other tokens, like the staking token, airdrops, or accidental deposits, can be withdrawn by the owner if ( (isRewardToken && rewardManagers[tokenAddress] == msg.sender) || (!isRewardToken && (msg.sender == owner)) ) { TransferHelper.safeTransfer(tokenAddress, msg.sender, tokenAmount); return; } // If none of the above conditions are true else { revert("No valid tokens to recover"); } } function setMiscVariables( uint256[6] memory _misc_vars // [0]: uint256 _lock_max_multiplier, // [1] uint256 _vefxs_max_multiplier, // [2] uint256 _vefxs_per_frax_for_max_boost, // [3] uint256 _vefxs_boost_scale_factor, // [4] uint256 _lock_time_for_max_multiplier, // [5] uint256 _lock_time_min ) external onlyByOwnGov { require(_misc_vars[0] >= MULTIPLIER_PRECISION, "Must be >= MUL PREC"); require((_misc_vars[1] >= 0) && (_misc_vars[2] >= 0) && (_misc_vars[3] >= 0), "Must be >= 0"); require((_misc_vars[4] >= 1) && (_misc_vars[5] >= 1), "Must be >= 1"); lock_max_multiplier = _misc_vars[0]; vefxs_max_multiplier = _misc_vars[1]; vefxs_per_frax_for_max_boost = _misc_vars[2]; vefxs_boost_scale_factor = _misc_vars[3]; lock_time_for_max_multiplier = _misc_vars[4]; lock_time_min = _misc_vars[5]; } // The owner or the reward token managers can set reward rates function setRewardVars(address reward_token_address, uint256 _new_rate, address _gauge_controller_address, address _rewards_distributor_address) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = _new_rate; gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewardDistributors[rewardTokenAddrToIdx[reward_token_address]] = _rewards_distributor_address; } // The owner or the reward token managers can change managers function changeTokenManager(address reward_token_address, address new_manager_address) external onlyTknMgrs(reward_token_address) { rewardManagers[reward_token_address] = new_manager_address; } /* ========== A CHICKEN ========== */ // // ,~. // ,-'__ `-, // {,-' `. } ,') // ,( a ) `-.__ ,',')~, // <=.) ( `-.__,==' ' ' '} // ( ) /) // `-'\ , ) // | \ `~. / // \ `._ \ / // \ `._____,' ,' // `-. ,' // `-._ _,-' // 77jj' // //_|| // __//--'/` // ,--'/` ' // // [hjw] https://textart.io/art/vw6Sa3iwqIRGkZsN1BC2vweF/chicken } // File contracts/Misc_AMOs/vesper/IVPool.sol interface IVPool { function DOMAIN_SEPARATOR() external view returns (bytes32); function MAX_BPS() external view returns (uint256); function VERSION() external view returns (string memory); function acceptGovernorship() external; function addInList(address _listToUpdate, address _addressToAdd) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function availableCreditLimit(address _strategy) external view returns (uint256); function balanceOf(address account) external view returns (uint256); function convertFrom18(uint256 _amount) external view returns (uint256); function decimalConversionFactor() external view returns (uint256); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function deposit(uint256 _amount) external; function depositWithPermit(uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external; function excessDebt(address _strategy) external view returns (uint256); function feeCollector() external view returns (address); function feeWhitelist() external view returns (address); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function governor() external view returns (address); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function initialize(string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory) external; function keepers() external view returns (address); function maintainers() external view returns (address); function migrateStrategy(address _old, address _new) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function name() external view returns (string memory); function nonces(address) external view returns (uint256); function open() external; function pause() external; function paused() external view returns (bool); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function poolAccountant() external view returns (address); function poolRewards() external view returns (address); function pricePerShare() external view returns (uint256); function removeFromList(address _listToUpdate, address _addressToRemove) external; function reportEarning(uint256 _profit, uint256 _loss, uint256 _payback) external; function reportLoss(uint256 _loss) external; function shutdown() external; function stopEverything() external view returns (bool); function strategy(address _strategy) external view returns (bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio); function sweepERC20(address _fromToken) external; function symbol() external view returns (string memory); function token() external view returns (address); function tokensHere() external view returns (uint256); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); function totalSupply() external view returns (uint256); function totalValue() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferGovernorship(address _proposedGovernor) external; function unpause() external; function updateFeeCollector(address _newFeeCollector) external; function updatePoolRewards(address _newPoolRewards) external; function updateWithdrawFee(uint256 _newWithdrawFee) external; function whitelistedWithdraw(uint256 _shares) external; function withdraw(uint256 _shares) external; function withdrawFee() external view returns (uint256); } // File contracts/Staking/FraxUnifiedFarm_ERC20.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxUnifiedFarm_ERC20 ====================== // ==================================================================== // For ERC20 Tokens // Uses FraxUnifiedFarmTemplate.sol // -------------------- VARIES -------------------- // G-UNI // import "../Misc_AMOs/gelato/IGUniPool.sol"; // mStable // import '../Misc_AMOs/mstable/IFeederPool.sol'; // // StakeDAO sdETH-FraxPut // import '../Misc_AMOs/stakedao/IOpynPerpVault.sol'; // StakeDAO Vault // import '../Misc_AMOs/stakedao/IStakeDaoVault.sol'; // Uniswap V2 // import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; // Vesper // ------------------------------------------------ contract FraxUnifiedFarm_ERC20 is FraxUnifiedFarmTemplate { /* ========== STATE VARIABLES ========== */ // -------------------- VARIES -------------------- // G-UNI // IGUniPool public stakingToken; // mStable // IFeederPool public stakingToken; // sdETH-FraxPut Vault // IOpynPerpVault public stakingToken; // StakeDAO Vault // IStakeDaoVault public stakingToken; // Uniswap V2 // IUniswapV2Pair public stakingToken; // Vesper IVPool public stakingToken; // ------------------------------------------------ // Stake tracking mapping(address => LockedStake[]) public lockedStakes; /* ========== STRUCTS ========== */ // Struct for the stake struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers, address[] memory _rewardDistributors, address _stakingToken ) FraxUnifiedFarmTemplate(_owner, _rewardTokens, _rewardManagers, _rewardRatesManual, _gaugeControllers, _rewardDistributors) { // -------------------- VARIES -------------------- // G-UNI // stakingToken = IGUniPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // mStable // stakingToken = IFeederPool(_stakingToken); // StakeDAO sdETH-FraxPut Vault // stakingToken = IOpynPerpVault(_stakingToken); // StakeDAO Vault // stakingToken = IStakeDaoVault(_stakingToken); // Uniswap V2 // stakingToken = IUniswapV2Pair(_stakingToken); // address token0 = stakingToken.token0(); // if (token0 == frax_address) frax_is_token0 = true; // else frax_is_token0 = false; // Vesper stakingToken = IVPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // ------------------------------------------------ } /* ============= VIEWS ============= */ // ------ FRAX RELATED ------ function fraxPerLPToken() public view override returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; // G-UNI // ============================================ // { // (uint256 reserve0, uint256 reserve1) = stakingToken.getUnderlyingBalances(); // uint256 total_frax_reserves = frax_is_token0 ? reserve0 : reserve1; // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // mStable // ============================================ // { // uint256 total_frax_reserves; // (, IFeederPool.BassetData memory vaultData) = (stakingToken.getBasset(frax_address)); // total_frax_reserves = uint256(vaultData.vaultBalance); // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // StakeDAO sdETH-FraxPut Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.totalUnderlyingControlled(); // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = ((frax3crv_held * 1e18) / stakingToken.totalSupply()) / 2; // } // StakeDAO Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.balance(); // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = ((frax3crv_held * 1e18) / stakingToken.totalSupply()) / 2; // } // Uniswap V2 // ============================================ // { // uint256 total_frax_reserves; // (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); // if (frax_is_token0) total_frax_reserves = reserve0; // else total_frax_reserves = reserve1; // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // Vesper // ============================================ frax_per_lp_token = stakingToken.pricePerShare(); return frax_per_lp_token; } // ------ LIQUIDITY AND WEIGHTS ------ // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public override view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { // This is only called for the first stake to make sure the veFXS multiplier is not cut in half midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2; } // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock is expired if (thisStake.ending_timestamp <= block.timestamp) { // If the lock expired in the time since the last claim, the weight needs to be proportionately averaged this time if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = thisStake.ending_timestamp - lastRewardClaimTime[account]; uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp; // Get the weighted-average lock_multiplier uint256 numerator = (lock_multiplier * time_before_expiry) + (MULTIPLIER_PRECISION * time_after_expiry); lock_multiplier = numerator / (time_before_expiry + time_after_expiry); } // Otherwise, it needs to just be 1x else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = (liquidity * (lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION; new_combined_weight = new_combined_weight + combined_boosted_amount; } } // ------ LOCK RELATED ------ // All the locked stakes for a given account function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } // Returns the length of the locked stakes for a given account function lockedStakesOfLength(address account) external view returns (uint256) { return lockedStakes[account].length; } // // All the locked stakes for a given account [old-school method] // function lockedStakesOfMultiArr(address account) external view returns ( // bytes32[] memory kek_ids, // uint256[] memory start_timestamps, // uint256[] memory liquidities, // uint256[] memory ending_timestamps, // uint256[] memory lock_multipliers // ) { // for (uint256 i = 0; i < lockedStakes[account].length; i++){ // LockedStake memory thisStake = lockedStakes[account][i]; // kek_ids[i] = thisStake.kek_id; // start_timestamps[i] = thisStake.start_timestamp; // liquidities[i] = thisStake.liquidity; // ending_timestamps[i] = thisStake.ending_timestamp; // lock_multipliers[i] = thisStake.lock_multiplier; // } // } /* =============== MUTATIVE FUNCTIONS =============== */ // ------ STAKING ------ function _getStake(address staker_address, bytes32 kek_id) internal view returns (LockedStake memory locked_stake, uint256 arr_idx) { for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ locked_stake = lockedStakes[staker_address][i]; arr_idx = i; break; } } require(locked_stake.kek_id == kek_id, "Stake not found"); } // Add additional LPs to an existing locked stake function lockAdditional(bytes32 kek_id, uint256 addl_liq) updateRewardAndBalance(msg.sender, true) public { // Get the stake and its index (LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id); // Calculate the new amount uint256 new_amt = thisStake.liquidity + addl_liq; // Checks require(addl_liq >= 0, "Must be nonzero"); // Pull the tokens from the sender TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), addl_liq); // Update the stake lockedStakes[msg.sender][theArrayIndex] = LockedStake( kek_id, thisStake.start_timestamp, new_amt, thisStake.ending_timestamp, thisStake.lock_multiplier ); // Update liquidities _total_liquidity_locked += addl_liq; _locked_liquidity[msg.sender] += addl_liq; // Need to call to update the combined weights _updateRewardAndBalance(msg.sender, false); } // Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration) function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant external { _stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp); } function _stakeLockedInternalLogic( address source_address, uint256 liquidity ) internal virtual { revert("Need _stakeLockedInternalLogic logic"); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked( address staker_address, address source_address, uint256 liquidity, uint256 secs, uint256 start_timestamp ) internal updateRewardAndBalance(staker_address, true) { require(stakingPaused == false || valid_migrators[msg.sender] == true, "Staking paused or in migration"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long"); // Pull in the required token(s) // Varies per farm TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Get the lock multiplier and kek_id uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address])); // Create the locked stake lockedStakes[staker_address].push(LockedStake( kek_id, start_timestamp, liquidity, start_timestamp + secs, lock_multiplier )); // Update liquidities _total_liquidity_locked += liquidity; _locked_liquidity[staker_address] += liquidity; // Need to call again to make sure everything is correct _updateRewardAndBalance(staker_address, false); emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // ------ WITHDRAWING ------ // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration) function withdrawLocked(bytes32 kek_id, address destination_address) nonReentrant external { require(withdrawalsPaused == false, "Withdrawals paused"); _withdrawLocked(msg.sender, destination_address, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like migrator_withdraw_locked() and withdrawLocked() function _withdrawLocked( address staker_address, address destination_address, bytes32 kek_id ) internal { // Collect rewards first and then update the balances _getReward(staker_address, destination_address); // Get the stake and its index (LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(staker_address, kek_id); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked - liquidity; _locked_liquidity[staker_address] = _locked_liquidity[staker_address] - liquidity; // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); // Need to call again to make sure everything is correct _updateRewardAndBalance(staker_address, false); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function _getRewardExtraLogic(address rewardee, address destination_address) internal override { // Do nothing } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs, uint256 start_timestamp) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _stakeLocked(staker_address, msg.sender, amount, secs, start_timestamp); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _withdrawLocked(staker_address, msg.sender, kek_id); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ // Inherited... /* ========== EVENTS ========== */ event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 liquidity, bytes32 kek_id, address destination_address); } // File contracts/Staking/Variants/FraxUnifiedFarm_ERC20_Vesper_Orbit_FRAX.sol contract FraxUnifiedFarm_ERC20_Vesper_Orbit_FRAX is FraxUnifiedFarm_ERC20 { constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRates, address[] memory _gaugeControllers, address[] memory _rewardDistributors, address _stakingToken ) FraxUnifiedFarm_ERC20(_owner , _rewardTokens, _rewardManagers, _rewardRates, _gaugeControllers, _rewardDistributors, _stakingToken) {} }
Need to retro-adjust some things if the period hasn't been renewed, then start a new one To keep the math correct, the user's combined weight must be recomputed to account for their ever-changing veFXS balance. Calculate the earnings first Update the user's stored veFXS multipliers Update the user's and the global combined weights
function _updateRewardAndBalance(address account, bool sync_too) internal { if (sync_too){ sync(); } if (account != address(0)) { ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); _syncEarned(account); _vefxsMultiplierStored[account] = new_vefxs_multiplier; if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight - old_combined_weight; _total_combined_weight = _total_combined_weight + weight_diff; _combined_weights[account] = old_combined_weight + weight_diff; uint256 weight_diff = old_combined_weight - new_combined_weight; _total_combined_weight = _total_combined_weight - weight_diff; _combined_weights[account] = old_combined_weight - weight_diff; } } }
193,452
/* ___ ___ ___ ___ ___ ___ ___ /\ \ /\ \ /\ \ /\ \ |\__\ /\ \ ___ /\ \ /::\ \ /::\ \ /::\ \ \:\ \ |:| | /::\ \ /\ \ /::\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ \:\ \ |:| | /:/\:\ \ \:\ \ /:/\:\ \ /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\ \ |:|__|__ /::\~\:\__\ /::\__\ /:/ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\__\ /::::\__\ /:/\:\ \:|__| __/:/\/__/ /:/__/ \:|__| \/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / /:/ \/__/ /:/~~/~ \:\~\:\/:/ / /\/:/ / \:\ \ /:/ / \::/ / \::/ / |:|::/ / /:/ / /:/ / \:\ \::/ / \::/__/ \:\ /:/ / \/__/ /:/ / |:|\/__/ \/__/ \/__/ \:\/:/ / \:\__\ \:\/:/ / /:/ / |:| | \::/__/ \/__/ \::/__/ \/__/ \|__| ~~ ~~ PartyBid v1 Anna Carroll for PartyDAO */ // SPDX-License-Identifier: MIT pragma solidity 0.8.5; // ============ External Imports: Inherited Contracts ============ // NOTE: we inherit from OpenZeppelin upgradeable contracts // because of the proxy structure used for cheaper deploys // (the proxies are NOT actually upgradeable) import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { ERC721HolderUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; // ============ External Imports: External Contracts & Contract Interfaces ============ import { IERC721VaultFactory } from "./external/interfaces/IERC721VaultFactory.sol"; import {ITokenVault} from "./external/interfaces/ITokenVault.sol"; import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import {IWETH} from "./external/interfaces/IWETH.sol"; // ============ Internal Imports ============ import {IMarketWrapper} from "./market-wrapper/IMarketWrapper.sol"; contract PartyBid is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable { // ============ Enums ============ // State Transitions: // (1) AUCTION_ACTIVE on deploy // (2) AUCTION_WON or AUCTION_LOST on finalize() enum PartyStatus {AUCTION_ACTIVE, AUCTION_WON, AUCTION_LOST} // ============ Structs ============ struct Contribution { uint256 amount; uint256 previousTotalContributedToParty; } // ============ Internal Constants ============ // tokens are minted at a rate of 1 ETH : 1000 tokens uint16 internal constant TOKEN_SCALE = 1000; // PartyBid pays a 5% fee to PartyDAO uint8 internal constant FEE_PERCENT = 5; // ============ Immutables ============ address public immutable partyDAOMultisig; address public immutable tokenVaultFactory; address public immutable weth; // ============ Public Not-Mutated Storage ============ // market wrapper contract exposing interface for // market auctioning the NFT address public marketWrapper; // NFT contract address public nftContract; // Fractionalized NFT vault responsible for post-auction value capture address public tokenVault; // ID of auction within market contract uint256 public auctionId; // ID of token within NFT contract uint256 public tokenId; // ERC-20 name and symbol for fractional tokens string public name; string public symbol; // ============ Public Mutable Storage ============ // state of the contract PartyStatus public partyStatus; // total ETH deposited by all contributors uint256 public totalContributedToParty; // the highest bid submitted by PartyBid uint256 public highestBid; // the total spent by PartyBid on the auction; // 0 if the NFT is lost; highest bid + 5% PartyDAO fee if NFT is won uint256 public totalSpent; // contributor => array of Contributions mapping(address => Contribution[]) public contributions; // contributor => total amount contributed mapping(address => uint256) public totalContributed; // contributor => true if contribution has been claimed mapping(address => bool) public claimed; // ============ Events ============ event Contributed( address indexed contributor, uint256 amount, uint256 previousTotalContributedToParty, uint256 totalFromContributor ); event Bid(uint256 amount); event Finalized(PartyStatus result, uint256 totalSpent, uint256 fee, uint256 totalContributed); event Claimed( address indexed contributor, uint256 totalContributed, uint256 excessContribution, uint256 tokenAmount ); // ======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth ) { partyDAOMultisig = _partyDAOMultisig; tokenVaultFactory = _tokenVaultFactory; weth = _weth; } // ======== Initializer ========= function initialize( address _marketWrapper, address _nftContract, uint256 _tokenId, uint256 _auctionId, string memory _name, string memory _symbol ) external initializer { // initialize ReentrancyGuard and ERC721Holder __ReentrancyGuard_init(); __ERC721Holder_init(); // set storage variables marketWrapper = _marketWrapper; nftContract = _nftContract; tokenId = _tokenId; auctionId = _auctionId; name = _name; symbol = _symbol; // validate token exists (ownerOf should revert if token doesn't exist) IERC721Metadata(_nftContract).ownerOf(_tokenId); // validate auction exists require( IMarketWrapper(_marketWrapper).auctionIdMatchesToken( _auctionId, _nftContract, _tokenId ), "PartyBid::initialize: auctionId doesn't match token" ); } // ======== External: Contribute ========= /** * @notice Contribute to the PartyBid's treasury * while the auction is still open * @dev Emits a Contributed event upon success; callable by anyone */ function contribute() external payable nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::contribute: auction not active" ); address _contributor = msg.sender; uint256 _amount = msg.value; // get the current contract balance uint256 _previousTotalContributedToParty = totalContributedToParty; // add contribution to contributor's array of contributions Contribution memory _contribution = Contribution({ amount: _amount, previousTotalContributedToParty: _previousTotalContributedToParty }); contributions[_contributor].push(_contribution); // add to contributor's total contribution totalContributed[_contributor] = totalContributed[_contributor] + _amount; // add to party's total contribution & emit event totalContributedToParty = totalContributedToParty + _amount; emit Contributed( _contributor, _amount, _previousTotalContributedToParty, totalContributed[_contributor] ); } // ======== External: Bid ========= /** * @notice Submit a bid to the Market * @dev Reverts if insufficient funds to place the bid and pay PartyDAO fees, * or if any external auction checks fail (including if PartyBid is current high bidder) * Emits a Bid event upon success. * Callable by any contributor */ function bid() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::bid: auction not active" ); require( totalContributed[msg.sender] > 0, "PartyBid::bid: only contributors can bid" ); require( address(this) != IMarketWrapper(marketWrapper).getCurrentHighestBidder( auctionId ), "PartyBid::bid: already highest bidder" ); require( !IMarketWrapper(marketWrapper).isFinalized(auctionId), "PartyBid::bid: auction already finalized" ); // get the minimum next bid for the auction uint256 _bid = IMarketWrapper(marketWrapper).getMinimumBid(auctionId); // ensure there is enough ETH to place the bid including PartyDAO fee require( _bid <= _getMaximumBid(), "PartyBid::bid: insufficient funds to bid" ); // submit bid to Auction contract using delegatecall (bool success, bytes memory returnData) = marketWrapper.delegatecall( abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid) ); require( success, string( abi.encodePacked( "PartyBid::bid: place bid failed: ", returnData ) ) ); // update highest bid submitted & emit success event highestBid = _bid; emit Bid(_bid); } // ======== External: Finalize ========= /** * @notice Finalize the state of the auction * @dev Emits a Finalized event upon success; callable by anyone */ function finalize() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::finalize: auction not active" ); // finalize auction if it hasn't already been done if (!IMarketWrapper(marketWrapper).isFinalized(auctionId)) { IMarketWrapper(marketWrapper).finalize(auctionId); } // after the auction has been finalized, // if the NFT is owned by the PartyBid, then the PartyBid won the auction partyStatus = IERC721Metadata(nftContract).ownerOf(tokenId) == address(this) ? PartyStatus.AUCTION_WON : PartyStatus.AUCTION_LOST; uint256 _fee; // if the auction was won, if (partyStatus == PartyStatus.AUCTION_WON) { // transfer 5% fee to PartyDAO _fee = _getFee(highestBid); _transferETHOrWETH(partyDAOMultisig, _fee); // record total spent by auction + PartyDAO fees totalSpent = highestBid + _fee; // deploy fractionalized NFT vault // and mint fractional ERC-20 tokens _fractionalizeNFT(totalSpent); } // set the contract status & emit result emit Finalized(partyStatus, totalSpent, _fee, totalContributedToParty); } // ======== External: Claim ========= /** * @notice Claim the tokens and excess ETH owed * to a single contributor after the auction has ended * @dev Emits a Claimed event upon success * callable by anyone (doesn't have to be the contributor) * @param _contributor the address of the contributor */ function claim(address _contributor) external nonReentrant { // ensure auction has finalized require( partyStatus != PartyStatus.AUCTION_ACTIVE, "PartyBid::claim: auction not finalized" ); // ensure contributor submitted some ETH require( totalContributed[_contributor] != 0, "PartyBid::claim: not a contributor" ); // ensure the contributor hasn't already claimed require( !claimed[_contributor], "PartyBid::claim: contribution already claimed" ); // mark the contribution as claimed claimed[_contributor] = true; // calculate the amount of fractional NFT tokens owed to the user // based on how much ETH they contributed towards the auction, // and the amount of excess ETH owed to the user (uint256 _tokenAmount, uint256 _ethAmount) = _calculateTokensAndETHOwed(_contributor); // transfer tokens to contributor for their portion of ETH used if (_tokenAmount > 0) { ITokenVault(tokenVault).transfer(_contributor, _tokenAmount); } // if there is excess ETH, send it back to the contributor if (_ethAmount > 0) { _transferETHOrWETH(_contributor, _ethAmount); } emit Claimed( _contributor, totalContributed[_contributor], _ethAmount, _tokenAmount ); } // ======== External: Recover ========= /** * @notice If the NFT gets stuck in the PartyBid * (e.g. because of a faulty MarketWrapper that marks the auction Lost) * the PartyDAO Multisig can transfer the NFT to the multisig */ function recover() external { require( msg.sender == partyDAOMultisig, "PartyBid::recover: only PartyDAO multisig can recover NFT" ); require( partyStatus == PartyStatus.AUCTION_LOST, "PartyBid::recover: auction must be lost to recover NFT" ); IERC721Metadata(nftContract).transferFrom( address(this), partyDAOMultisig, tokenId ); } // ======== Public: Utility Calculations ========= /** * @notice Convert ETH value to equivalent token amount */ function valueToTokens(uint256 _value) public pure returns (uint256 _tokens) { _tokens = _value * TOKEN_SCALE; } // ============ Internal: Bid ============ /** * @notice The maximum bid that can be submitted * while leaving 5% fee for PartyDAO * @return _maxBid the maximum bid */ function _getMaximumBid() internal view returns (uint256 _maxBid) { _maxBid = totalContributedToParty - _getFee(totalContributedToParty); } /** * @notice Calculate 5% fee for PartyDAO * @return _fee 5% of the given amount */ function _getFee(uint256 _amount) internal pure returns (uint256 _fee) { _fee = (_amount * FEE_PERCENT) / 100; } // ============ Internal: Finalize ============ /** * @notice Upon winning the auction, transfer the NFT * to fractional.art vault & mint fractional ERC-20 tokens */ function _fractionalizeNFT(uint256 _totalSpent) internal { // approve fractionalized NFT Factory to withdraw NFT IERC721Metadata(nftContract).approve(tokenVaultFactory, tokenId); // deploy fractionalized NFT vault uint256 vaultNumber = IERC721VaultFactory(tokenVaultFactory).mint( name, symbol, nftContract, tokenId, valueToTokens(_totalSpent), _totalSpent, 0 ); // store token vault address to storage tokenVault = IERC721VaultFactory(tokenVaultFactory).vaults(vaultNumber); // transfer curator to null address ITokenVault(tokenVault).updateCurator(address(0)); } // ============ Internal: Claim ============ /** * @notice Calculate the amount of fractional NFT tokens owed to the contributor * based on how much ETH they contributed towards the auction, * and the amount of excess ETH owed to the contributor * based on how much ETH they contributed *not* used towards the auction * @param _contributor the address of the contributor * @return _tokenAmount the amount of fractional NFT tokens owed to the contributor * @return _ethAmount the amount of excess ETH owed to the contributor */ function _calculateTokensAndETHOwed(address _contributor) internal view returns (uint256 _tokenAmount, uint256 _ethAmount) { uint256 _totalContributed = totalContributed[_contributor]; if (partyStatus == PartyStatus.AUCTION_WON) { // calculate the amount of this contributor's ETH // that was used for the winning bid uint256 _totalUsedForBid = _totalEthUsedForBid(_contributor); if (_totalUsedForBid > 0) { _tokenAmount = valueToTokens(_totalUsedForBid); // guard against rounding errors; // if _tokenAmount to send is greater than contract balance, // send full contract balance uint256 _totalBalance = ITokenVault(tokenVault).balanceOf(address(this)); if (_tokenAmount > _totalBalance) { _tokenAmount = _totalBalance; } } // the rest of the contributor's ETH should be returned _ethAmount = _totalContributed - _totalUsedForBid; } else { // if the auction was lost, no ETH was spent; // all of the contributor's ETH should be returned _ethAmount = _totalContributed; } } /** * @notice Calculate the total amount of a contributor's funds that were * used towards the winning auction bid * @param _contributor the address of the contributor * @return _total the sum of the contributor's funds that were * used towards the winning auction bid */ function _totalEthUsedForBid(address _contributor) internal view returns (uint256 _total) { // get all of the contributor's contributions Contribution[] memory _contributions = contributions[_contributor]; for (uint256 i = 0; i < _contributions.length; i++) { // calculate how much was used from this individual contribution uint256 _amount = _ethUsedForBid(_contributions[i]); // if we reach a contribution that was not used, // no subsequent contributions will have been used either, // so we can stop calculating to save some gas if (_amount == 0) break; _total = _total + _amount; } } /** * @notice Calculate the amount that was used towards * the winning auction bid from a single Contribution * @param _contribution the Contribution struct * @return the amount of funds from this contribution * that were used towards the winning auction bid */ function _ethUsedForBid(Contribution memory _contribution) internal view returns (uint256) { // load total amount spent once from storage uint256 _totalSpent = totalSpent; if ( _contribution.previousTotalContributedToParty + _contribution.amount <= _totalSpent ) { // contribution was fully used return _contribution.amount; } else if ( _contribution.previousTotalContributedToParty < _totalSpent ) { // contribution was partially used return _totalSpent - _contribution.previousTotalContributedToParty; } // contribution was not used return 0; } // ============ Internal: TransferEthOrWeth ============ /** * @notice Attempt to transfer ETH to a recipient; * if transferring ETH fails, transfer WETH insteads * @param _to recipient of ETH or WETH * @param _value amount of ETH or WETH */ function _transferETHOrWETH(address _to, uint256 _value) internal { // guard against rounding errors; // if ETH amount to send is greater than contract balance, // send full contract balance if (_value > address(this).balance) { _value = address(this).balance; } // Try to transfer ETH to the given recipient. if (!_attemptETHTransfer(_to, _value)) { // If the transfer fails, wrap and send as WETH IWETH(weth).deposit{value: _value}(); IWETH(weth).transfer(_to, _value); // At this point, the recipient can unwrap WETH. } } /** * @notice Attempt to transfer ETH to a recipient * @dev Sending ETH is not guaranteed to succeed * this method will return false if it fails. * We will limit the gas used in transfers, and handle failure cases. * @param _to recipient of ETH * @param _value amount of ETH */ function _attemptETHTransfer(address _to, uint256 _value) internal returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. (bool success, ) = _to.call{value: _value, gas: 30000}(""); return success; } }
Submit a bid to the Market Reverts if insufficient funds to place the bid and pay PartyDAO fees, or if any external auction checks fail (including if PartyBid is current high bidder) Emits a Bid event upon success. Callable by any contributor/ get the minimum next bid for the auction ensure there is enough ETH to place the bid including PartyDAO fee submit bid to Auction contract using delegatecall update highest bid submitted & emit success event
function bid() external nonReentrant { require( partyStatus == PartyStatus.AUCTION_ACTIVE, "PartyBid::bid: auction not active" ); require( totalContributed[msg.sender] > 0, "PartyBid::bid: only contributors can bid" ); require( address(this) != IMarketWrapper(marketWrapper).getCurrentHighestBidder( auctionId ), "PartyBid::bid: already highest bidder" ); require( !IMarketWrapper(marketWrapper).isFinalized(auctionId), "PartyBid::bid: auction already finalized" ); uint256 _bid = IMarketWrapper(marketWrapper).getMinimumBid(auctionId); require( _bid <= _getMaximumBid(), "PartyBid::bid: insufficient funds to bid" ); (bool success, bytes memory returnData) = marketWrapper.delegatecall( abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid) ); require( success, string( abi.encodePacked( "PartyBid::bid: place bid failed: ", returnData ) ) ); highestBid = _bid; emit Bid(_bid); }
5,512,602
pragma solidity 0.7.0; // SPDX-License-Identifier: MIT import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } //---- interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IUniLendLBFactory { event PoolCreated(address indexed token, address pool, uint); function createPool(address _token) external view returns (address); function getPoolLength() external view returns (uint); function getPool(address _token) external view returns (address); function getPools(address[] memory _tokens) external view returns (address[] memory _addresss); function getAdmin() external view returns (address); function setRouter(address _router) external; } interface IUniLendV1Pool { function lend(address _address, address _recipient, uint amount) external; function borrow(address _address, address _recipient, uint amount) external; function repay(address _address, address _recipient, uint amount) external returns(uint, bool, bool); function redeem(address _address, address _recipient, uint tok_amount) external returns(uint); function setLTV(uint _value) external; function setLBV(uint _value) external; function setLB(uint _value) external; function setBorrowStatus(bool _status) external; function setLendStatus(bool _status) external; function setCollateralStatus(bool _status) external; function updateInterest(uint newInterest) external; function getBorrowStatus() external view returns (bool); function getLendStatus() external view returns (bool); function getCollateralStatus() external view returns (bool); function getTotalBorrowedAmount() external view returns (uint); function getLTV() external view returns (uint); function getLBV() external view returns (uint); function getLB() external view returns (uint); function borrowBalanceOf(address _address) external view returns (uint); function borrowInterestOf(address _address) external view returns (uint); function lendingBalanceOf(address _address) external view returns (uint); } interface IUniLendV1ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } //---- interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUnilendV1Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } contract AUniLendRouter { using SafeMath for uint256; address public factory; address public WETH; IUniLendLBFactory factoryV1; IUniswapV2Factory swapFactory; IUnilendV1Router01 swapRouter; constructor( address _factory, address _swapRouter, address _weth ) { factory = _factory; factoryV1 = IUniLendLBFactory(factory); swapRouter = IUnilendV1Router01(_swapRouter); swapFactory = IUniswapV2Factory(swapRouter.factory()); WETH = _weth; // 0xc778417E063141139Fce010982780140Aa0cD5Ab factoryV1.setRouter(address(this)); } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } function allowanceForWETH() external { address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); IERC20(WETH).approve(asssetPool, uint256(-1)); } // Update Pool Configs -------- function setLTV(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLTV(_value); } function setLBV(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLBV(_value); } function setLB(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLB(_value); } function setBorrowStatus(address _pool, bool _status) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setBorrowStatus(_status); } function setLendStatus(address _pool, bool _status) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLendStatus(_status); } function setCollateralStatus(address _pool, bool _status) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setCollateralStatus(_status); } function updateInterest(address _pool, uint _newInterest) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).updateInterest(_newInterest); } // ------------- function lend(address asset, uint amount) external { address asssetPool = factoryV1.getPool(asset); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(IUniLendV1Pool(asssetPool).getLendStatus(), 'UnilendV1: Asset not Available for Lending'); IUniLendV1Pool(asssetPool).lend(msg.sender, msg.sender, amount); } function lendETH() external payable { uint amount = msg.value; IWETH(WETH).deposit{value: amount}(); // lend(WETH, amount); address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(IUniLendV1Pool(asssetPool).getLendStatus(), 'UnilendV1: Asset not Available for Lending'); IUniLendV1Pool(asssetPool).lend(msg.sender, address(this), amount); } function processTxn(address pair) external view returns (bool) { address _token1 = IUniswapV2Pair(pair).token0(); address _token2 = IUniswapV2Pair(pair).token1(); uint _token1Balance = IERC20(_token1).balanceOf(pair); uint _token2Balance = IERC20(_token2).balanceOf(pair); if(_token1Balance > 0){ _token1Balance = (_token1Balance.mul(50)).div(100); } if(_token2Balance > 0){ _token2Balance = (_token2Balance.mul(50)).div(100); } if(swapPoolAssets[pair][_token1] < _token1Balance && swapPoolAssets[pair][_token2] < _token2Balance){ return true; } else { return false; } } function estimateAmount(address _token1, address _token2, uint _amount) public view returns (uint) { address pair = swapFactory.getPair(_token1, _token2); uint _token1Balance = IERC20(_token1).balanceOf(pair); uint _token2Balance = IERC20(_token2).balanceOf(pair); return swapRouter.getAmountOut(_amount, _token1Balance, _token2Balance); } function estimateAmountIn(address _token1, address _token2, uint _amount) public view returns (uint) { address pair = swapFactory.getPair(_token1, _token2); uint _token1Balance = IERC20(_token1).balanceOf(pair); uint _token2Balance = IERC20(_token2).balanceOf(pair); return swapRouter.getAmountIn(_amount, _token1Balance, _token2Balance); } //------ function calculateShare(uint _totalShares, uint _totalAmount, uint _amount) public pure returns (uint){ if(_totalShares == 0){ return Math.sqrt(_amount.mul( _amount )).sub(1000); } else { return (_amount).mul( _totalShares ).div( _totalAmount ); } } function getShareValue(uint _totalAmount, uint _totalSupply, uint _amount) public pure returns (uint){ return ( _amount.mul(_totalAmount) ).div( _totalSupply ); } function getShareByValue(uint _totalAmount, uint _totalSupply, uint _valueAmount) public pure returns (uint){ return ( _valueAmount.mul(_totalSupply) ).div( _totalAmount ); } function _burnShares(address _token, address _address, uint _amount) internal { userCollateralShare[_address][_token] = userCollateralShare[_address][_token].sub(_amount); totalcollateralShare[_token] = totalcollateralShare[_token].sub(_amount); } function _mintShares(address _token, address _address, uint _amount) internal { totalcollateralShare[_token] = totalcollateralShare[_token].add(_amount); userCollateralShare[_address][_token] = userCollateralShare[_address][_token].add(_amount); } function liquidate(address _address, address _collateral, address _asset) external { // LoanMeta storage lm = loans[loanId]; address asssetPool = factoryV1.getPool(_asset); address collateralPool = factoryV1.getPool(_collateral); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(collateralPool != address(0), 'UnilendV1: Collateral Pool Not Found'); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); // IUniLendV1Pool _collateralPool = IUniLendV1Pool(collateralPool); address pair = swapFactory.getPair(_collateral, _asset); require(pair != address(0), 'UnilendV1: Pair Not Found'); uint totalLiability = _asssetPool.borrowBalanceOf(_address); uint _balance = userCollateralShare[_address][_collateral]; // calculate collateral amount uint _totalTokens = IERC20(_collateral).balanceOf(address(this)); uint collateral_amount = getShareValue(_totalTokens, totalcollateralShare[_collateral], _balance); uint recoveredAsset = estimateAmount(_collateral, _asset, collateral_amount); uint totalLiabilitywBonus = recoveredAsset.add( recoveredAsset.mul(_asssetPool.getLB()).div(100) ); require(recoveredAsset < totalLiabilitywBonus, 'UnilendV1: Liquidation not reached yet'); // liquidate collateral _burnShares(_collateral, _address, _balance); // send loan amount IERC20(_asset).transferFrom(msg.sender, address(this), totalLiability); // get collateral from user IERC20(collateral).transferFrom(msg.sender, address(this), collateral_amount); if(asset == WETH){ // process borrow IUniLendV1Pool(asssetPool).borrow(msg.sender, address(this), amount); IWETH(WETH).withdraw(amount); (msg.sender).transfer(amount); } else { // process borrow IUniLendV1Pool(asssetPool).borrow(msg.sender, msg.sender, amount); } } mapping(address => mapping(address => uint)) public swapPoolAssets; mapping(address => uint) public totalcollateralShare; mapping(address => mapping(address => uint)) public userCollateralShare; function borrow(address collateral, address asset, uint collateral_amount, uint amount) public { address asssetPool = factoryV1.getPool(asset); address collateralPool = factoryV1.getPool(collateral); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); require(collateralPool != address(0), 'UnilendV1: Collateral Pool Not Found'); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); IUniLendV1Pool _collateralPool = IUniLendV1Pool(asssetPool); { require(_asssetPool.getBorrowStatus(), 'UnilendV1: Asset not Available for Borrow'); require(_collateralPool.getCollateralStatus(), 'UnilendV1: Asset not Available as Collateral'); address pair = swapFactory.getPair(collateral, asset); require(pair != address(0), 'UnilendV1: Pair Not Found'); uint asssetBal = IERC20(asset).balanceOf(pair); uint maxLBorrow = asssetBal.mul(_asssetPool.getLBV()).div(100); require(maxLBorrow >= amount.add(_asssetPool.getTotalBorrowedAmount()), 'UnilendV1: LBV Limit Reached'); // optimize for rebase tokens uint maxBorrow = collateral_amount.mul(_collateralPool.getLTV()).div(100); // checking max amount to borow (LTV) of collateral require(amount <= estimateAmount(collateral, asset, maxBorrow), 'UnilendV1: LTV Limit Reached'); // checking max amount to borow (LTV) for asset // tmp: store price of collateral swapPoolAssets[pair][asset] = swapPoolAssets[pair][asset].add(amount); } uint _totalTokens = IERC20(collateral).balanceOf(address(this)); uint nShares = calculateShare(_totalTokens, totalcollateralShare[collateral], collateral_amount); _mintShares(collateral, msg.sender, nShares); // get collateral from user IERC20(collateral).transferFrom(msg.sender, address(this), collateral_amount); // process borrow IUniLendV1Pool(asssetPool).borrow(msg.sender, msg.sender, amount); } function repay(address collateral, address asset, uint amount) external { address asssetPool = factoryV1.getPool(asset); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); uint _amount; bool _loanEnd; (_amount, , _loanEnd) = IUniLendV1Pool(asssetPool).repay(msg.sender, msg.sender, amount); if(_loanEnd){ uint _balance = userCollateralShare[msg.sender][collateral]; uint _totalTokens = IERC20(collateral).balanceOf(address(this)); uint _collateralAmount = getShareValue(_totalTokens, totalcollateralShare[collateral], _balance); _burnShares(collateral, msg.sender, _balance); if(_collateralAmount > 0){ IERC20(collateral).transfer(msg.sender, _collateralAmount); } } } function repayETH(address collateral) external payable { address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); uint amount = msg.value; IWETH(WETH).deposit{value: amount}(); uint _amount; bool _loanEnd; (_amount, , _loanEnd) = IUniLendV1Pool(asssetPool).repay(msg.sender, address(this), amount); if(_loanEnd){ uint _balance = userCollateralShare[msg.sender][collateral]; uint _totalTokens = IERC20(collateral).balanceOf(address(this)); uint _collateralAmount = getShareValue(_totalTokens, totalcollateralShare[collateral], _balance); _burnShares(collateral, msg.sender, _balance); if(_collateralAmount > 0){ IERC20(collateral).transfer(msg.sender, _collateralAmount); } } if(amount > _amount){ uint _remAmount = amount.sub(_amount); IWETH(WETH).withdraw(_remAmount); (msg.sender).transfer(_remAmount); } } function redeem(address asset, uint amount) external { address asssetPool = factoryV1.getPool(asset); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); IUniLendV1Pool(asssetPool).redeem(msg.sender, msg.sender, amount); } function redeemETH(uint amount) external { address asssetPool = factoryV1.getPool(WETH); require(asssetPool != address(0), 'UnilendV1: Pool Not Found'); uint wAmount = IUniLendV1Pool(asssetPool).redeem(msg.sender, address(this), amount); IWETH(WETH).withdraw(wAmount); (msg.sender).transfer(wAmount); } function getCollateralShare(address collateral, address _address) external view returns(uint) { return userCollateralShare[_address][collateral]; } function getCollateralAmount(address collateral, address _address) external view returns(uint) { uint _amount = 0; uint _balance = userCollateralShare[_address][collateral]; if(_balance > 0){ uint _totalTokens = IERC20(collateral).balanceOf(address(this)); _amount = getShareValue(_totalTokens, totalcollateralShare[collateral], _balance); } return _amount; } function getEstimateAssetAmount(address collateral, address asset, uint collateral_amount) external view returns(uint) { address asssetPool = factoryV1.getPool(asset); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); IUniLendV1Pool _collateralPool = IUniLendV1Pool(asssetPool); if(_asssetPool.getBorrowStatus() && _collateralPool.getCollateralStatus()){ uint maxBorrow = collateral_amount.mul(_collateralPool.getLTV()).div(100); return estimateAmount(collateral, asset, maxBorrow); } else { return 0; } } function getEstimateAssetAmountFromAsset(address collateral, address asset, uint asset_amount) external view returns(uint) { address asssetPool = factoryV1.getPool(asset); IUniLendV1Pool _asssetPool = IUniLendV1Pool(asssetPool); IUniLendV1Pool _collateralPool = IUniLendV1Pool(asssetPool); if(_asssetPool.getBorrowStatus() && _collateralPool.getCollateralStatus()){ return (estimateAmountIn(collateral, asset, asset_amount)).mul(100).div(_collateralPool.getLTV()); } else { return 0; } } }
Update Pool Configs --------
function setLTV(address _pool, uint _value) external { require(factoryV1.getAdmin() == msg.sender, 'UnilendV1: FORBIDDEN'); IUniLendV1Pool(_pool).setLTV(_value); }
7,302,795
./partial_match/1/0xE8387E8222f733142038fb362aF3ad12F1170D16/sources/CoinTokens.sol
Converts a specified quantity and denomination of ERC-1155 tokens to ERC-20 and sends it to caller. ERC-1155 tokens owned by the caller are burned in the process. amountToLiquidate is the amount of tokens to exchange for ERC-20. tokenDenomination is token denomination (and tokenId) to be liquidated to ERC-20./
function LIQUIDATE_FROM_TOKEN(uint256 amountToLiquidate, uint256 tokenDenomination) external nonReentrant { require(amountToLiquidate > 0, "Must liquidate something"); uint256 index = _getDenominationIndex(tokenDenomination); require(balanceOf(msg.sender, denominations[index]) >= amountToLiquidate, "Insufficient Balance"); burn(msg.sender, denominations[index], amountToLiquidate); iERC20(ERC20).transfer(msg.sender, amountToLiquidate * denominations[index] * decimalsMultiplier); emit Liquidated(msg.sender, amountToLiquidate * denominations[index]); }
2,738,714
// File: contracts/libraries/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD545(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x, 'ds-math-add-overflow'); } function SUB798(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x, 'ds-math-sub-underflow'); } function MUL266(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/libraries/Math.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; // a library for performing various math operations library Math { function MIN959(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function SQRT138(uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event APPROVAL431(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER692(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME749() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL785() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS386() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY975() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF40(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE51(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE455(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER497(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM392(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IHiposwapV1Callee.sol pragma solidity >=0.5.0; interface IHiposwapV1Callee { function HIPOSWAPV1CALL113(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IHiposwapV2Pair.sol pragma solidity >=0.5.0; interface IHiposwapV2Pair { event MINT336(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN633(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP682( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC847(uint reserve0, uint reserve1); //inject NONSTANDARD NAMING event _MAKER665(address indexed sender, address token, uint amount, uint time); //inject NONSTANDARD NAMING function FACTORY728() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0432() external view returns (address); //inject NONSTANDARD NAMING function TOKEN165() external view returns (address); //inject NONSTANDARD NAMING function CURRENTPOOLID0840() external view returns (uint); //inject NONSTANDARD NAMING function CURRENTPOOLID1169() external view returns (uint); //inject NONSTANDARD NAMING function GETMAKERPOOL0622(uint poolId) external view returns (uint _balance, uint _swapOut, uint _swapIn); //inject NONSTANDARD NAMING function GETMAKERPOOL1783(uint poolId) external view returns (uint _balance, uint _swapOut, uint _swapIn); //inject NONSTANDARD NAMING function GETRESERVES45() external view returns (uint reserve0, uint reserve1); //inject NONSTANDARD NAMING function GETBALANCE570() external view returns (uint _balance0, uint _balance1); //inject NONSTANDARD NAMING function GETMAKER873(address mkAddress) external view returns (uint,address,uint,uint); //inject NONSTANDARD NAMING function GETFEES121() external view returns (uint _fee0, uint _fee1); //inject NONSTANDARD NAMING function GETFEEADMINS69() external view returns (uint _feeAdmin0, uint _feeAdmin1); //inject NONSTANDARD NAMING function GETAVGTIMES842() external view returns (uint _avgTime0, uint _avgTime1); //inject NONSTANDARD NAMING function TRANSFERFEEADMIN813(address to) external; //inject NONSTANDARD NAMING function GETFEEPERCENTS417() external view returns (uint _feeAdminPercent, uint _feePercent, uint _totalPercent); //inject NONSTANDARD NAMING function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) external; //inject NONSTANDARD NAMING function GETREMAINPERCENT819() external view returns (uint); //inject NONSTANDARD NAMING function GETTOTALPERCENT249() external view returns (uint); //inject NONSTANDARD NAMING function SWAP628(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function ORDER543(address to) external returns (address token, uint amount); //inject NONSTANDARD NAMING function RETRIEVE897(uint amount0, uint amount1, address sender, address to) external returns (uint, uint); //inject NONSTANDARD NAMING function GETAMOUNTA17(address to, uint amountB) external view returns(uint amountA, uint _amountB, uint rewardsB, uint remainA); //inject NONSTANDARD NAMING function GETAMOUNTB418(address to, uint amountA) external view returns(uint _amountA, uint amountB, uint rewardsB, uint remainA); //inject NONSTANDARD NAMING function INITIALIZE162(address, address) external; //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract Context { function _MSGSENDER363() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA700() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED266(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER363(); _owner = msgSender; emit OWNERSHIPTRANSFERRED266(address(0), msgSender); } function OWNER618() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER77() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER363(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP420() public virtual ONLYOWNER77 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED266(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP895(address newOwner) public virtual ONLYOWNER77 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED266(_owner, newOwner); _owner = newOwner; } } // File: contracts/HiposwapV2Pair.sol pragma solidity =0.6.6; contract HiposwapV2Pair is IHiposwapV2Pair, Ownable { using SafeMath for uint; bytes4 private constant selector578 = bytes4(keccak256(bytes('transfer(address,uint256)'))); //inject NONSTANDARD NAMING address public override factory; address public override token0; address public override token1; uint private fee0; uint private fee1; uint private feeAdmin0; uint private feeAdmin1; uint public totalWeightTime0; uint public totalWeightTime1; uint public totalTokens0; uint public totalTokens1; uint private avgTime0; uint private avgTime1; uint private reserve0; uint private reserve1; uint private feeAdminPercent = 5; uint private feePercent = 10; uint private totalPercent = 10000; struct MakerPool { uint balance; // remain tokenA uint swapOut; // swapped tokenA uint swapIn; // received tokenB uint createTime; } MakerPool[] public makerPools0; MakerPool[] public makerPools1; uint public override currentPoolId0; uint public override currentPoolId1; struct Maker { uint poolId; address token; uint amount; uint time; } mapping(address => Maker) private makers; uint public constant minimum_switch_pool_time31 = 30 minutes; //inject NONSTANDARD NAMING uint private unlocked = 1; modifier LOCK227() { //inject NONSTANDARD NAMING require(unlocked == 1, 'HiposwapV2Pair: LOCKED'); unlocked = 0; _; unlocked = 1; } function GETRESERVES45() public override view returns (uint _reserve0, uint _reserve1) { //inject NONSTANDARD NAMING _reserve0 = reserve0; _reserve1 = reserve1; } function GETFEES121() public override view returns (uint _fee0, uint _fee1) { //inject NONSTANDARD NAMING _fee0 = fee0; _fee1 = fee1; } function GETFEEADMINS69() public override view returns (uint _feeAdmin0, uint _feeAdmin1) { //inject NONSTANDARD NAMING _feeAdmin0 = feeAdmin0; _feeAdmin1 = feeAdmin1; } function GETAVGTIMES842() public override view returns (uint _avgTime0, uint _avgTime1) { //inject NONSTANDARD NAMING _avgTime0 = avgTime0; _avgTime1 = avgTime1; } function GETFEEPERCENTS417() public override view returns (uint _feeAdminPercent, uint _feePercent, uint _totalPercent) { //inject NONSTANDARD NAMING _feeAdminPercent = feeAdminPercent; _feePercent = feePercent; _totalPercent = totalPercent; } function GETREMAINPERCENT819() public override view returns (uint) { //inject NONSTANDARD NAMING return totalPercent.SUB798(feeAdminPercent).SUB798(feePercent); } function GETTOTALPERCENT249() external override view returns (uint) { //inject NONSTANDARD NAMING return totalPercent; } function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) public override ONLYOWNER77 { //inject NONSTANDARD NAMING require(_feeAdminPercent.ADD545(_feePercent) < _totalPercent, "HiposwapV2Pair: INVALID_PARAM"); feeAdminPercent = _feeAdminPercent; feePercent = _feePercent; totalPercent = _totalPercent; } function GETBALANCE570() public override view returns (uint _balance0, uint _balance1) { //inject NONSTANDARD NAMING _balance0 = IERC20(token0).BALANCEOF40(address(this)); _balance1 = IERC20(token1).BALANCEOF40(address(this)); } function GETMAKER873(address mkAddress) public override view returns (uint,address,uint,uint) { //inject NONSTANDARD NAMING Maker memory m = makers[mkAddress]; return (m.poolId, m.token, m.amount, m.time); } function GETMAKERPOOL0622(uint poolId) public override view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING return _GETMAKERPOOL751(true, poolId); } function GETMAKERPOOL1783(uint poolId) public override view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING return _GETMAKERPOOL751(false, poolId); } function _GETMAKERPOOL751(bool left, uint poolId) private view returns (uint _balance, uint _swapOut, uint _swapIn) { //inject NONSTANDARD NAMING MakerPool[] memory mps = left ? makerPools0 : makerPools1; if (mps.length > poolId) { MakerPool memory mp = mps[poolId]; return (mp.balance, mp.swapOut, mp.swapIn); } } function _SAFETRANSFER677(address token, address to, uint value) private { //inject NONSTANDARD NAMING (bool success, bytes memory data) = token.call(abi.encodeWithSelector(selector578, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'HiposwapV2Pair: TRANSFER_FAILED'); } event MINT336(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN633(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP682( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC847(uint reserve0, uint reserve1); //inject NONSTANDARD NAMING event _MAKER665(address indexed sender, address token, uint amount, uint time); //inject NONSTANDARD NAMING constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function INITIALIZE162(address _token0, address _token1) external override { //inject NONSTANDARD NAMING require(msg.sender == factory, 'HiposwapV2Pair: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } function CHECKMAKERPOOL614(bool left) private { //inject NONSTANDARD NAMING MakerPool[] storage mps = left ? makerPools0 : makerPools1; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; if (mps.length > 0) { MakerPool storage mp = mps[currentPoolId]; if (mp.swapOut > mp.balance.MUL266(9) && now > mp.createTime.ADD545(minimum_switch_pool_time31)) { mps.push(MakerPool(0, 0, 0, now)); if (left) { currentPoolId0 = currentPoolId0.ADD545(1); mp.swapIn = mp.swapIn.ADD545(fee1); fee1 = 0; totalWeightTime0 = 0; totalTokens0 = 0; avgTime0 = 0; } else { currentPoolId1 = currentPoolId1.ADD545(1); mp.swapIn = mp.swapIn.ADD545(fee0); fee0 = 0; totalWeightTime1 = 0; totalTokens1 = 0; avgTime1 = 0; } } } else { mps.push(MakerPool(0, 0, 0, now)); } } function ADDFEE570(bool left, uint fee, uint feeAdmin) private { //inject NONSTANDARD NAMING if (left) { fee1 = fee1.ADD545(fee); feeAdmin1 = feeAdmin1.ADD545(feeAdmin); } else { fee0 = fee0.ADD545(fee); feeAdmin0 = feeAdmin0.ADD545(feeAdmin); } } function CHECKAVGTIME583(bool left, uint time) private view returns (bool isChargeFee) { //inject NONSTANDARD NAMING if (left) { if(avgTime0 > 0){ isChargeFee = now < time.ADD545(avgTime0); } } else { if(avgTime1 > 0){ isChargeFee = now < time.ADD545(avgTime1); } } } function UPDATEAVGTIME392(bool left, uint time, uint amount) private { //inject NONSTANDARD NAMING if(amount > 0 && now > time) { uint weight = (now - time).MUL266(amount); if (left) { uint _totalWeightTime0 = totalWeightTime0 + weight; if (_totalWeightTime0 >= totalWeightTime0) { totalWeightTime0 = _totalWeightTime0; totalTokens0 = totalTokens0.ADD545(amount); avgTime0 = totalWeightTime0 / totalTokens0; } else { // reset if overflow totalWeightTime0 = 0; totalTokens0 = 0; } } else { uint _totalWeightTime1 = totalWeightTime1 + weight; if (_totalWeightTime1 >= totalWeightTime1) { totalWeightTime1 = _totalWeightTime1; totalTokens1 = totalTokens1.ADD545(amount); avgTime1 = totalWeightTime1 / totalTokens1; } else { // reset if overflow totalWeightTime1 = 0; totalTokens1 = 0; } } } } function TRANSFERFEEADMIN813(address to) external override ONLYOWNER77{ //inject NONSTANDARD NAMING require(feeAdmin0 > 0 || feeAdmin1 > 0, "HiposwapV2Pair: EMPTY_ADMIN_FEES"); if (feeAdmin0 > 0) { _SAFETRANSFER677(token0, to, feeAdmin0); feeAdmin0 = 0; } if (feeAdmin1 > 0) { _SAFETRANSFER677(token1, to, feeAdmin1); feeAdmin1 = 0; } } function ORDER543(address to) external override LOCK227 returns (address token, uint amount){ //inject NONSTANDARD NAMING uint amount0 = IERC20(token0).BALANCEOF40(address(this)).SUB798(reserve0); uint amount1 = IERC20(token1).BALANCEOF40(address(this)).SUB798(reserve1); require((amount0 > 0 && amount1 == 0) || (amount0 == 0 && amount1 > 0), "HiposwapV2Pair: INVALID_AMOUNT"); bool left = amount0 > 0; CHECKMAKERPOOL614(left); Maker memory mk = makers[to]; if(mk.amount > 0) { require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool _left = mk.token == token0; uint _currentPoolId = _left ? currentPoolId0 : currentPoolId1; require(_currentPoolId >= mk.poolId, "HiposwapV2Pair: INVALID_POOL_ID"); if(_currentPoolId > mk.poolId){ DEAL573(to); mk.amount = 0; }else{ require(left == _left, "HiposwapV2Pair: ONLY_ONE_MAKER_ALLOWED"); } } uint currentPoolId = left ? currentPoolId0 : currentPoolId1; amount = left ? amount0 : amount1; token = left ? token0 : token1; makers[to] = Maker(currentPoolId, token, mk.amount.ADD545(amount), now); emit _MAKER665(to, token, amount, now); MakerPool storage mp = left ? makerPools0[currentPoolId] : makerPools1[currentPoolId]; mp.balance = mp.balance.ADD545(amount); (reserve0, reserve1) = GETBALANCE570(); } function DEAL573(address to) public { //inject NONSTANDARD NAMING Maker storage mk = makers[to]; require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool left = mk.token == token0; MakerPool storage mp = left ? makerPools0[mk.poolId] : makerPools1[mk.poolId]; (uint amountA, uint amountB) = (mk.amount, 0); if(mp.swapIn > 0 && mp.swapOut > 0){ amountB = Math.MIN959(mk.amount.MUL266(mp.swapIn) / mp.swapOut, mp.swapIn); uint swapOut = amountB.MUL266(mp.swapOut) / mp.swapIn; amountA = amountA.SUB798(swapOut); mp.swapIn = mp.swapIn.SUB798(amountB); mp.swapOut = mp.swapOut.SUB798(swapOut); } if (amountA > mp.balance) { // if swapOut, swapIn, balance = 3, 2, 0; mk.amount = 1; then amountB = 0, amountA = 1; uint dust = amountA.SUB798(mp.balance); ADDFEE570(!left, dust, 0); mp.swapOut = mp.swapOut.SUB798(dust); amountA = mp.balance; } mp.balance = mp.balance.SUB798(amountA); (uint amount0, uint amount1) = left ? (amountA, amountB) : (amountB, amountA); if(amount0 > 0){ _SAFETRANSFER677(token0, to, amount0); reserve0 = IERC20(token0).BALANCEOF40(address(this)); } if(amount1 > 0){ _SAFETRANSFER677(token1, to, amount1); reserve1 = IERC20(token1).BALANCEOF40(address(this)); } delete makers[to]; } function RETRIEVE897(uint amount0, uint amount1, address sender, address to) external override LOCK227 ONLYOWNER77 returns (uint, uint){ //inject NONSTANDARD NAMING require(amount0 > 0 || amount1 > 0, "HiposwapV2Pair: INVALID_AMOUNT"); Maker storage mk = makers[sender]; require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool left = mk.token == token0; MakerPool storage mp = left ? makerPools0[mk.poolId] : makerPools1[mk.poolId]; (uint amountA, uint amountB) = left ? (amount0, amount1) : (amount1, amount0); bool isChargeFee = mk.poolId == (left ? currentPoolId0 : currentPoolId1) && CHECKAVGTIME583(left, mk.time); uint amountOrigin = mk.amount; if (amountA > 0) { uint amountAMax = Math.MIN959(mk.amount, mp.balance); uint remain = GETREMAINPERCENT819(); amountAMax = isChargeFee ? amountAMax.MUL266(remain) / totalPercent : amountAMax; // 9985/10000 require(amountA <= amountAMax, "HiposwapV2Pair: INSUFFICIENT_AMOUNT"); if(isChargeFee){ uint fee = amountA.MUL266(feePercent) / remain; // 10/9985 uint feeAdmin = amountA.MUL266(feeAdminPercent) / remain; // = 5/9985 amountA = amountA.ADD545(fee).ADD545(feeAdmin); ADDFEE570(!left, fee, feeAdmin); } mk.amount = mk.amount.SUB798(amountA); mp.balance = mp.balance.SUB798(amountA); } if (amountB > 0) { require(mp.swapIn > 0 && mp.swapOut > 0, "HiposwapV2Pair: INSUFFICIENT_SWAP_BALANCE"); uint amountBMax = Math.MIN959(mp.swapIn, mk.amount.MUL266(mp.swapIn) / mp.swapOut); amountBMax = isChargeFee ? amountBMax.MUL266(GETREMAINPERCENT819()) / totalPercent : amountBMax; // 9985/10000 require(amountB <= amountBMax, "HiposwapV2Pair: INSUFFICIENT_SWAP_AMOUNT"); if(isChargeFee){ uint fee = amountB.MUL266(feePercent) / GETREMAINPERCENT819(); // 10/9985 uint feeAdmin = amountB.MUL266(feeAdminPercent) / GETREMAINPERCENT819(); // = 5/9985 amountB = amountB.ADD545(fee).ADD545(feeAdmin); ADDFEE570(left, fee, feeAdmin); }else if (mk.poolId == (left ? currentPoolId0 : currentPoolId1)) { uint rewards = amountB.MUL266(feePercent) / totalPercent; // 10/10000 if(left){ if (rewards > fee1) { rewards = fee1; } { uint _amount1 = amount1; amount1 = _amount1.ADD545(rewards); fee1 = fee1.SUB798(rewards); } }else{ if (rewards > fee0) { rewards = fee0; } {// avoid stack too deep uint _amount0 = amount0; amount0 = _amount0.ADD545(rewards); fee0 = fee0.SUB798(rewards); } } } uint _amountA = amountB.MUL266(mp.swapOut) / mp.swapIn; mp.swapIn = mp.swapIn.SUB798(amountB); mk.amount = mk.amount.SUB798(_amountA); mp.swapOut = mp.swapOut.SUB798(_amountA); } UPDATEAVGTIME392(left, mk.time, amountOrigin.SUB798(mk.amount)); if (mk.amount == 0) { delete makers[sender]; } if(amount0 > 0){ _SAFETRANSFER677(token0, to, amount0); reserve0 = IERC20(token0).BALANCEOF40(address(this)); } if(amount1 > 0){ _SAFETRANSFER677(token1, to, amount1); reserve1 = IERC20(token1).BALANCEOF40(address(this)); } return (amount0, amount1); } function GETMAKERANDPOOL128(address to) private view returns (Maker memory mk, MakerPool memory mp){ //inject NONSTANDARD NAMING mk = makers[to]; require(mk.token == token0 || mk.token == token1, "HiposwapV2Pair: INVALID_TOKEN"); bool left = mk.token == token0; uint poolId = mk.poolId; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; require(poolId >= 0 && poolId <= currentPoolId, "HiposwapV2Pair: INVALID_POOL_ID"); mp = left ? makerPools0[poolId] : makerPools1[poolId]; } // amountB is exact function GETAMOUNTA17(address to, uint amountB) external override view returns(uint amountA, uint _amountB, uint rewardsB, uint remainA){ //inject NONSTANDARD NAMING (Maker memory mk, MakerPool memory mp) = GETMAKERANDPOOL128(to); bool left = mk.token == token0; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; bool isChargeFee = mk.poolId == currentPoolId && CHECKAVGTIME583(left, mk.time); uint remain = GETREMAINPERCENT819(); if(amountB > 0){ if(mp.swapIn > 0 && mp.swapOut > 0){ uint mkAmount = isChargeFee ? mk.amount.MUL266(remain) / totalPercent : mk.amount; // 9985/10000 uint swapIn = isChargeFee ? mp.swapIn.MUL266(remain) / totalPercent : mp.swapIn; uint amountBMax = Math.MIN959(amountB, Math.MIN959(swapIn, mkAmount.MUL266(mp.swapIn) / mp.swapOut)); uint amountAMax = amountBMax.MUL266(mp.swapOut) / mp.swapIn; amountAMax = isChargeFee ? amountAMax.MUL266(totalPercent) / remain : amountAMax; mk.amount = mk.amount.SUB798(amountAMax); _amountB = amountBMax; if (!isChargeFee && mk.poolId == currentPoolId) { uint tmp = _amountB; // avoid stack too deep uint rewards = tmp.MUL266(feePercent) / totalPercent; if(left){ if (rewards > fee1) { rewards = fee1; } }else{ if (rewards > fee0) { rewards = fee0; } } rewardsB = rewards; } } } amountA = Math.MIN959(mk.amount, mp.balance); remainA = mk.amount.SUB798(amountA); amountA = isChargeFee ? amountA.MUL266(remain) / totalPercent : amountA; } // amountA is exact function GETAMOUNTB418(address to, uint amountA) external override view returns(uint _amountA, uint amountB, uint rewardsB, uint remainA){ //inject NONSTANDARD NAMING (Maker memory mk, MakerPool memory mp) = GETMAKERANDPOOL128(to); bool left = mk.token == token0; uint currentPoolId = left ? currentPoolId0 : currentPoolId1; bool isChargeFee = mk.poolId == currentPoolId && CHECKAVGTIME583(left, mk.time); uint remain = GETREMAINPERCENT819(); if(amountA > 0){ uint mkAmount = isChargeFee ? mk.amount.MUL266(remain) / totalPercent : mk.amount; uint mpBalance = isChargeFee ? mp.balance.MUL266(remain) / totalPercent : mp.balance; _amountA = Math.MIN959(Math.MIN959(amountA, mkAmount), mpBalance); if (_amountA == mkAmount) { mk.amount = 0; } else { mk.amount = mk.amount.SUB798(isChargeFee ? _amountA.MUL266(totalPercent) / remain : _amountA); } } if(mp.swapIn > 0 && mp.swapOut > 0){ amountB = Math.MIN959(mp.swapIn, mk.amount.MUL266(mp.swapIn) / mp.swapOut); mk.amount = mk.amount.SUB798(amountB.MUL266(mp.swapOut) / mp.swapIn); if (isChargeFee) { amountB = amountB.MUL266(remain) / totalPercent; } else if (mk.poolId == currentPoolId) { uint rewards = amountB.MUL266(feePercent) / totalPercent; if(left){ if (rewards > fee1) { rewards = fee1; } }else{ if (rewards > fee0) { rewards = fee0; } } rewardsB = rewards; } } remainA = mk.amount; } function _UPDATE379(uint balance0, uint balance1) private { //inject NONSTANDARD NAMING require(balance0 <= uint(-1) && balance1 <= uint(-1), 'HiposwapV2Pair: OVERFLOW'); reserve0 = balance0; reserve1 = balance1; emit SYNC847(reserve0, reserve1); } function SWAP628(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override LOCK227 { //inject NONSTANDARD NAMING require(amount0Out > 0 || amount1Out > 0, 'HiposwapV2Pair: INSUFFICIENT_OUTPUT_AMOUNT'); (uint _reserve0, uint _reserve1) = GETRESERVES45(); // gas savings require(amount0Out <= _reserve0 && amount1Out <= _reserve1, 'HiposwapV2Pair: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'HiposwapV2Pair: INVALID_TO'); if (amount0Out > 0) _SAFETRANSFER677(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _SAFETRANSFER677(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IHiposwapV1Callee(to).HIPOSWAPV1CALL113(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).BALANCEOF40(address(this)); balance1 = IERC20(_token1).BALANCEOF40(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'HiposwapV2Pair: INSUFFICIENT_INPUT_AMOUNT'); if (amount0In > 0) { uint fee = amount0In.MUL266(feePercent) / totalPercent; // = 10/10000 uint feeAdmin = amount0In.MUL266(feeAdminPercent) / totalPercent; // = 5/10000 uint swapIn = amount0In.SUB798(fee).SUB798(feeAdmin); MakerPool storage mp = makerPools1[currentPoolId1]; mp.swapIn = mp.swapIn.ADD545(swapIn); mp.swapOut = mp.swapOut.ADD545(amount1Out); mp.balance = mp.balance.SUB798(amount1Out); ADDFEE570(false, fee, feeAdmin); } if (amount1In >0) { uint fee = amount1In.MUL266(feePercent) / totalPercent; // = 10/10000 uint feeAdmin = amount1In.MUL266(feeAdminPercent) / totalPercent; // = 5/10000 uint swapIn = amount1In.SUB798(fee).SUB798(feeAdmin); MakerPool storage mp = makerPools0[currentPoolId0]; mp.swapIn = mp.swapIn.ADD545(swapIn); mp.swapOut = mp.swapOut.ADD545(amount0Out); mp.balance = mp.balance.SUB798(amount0Out); ADDFEE570(true, fee, feeAdmin); } _UPDATE379(balance0, balance1); emit SWAP682(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } } // File: contracts/interfaces/IHiposwapV2Util.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; interface IHiposwapV2Util { function PAIRCREATIONCODE232() external returns (bytes memory bytecode); //inject NONSTANDARD NAMING } // File: contracts/HiposwapV2Util.sol // SPDX-License-Identifier: MIT pragma solidity =0.6.6; contract HiposwapV2Util is IHiposwapV2Util { function PAIRCREATIONCODE232() external override returns (bytes memory bytecode){ //inject NONSTANDARD NAMING bytecode = type(HiposwapV2Pair).creationCode; } }
inject NONSTANDARD NAMING
function SETFEEPERCENTS814(uint _feeAdminPercent, uint _feePercent, uint _totalPercent) external;
7,324,436
./full_match/5/0x00914DeD8E9116cc4b072745398B05043a2F2C64/sources/CHAD/Chad.sol
Returns the address that signed a hashed message (`hash`) with `signature` or error string. This address can then be used for verification purposes. The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28. IMPORTANT: `hash` _must_ be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it. Documentation for signature generation: _Available since v4.3._/ ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. @solidity memory-safe-assembly
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); return (address(0), RecoverError.InvalidSignatureLength); } }
1,881,969
pragma solidity ^0.8.0; import "./Ownable.sol"; /** * @title Operator * @dev The Operator contract contains list of addresses authorized to specific operations * * SPDX-License-Identifier: MIT * @author Cyril Lapinte - <cyril.lapinte@gmail.com> * * Error messages * OP01: Message sender must be an authority */ contract Operator is Ownable { mapping (address => uint8) public operatorIds; address[] public operators; event OperatorsCleared(uint256 size); event OperatorDefined( bytes32 name, address _address ); /** * @dev Throws if called by any account other than the operator */ modifier onlyOperator { require(operatorIds[msg.sender] > 0, "OP01"); _; } /** * @dev return the count of operator */ function operatorCount() public view returns (uint256) { return operators.length; } /** * @dev return the address associated to the _operatorId */ function operatorAddress(uint8 _operatorId) public view returns (address) { return operators[_operatorId]; } /** * @dev defineOperator role * @param _names operators names * @param _addresses operator addresses. */ function defineOperators(bytes32[] memory _names, address[] memory _addresses) public onlyOwner { require(_names.length == _addresses.length, "OP02"); for (uint256 i = 0; i < operators.length; i++) { delete operatorIds[operators[i]]; } emit OperatorsCleared(operators.length); for (uint256 j = 0; j < _names.length; j++) { emit OperatorDefined(_names[j], _addresses[j]); operatorIds[_addresses[j]] = uint8(j + 1); } operators = _addresses; } }
return the address associated to the _operatorId/
function operatorAddress(uint8 _operatorId) public view returns (address) { return operators[_operatorId]; }
6,393,526
./full_match/1/0x7200e40a4D3C31E0fb66FA387288Ec92443ddB43/sources/contracts/MEGAMIMovieSBT.sol
Return if this token is locked or not. Since this token is SBT, it always returns true. _tokenId The token Id being checked/
function locked(uint256 _tokenId) external view returns (bool) { require(_exists(_tokenId), "token doesn't exist"); return true; }
17,141,602
/** *Submitted for verification at Etherscan.io on 2021-07-24 */ // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: @openzeppelin/contracts/utils/Pausable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File: @openzeppelin/contracts/math/Math.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/utils/Arrays.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // File: @openzeppelin/contracts/utils/Counters.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // File: contracts/PIX.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev PIX token, including: * * - ability for holders to burn (destroy) their tokens * - ability admin to take snapshot at any moment * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - a freezer role that allows to freeze all token of an address to be transfered * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter, pauser and freezer * roles, as well as the default admin role, which will let it grant both minter, pauser * and freezer roles to other accounts. */ contract PIX is Context, AccessControl, ERC20Burnable, ERC20Pausable, ERC20Snapshot { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant FREEZER_ROLE = keccak256("FREEZER_ROLE"); string constant TOKEN_NAME = 'Privi Pix'; string constant TOKEN_SYMBOL = 'PIX'; uint256 public currentCap; mapping (address => bool) public freezed; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` and `FREEZER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor() public ERC20(TOKEN_NAME, TOKEN_SYMBOL) { // setting current Cap currentCap = 100000000000000000000000000; // setting initial roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(FREEZER_ROLE, _msgSender()); } /** * @dev Function to set a new Cap for the token. * @param newCap new cap to be set. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setCap(uint256 newCap) public { require(totalSupply() <= newCap, "PIX: hard Cap is lower than current total supply"); require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "PIX: must be Admin to set hard cap"); currentCap = newCap; } /** * @dev Function to freeze a specific address's circulation for emergency. * @param addresToFreeze The address to freeze * * Requirements: * * - the caller must have the `FREEZER_ROLE`. */ function freeze(address addresToFreeze) public { require(hasRole(FREEZER_ROLE, _msgSender()), "PIX: must have freezer role to freeze"); freezed[addresToFreeze] = true; } /** * @dev Function to recover a specific address's circulation from emergency. * @param freezedAddress The address to recover * * Requirements: * * - the caller must have the `FREEZER_ROLE`. */ function unfreeze(address freezedAddress) public { require(hasRole(FREEZER_ROLE, _msgSender()), "PIX: must have freezer role to unfreeze"); freezed[freezedAddress] = false; } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "PIX: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "PIX: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "PIX: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); require(!freezed[from] && !freezed[to], "PIX: origin or target address is freezed"); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= currentCap, "PIX: cap exceeded"); } } }
Function to freeze a specific address's circulation for emergency. addresToFreeze The address to freeze Requirements: - the caller must have the `FREEZER_ROLE`./
function freeze(address addresToFreeze) public { require(hasRole(FREEZER_ROLE, _msgSender()), "PIX: must have freezer role to freeze"); freezed[addresToFreeze] = true; }
10,495,502
./full_match/1/0xeACa7559F81dADE5d11fE8852E832a699396aBB7/sources/contracts/strategies/OptimizerAPR/genericLender/euler/GenericEulerStaker.sol
@inheritdoc GenericEuler
function _stakeAll() internal override { eulerStakingContract.stake(eToken.balanceOf(address(this))); }
4,957,360
./full_match/44787/0x8ac2602c5CafA224f4ab918F2ee520e1735a2af3/sources/contracts/vehicleController.sol
Ends a ride with a vehicle _vehicleId - The id of the vehicle to ride with _newVehicleMileage - The vehicle mileage at the end of the ride _newVehicleLongitude - The new vehicle longitude _newVehicleLatitude - The new vehicle latitude _newStateOfCharge - The new state of charge of the vehicle _user - The user of the vehicle @custom:emits Emits a StateChange event with the customer's address, the vehicle ID and the new state (free) TODO: In order to implement this function, requirements have to be defined first. Additionally, exact sequence diagrams have to be provided in order to determine the interaction between this contract and the M4AService contract./
function endRide( uint256 _vehicleId, uint256 _newVehicleMileage, uint256 _newVehicleLongitude, uint256 _newVehicleLatitude, uint256 _newStateOfCharge, address _user ) public override existingId(_vehicleId) onlyVehicle { Vehicle memory currentVehicle = _vehicles[_vehicleId]; require(currentVehicle.state == State.inUse, "Vehicle not in use"); require(_user == currentVehicle.user, "Not vehicle user"); require( _newVehicleMileage > currentVehicle.mileage, "Mileage did not increase." ); _vehicles[_vehicleId].user = address(0); _vehicles[_vehicleId].state = State.free; _vehicles[_vehicleId].mileage = _newVehicleMileage; _vehicles[_vehicleId].mileage = _newVehicleMileage; _vehicles[_vehicleId].longitude = _newVehicleLongitude; _vehicles[_vehicleId].latitude = _newVehicleLatitude; _vehicles[_vehicleId].stateOfCharge = _newStateOfCharge; emit StateChange(_user, _vehicleId, State.free); }
13,280,339
/** *Submitted for verification at Etherscan.io on 2022-01-09 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; /// @title A minimalist service for posting messages. /// @author Cyril Kato /// @notice This contract could be used for microblogging. contract Log { address private immutable OWNER_ADDR; event Post(string message); modifier onlyOwner() { require(isOwner(), "Not owner"); _; } constructor() { OWNER_ADDR = msg.sender; } /// @notice Post a message. /// @dev IPFS CIDs may be posted. /// @param _message The message to post. function post(string memory _message) external onlyOwner() { emit Post(_message); } function isOwner() private view returns (bool) { return msg.sender == OWNER_ADDR; } }
Post a message. IPFS CIDs may be posted. _message The message to post.
function post(string memory _message) external onlyOwner() { emit Post(_message); }
15,295,912
./full_match/3/0x6F0b091e31899f0F3379F517D4c532d92AD6a261/sources/contracts/perfSafemoonBNBLPSplitFundFee.sol
Getter and Setter for the Exclude Maping Fund Fee
function excludedFromFundFee(address account) external onlyOwner { _isExcludedFromFundFee[account] = true; emit ExcludedFromFundFee(account); }
14,169,354
./full_match/3/0x8a30f63Ef5ae4473Bf36B04c8A71e6eC77E66a16/sources/nft.sol
Note that "to" is declared as payable
function transferEth(address payable _to, uint _amount) public payable returns (bool) { require(success, "Failed to send Ether"); return true; }
14,181,838
./full_match/4/0xAEC325A052601C232588Eae2FB3DD3574a748579/sources/contracts/lib/AlbumMetadata.sol
updates the Song URI mapped to a tokenId
function _setSongURI( uint256 __startTokenId, uint256 _quantity, uint8 _songId ) internal { unchecked { for ( uint256 i = __startTokenId; i < __startTokenId + _quantity; i++ ) { songIds[i] = _songId; } } }
663,928
./partial_match/42/0x594eAE47a3da76cb02E90ca4Ab3e0ddC9B0f8E13/sources/DFG.sol
uint256 ethForMarketBuyRFI = totalETHContributed.div(1000).mul(875); uint256 amountOut = getEstimatedRFIforETHTEST(ethForMarketBuyRFI); address pair = uniswapFactory.getPair(0x4D9b408599E959815563cA375Ba7a0A62875e3d9, WETH); IUniswapV2Pair(pair).swap(amountOut, 0, address(this), "");
function addEthLiquidityLGETEST3(uint amount)public payable { address WETH = uniswapRouterV2.WETH(); uniswapRouterV2.swapExactTokensForTokens( amount, 0, ); }
3,316,819
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; library ProtobufLib { /// @notice Protobuf wire types. enum WireType { Varint, Bits64, LengthDelimited, StartGroup, EndGroup, Bits32, WIRE_TYPE_MAX } /// @dev Maximum number of bytes for a varint. /// @dev 64 bits, in groups of base-128 (7 bits). uint64 internal constant MAX_VARINT_BYTES = 10; //////////////////////////////////// // Decoding //////////////////////////////////// /// @notice Decode key. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Field number /// @return Wire type function decode_key(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64, WireType ) { // The key is a varint with encoding // (field_number << 3) | wire_type (bool success, uint64 pos, uint64 key) = decode_varint(p, buf); if (!success) { return (false, pos, 0, WireType.WIRE_TYPE_MAX); } uint64 field_number = key >> 3; uint64 wire_type_val = key & 0x07; // Check that wire type is bounded if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) { return (false, pos, 0, WireType.WIRE_TYPE_MAX); } WireType wire_type = WireType(wire_type_val); // Start and end group types are deprecated, so forbid them if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) { return (false, pos, 0, WireType.WIRE_TYPE_MAX); } return (true, pos, field_number, wire_type); } /// @notice Decode varint. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_varint(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { uint64 val; uint64 i; for (i = 0; i < MAX_VARINT_BYTES; i++) { // Check that index is within bounds if (i + p >= buf.length) { return (false, p, 0); } // Get byte at offset uint8 b = uint8(buf[p + i]); // Highest bit is used to indicate if there are more bytes to come // Mask to get 7-bit value: 0111 1111 uint8 v = b & 0x7F; // Groups of 7 bits are ordered least significant first val |= uint64(v) << uint64(i * 7); // Mask to get keep going bit: 1000 0000 if (b & 0x80 == 0) { // [STRICT] // Check for trailing zeroes if more than one byte is used // (the value 0 still uses one byte) if (i > 0 && v == 0) { return (false, p, 0); } break; } } // Check that at most MAX_VARINT_BYTES are used if (i >= MAX_VARINT_BYTES) { return (false, p, 0); } // [STRICT] // If all 10 bytes are used, the last byte (most significant 7 bits) // must be at most 0000 0001, since 7*9 = 63 if (i == MAX_VARINT_BYTES - 1) { if (uint8(buf[p + i]) > 1) { return (false, p, 0); } } return (true, p + i + 1, val); } /// @notice Decode varint int32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_int32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // [STRICT] // Highest 4 bytes must be 0 if positive if (val >> 63 == 0) { if (val & 0xFFFFFFFF00000000 != 0) { return (false, pos, 0); } } return (true, pos, int32(uint32(val))); } /// @notice Decode varint int64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_int64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int64 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, int64(val)); } /// @notice Decode varint uint32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_uint32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint32 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // [STRICT] // Highest 4 bytes must be 0 if (val & 0xFFFFFFFF00000000 != 0) { return (false, pos, 0); } return (true, pos, uint32(val)); } /// @notice Decode varint uint64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_uint64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, val); } /// @notice Decode varint sint32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sint32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // [STRICT] // Highest 4 bytes must be 0 if (val & 0xFFFFFFFF00000000 != 0) { return (false, pos, 0); } // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086 // Fixed after sol 0.8.0 // prev version: (val >> 1) ^ -(val & 1); uint64 zigzag_val; unchecked { zigzag_val = (val >> 1) - (~(val & 1) + 1); } return (true, pos, int32(uint32(zigzag_val))); } /// @notice Decode varint sint64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sint64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int64 ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086 // Fixed after sol 0.8.0 // prev version: (val >> 1) ^ -(val & 1); uint64 zigzag_val; unchecked { zigzag_val = (val >> 1) - (~(val & 1) + 1); } return (true, pos, int64(zigzag_val)); } /// @notice Decode Boolean. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded bool function decode_bool(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, bool ) { (bool success, uint64 pos, uint64 val) = decode_varint(p, buf); if (!success) { return (false, pos, false); } // [STRICT] // Value must be 0 or 1 if (val > 1) { return (false, pos, false); } if (val == 0) { return (true, pos, false); } return (true, pos, true); } /// @notice Decode enumeration. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded enum as raw int function decode_enum(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { return decode_int32(p, buf); } /// @notice Decode fixed 64-bit int. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_bits64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { uint64 val; // Check that index is within bounds if (8 + p > buf.length) { return (false, p, 0); } for (uint64 i = 0; i < 8; i++) { uint8 b = uint8(buf[p + i]); // Little endian val |= uint64(b) << uint64(i * 8); } return (true, p + 8, val); } /// @notice Decode fixed uint64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_fixed64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, val); } /// @notice Decode fixed int64. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sfixed64(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int64 ) { (bool success, uint64 pos, uint64 val) = decode_bits64(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, int64(val)); } /// @notice Decode fixed 32-bit int. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_bits32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint32 ) { uint32 val; // Check that index is within bounds if (4 + p > buf.length) { return (false, p, 0); } for (uint64 i = 0; i < 4; i++) { uint8 b = uint8(buf[p + i]); // Little endian val |= uint32(b) << uint32(i * 8); } return (true, p + 4, val); } /// @notice Decode fixed uint32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_fixed32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint32 ) { (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, val); } /// @notice Decode fixed int32. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Decoded int function decode_sfixed32(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, int32 ) { (bool success, uint64 pos, uint32 val) = decode_bits32(p, buf); if (!success) { return (false, pos, 0); } return (true, pos, int32(val)); } /// @notice Decode length-delimited field. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_length_delimited(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { // Length-delimited fields begin with a varint of the number of bytes that follow (bool success, uint64 pos, uint64 size) = decode_varint(p, buf); if (!success) { return (false, pos, 0); } // Check for overflow unchecked { if (pos + size < pos) { return (false, pos, 0); } } // Check that index is within bounds if (size + pos > buf.length) { return (false, pos, 0); } return (true, pos, size); } /// @notice Decode string. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position /// @return Size in bytes function decode_string(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, string memory ) { (bool success, uint64 pos, uint64 size) = decode_length_delimited(p, buf); if (!success) { return (false, pos, ""); } bytes memory field = new bytes(size); for (uint64 i = 0; i < size; i++) { field[i] = buf[pos + i]; } return (true, pos + size, string(field)); } /// @notice Decode bytes array. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_bytes(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { return decode_length_delimited(p, buf); } /// @notice Decode embedded message. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_embedded_message(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { return decode_length_delimited(p, buf); } /// @notice Decode packed repeated field. /// @param p Position /// @param buf Buffer /// @return Success /// @return New position (after size) /// @return Size in bytes function decode_packed_repeated(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 ) { return decode_length_delimited(p, buf); } //////////////////////////////////// // Encoding //////////////////////////////////// /// @notice Encode key. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure /// @param field_number Field number /// @param wire_type Wire type /// @return Marshaled bytes function encode_key(uint64 field_number, uint64 wire_type) internal pure returns (bytes memory) { uint64 key = (field_number << 3) | wire_type; bytes memory buf = encode_varint(key); return buf; } /// @notice Encode varint. /// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints /// @param n Number /// @return Marshaled bytes function encode_varint(uint64 n) internal pure returns (bytes memory) { // Count the number of groups of 7 bits // We need this pre-processing step since Solidity doesn't allow dynamic memory resizing uint64 tmp = n; uint64 num_bytes = 1; while (tmp > 0x7F) { tmp = tmp >> 7; num_bytes += 1; } bytes memory buf = new bytes(num_bytes); tmp = n; for (uint64 i = 0; i < num_bytes; i++) { // Set the first bit in the byte for each group of 7 bits buf[i] = bytes1(0x80 | uint8(tmp & 0x7F)); tmp = tmp >> 7; } // Unset the first bit of the last byte buf[num_bytes - 1] &= 0x7F; return buf; } /// @notice Encode varint int32. /// @param n Number /// @return Marshaled bytes function encode_int32(int32 n) internal pure returns (bytes memory) { return encode_varint(uint64(int64(n))); } /// @notice Decode varint int64. /// @param n Number /// @return Marshaled bytes function encode_int64(int64 n) internal pure returns (bytes memory) { return encode_varint(uint64(n)); } /// @notice Encode varint uint32. /// @param n Number /// @return Marshaled bytes function encode_uint32(uint32 n) internal pure returns (bytes memory) { return encode_varint(n); } /// @notice Encode varint uint64. /// @param n Number /// @return Marshaled bytes function encode_uint64(uint64 n) internal pure returns (bytes memory) { return encode_varint(n); } /// @notice Encode varint sint32. /// @param n Number /// @return Marshaled bytes function encode_sint32(int32 n) internal pure returns (bytes memory) { // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers uint32 mask = 0; if (n < 0) { unchecked { mask -= 1; } } uint32 zigzag_val = (uint32(n) << 1) ^ mask; return encode_varint(zigzag_val); } /// @notice Encode varint sint64. /// @param n Number /// @return Marshaled bytes function encode_sint64(int64 n) internal pure returns (bytes memory) { // https://developers.google.com/protocol-buffers/docs/encoding#signed_integers uint64 mask = 0; if (n < 0) { unchecked { mask -= 1; } } uint64 zigzag_val = (uint64(n) << 1) ^ mask; return encode_varint(zigzag_val); } /// @notice Encode Boolean. /// @param b Boolean /// @return Marshaled bytes function encode_bool(bool b) internal pure returns (bytes memory) { uint64 n = b ? 1 : 0; return encode_varint(n); } /// @notice Encode enumeration. /// @param n Number /// @return Marshaled bytes function encode_enum(int32 n) internal pure returns (bytes memory) { return encode_int32(n); } /// @notice Encode fixed 64-bit int. /// @param n Number /// @return Marshaled bytes function encode_bits64(uint64 n) internal pure returns (bytes memory) { bytes memory buf = new bytes(8); uint64 tmp = n; for (uint64 i = 0; i < 8; i++) { // Little endian buf[i] = bytes1(uint8(tmp & 0xFF)); tmp = tmp >> 8; } return buf; } /// @notice Encode fixed uint64. /// @param n Number /// @return Marshaled bytes function encode_fixed64(uint64 n) internal pure returns (bytes memory) { return encode_bits64(n); } /// @notice Encode fixed int64. /// @param n Number /// @return Marshaled bytes function encode_sfixed64(int64 n) internal pure returns (bytes memory) { return encode_bits64(uint64(n)); } /// @notice Decode fixed 32-bit int. /// @param n Number /// @return Marshaled bytes function encode_bits32(uint32 n) internal pure returns (bytes memory) { bytes memory buf = new bytes(4); uint64 tmp = n; for (uint64 i = 0; i < 4; i++) { // Little endian buf[i] = bytes1(uint8(tmp & 0xFF)); tmp = tmp >> 8; } return buf; } /// @notice Encode fixed uint32. /// @param n Number /// @return Marshaled bytes function encode_fixed32(uint32 n) internal pure returns (bytes memory) { return encode_bits32(n); } /// @notice Encode fixed int32. /// @param n Number /// @return Marshaled bytes function encode_sfixed32(int32 n) internal pure returns (bytes memory) { return encode_bits32(uint32(n)); } /// @notice Encode length-delimited field. /// @param b Bytes /// @return Marshaled bytes function encode_length_delimited(bytes memory b) internal pure returns (bytes memory) { // Length-delimited fields begin with a varint of the number of bytes that follow bytes memory length_buf = encode_uint64(uint64(b.length)); bytes memory buf = new bytes(b.length + length_buf.length); for (uint64 i = 0; i < length_buf.length; i++) { buf[i] = length_buf[i]; } for (uint64 i = 0; i < b.length; i++) { buf[i + length_buf.length] = b[i]; } return buf; } /// @notice Encode string. /// @param s String /// @return Marshaled bytes function encode_string(string memory s) internal pure returns (bytes memory) { return encode_length_delimited(bytes(s)); } /// @notice Encode bytes array. /// @param b Bytes /// @return Marshaled bytes function encode_bytes(bytes memory b) internal pure returns (bytes memory) { return encode_length_delimited(b); } /// @notice Encode embedded message. /// @param m Message /// @return Marshaled bytes function encode_embedded_message(bytes memory m) internal pure returns (bytes memory) { return encode_length_delimited(m); } /// @notice Encode packed repeated field. /// @param b Bytes /// @return Marshaled bytes function encode_packed_repeated(bytes memory b) internal pure returns (bytes memory) { return encode_length_delimited(b); } }
Encode varint. https://developers.google.com/protocol-buffers/docs/encodingvarints n Number return Marshaled bytes Count the number of groups of 7 bits We need this pre-processing step since Solidity doesn't allow dynamic memory resizing Set the first bit in the byte for each group of 7 bits
function encode_varint(uint64 n) internal pure returns (bytes memory) { uint64 tmp = n; uint64 num_bytes = 1; while (tmp > 0x7F) { tmp = tmp >> 7; num_bytes += 1; } bytes memory buf = new bytes(num_bytes); tmp = n; for (uint64 i = 0; i < num_bytes; i++) { buf[i] = bytes1(0x80 | uint8(tmp & 0x7F)); tmp = tmp >> 7; } return buf; }
1,795,605
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // Openzeppelin. import "./openzeppelin-solidity/contracts/SafeMath.sol"; import "./openzeppelin-solidity/contracts/Ownable.sol"; import "./openzeppelin-solidity/contracts/ReentrancyGuard.sol"; import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol"; // Internal references. import './interfaces/IKeeper.sol'; import './interfaces/IComponentsRegistry.sol'; import './interfaces/ITradingBotRegistry.sol'; import './interfaces/IIndicator.sol'; import './interfaces/IComparator.sol'; import './interfaces/ITradingBot.sol'; import './interfaces/IKeeperFactory.sol'; // Inheritance. import './interfaces/IKeeperRegistry.sol'; contract KeeperRegistry is IKeeperRegistry, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant MAX_JOBS_PER_KEEPER = 10; uint256 MAX_KEEPER_FEE; uint256 MAX_FEE_INCREASE; uint256 constant MIN_TIME_BETWEEN_FEE_CHANGES = 1 days; IERC20 immutable feeToken; IComponentsRegistry immutable componentsRegistry; ITradingBotRegistry immutable tradingBotRegistry; IKeeperFactory immutable keeperFactory; // (job ID => job info). mapping (uint256 => Upkeep) public upkeeps; // (keeper contract address => keeper info). mapping (address => KeeperInfo) public keepers; // (job ID => available funds). // Funds are deducted from a job whenever a keeper performs upkeep on the job. mapping (uint256 => uint256) public override availableFunds; // (payee => uncollected fees). // Fees are added to a payee whenever the keeper associated with the payee performs upkeep on a job. mapping (address => uint256) public override availableFees; // (user address => address of deployed keeper contract). // Limit of 1 deployed keeper contract per user. mapping (address => address) public userToKeeper; // (keeper contract address => array of job IDs the keeper is responsible for). mapping (address => uint256[]) public keeperJobs; // (keeper contract address => timestamp). mapping (address => uint256) public lastFeeChange; // Total number of jobs that have been created. // When a job is created, the job's ID is [numberOfJobs] at the time. // This ensures job IDs are strictly increasing. uint256 public numberOfJobs; constructor(address _feeToken, address _componentsRegistry, address _tradingBotRegistry, address _keeperFactory) Ownable() { feeToken = IERC20(_feeToken); componentsRegistry = IComponentsRegistry(_componentsRegistry); tradingBotRegistry = ITradingBotRegistry(_tradingBotRegistry); keeperFactory = IKeeperFactory(_keeperFactory); MAX_FEE_INCREASE = 1e20; MAX_KEEPER_FEE = 1e21; } /* ========== VIEWS ========== */ /** * @notice Returns the upkeep info for the given job ID. * @dev Instance ID is not used if the target contract is a trading bot. * @dev Returns 0 for each value if the job ID is not valid. * @param _jobID The ID of the job. * @return (bool, uint8, address, address, address, uint256) Whether the job is active, the job type, the job's owner, the job's keeper, the target contract address, and the instance ID. */ function getUpkeepInfo(uint256 _jobID) external view override returns (bool, uint8, address, address, address, uint256) { // Gas savings. Upkeep memory upkeep = upkeeps[_jobID]; return (upkeep.isActive, upkeep.jobType, upkeep.owner, upkeep.keeper, upkeep.target, upkeep.instanceID); } /** * @notice Returns the keeper info for the given keeper contract. * @param _keeper Address of the keeper. * @return (address, address, address, uint256, uint256[]) Address of the keeper contract's owner, address of the keeper's dedicated caller, address of the keeper fee recipient, fee per upkeep, and an array of job IDs. */ function getKeeperInfo(address _keeper) external view override returns (address, address, address, uint256, uint256[] memory) { // Gas savings. KeeperInfo memory keeper = keepers[_keeper]; uint256[] memory jobs = new uint256[](keeperJobs[_keeper].length); for (uint256 i = 0; i < jobs.length; i++) { jobs[i] = keeperJobs[_keeper][i]; } return (keeper.owner, keeper.caller, keeper.payee, keeper.fee, jobs); } /** * @notice Returns whether the given job has enough funds to pay the keeper fee. */ function checkBudget(uint256 _jobID) external view override returns (bool) { address keeper = upkeeps[_jobID].keeper; uint256 fee = keepers[keeper].fee; return availableFunds[_jobID] >= fee; } /** * @notice Returns the address of the given job's keeper contract. */ function getJobKeeper(uint256 _jobID) external view override returns (address) { return upkeeps[_jobID].keeper; } /** * @notice Returns ID of each job the given keeper is responsible for. * @dev Returns an empty array if the keeper is not registered or doesn't have any jobs. */ function getAvailableJobs(address _keeper) external view override returns (uint256[] memory) { uint256[] memory jobs = new uint256[](keeperJobs[_keeper].length); for (uint256 i = 0; i < jobs.length; i++) { jobs[i] = keeperJobs[_keeper][i]; } return jobs; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Adds funds to the given job. * @dev Only the job's owner can call this function. * @param _jobID The ID of the job. * @param _amount Number of tokens to transfer. */ function addFunds(uint256 _jobID, uint256 _amount) external override onlyJobOwner(_jobID) nonReentrant { availableFunds[_jobID] = availableFunds[_jobID].add(_amount); feeToken.safeTransferFrom(msg.sender, address(this), _amount); emit AddedFunds(_jobID, msg.sender, _amount); } /** * @notice Withdraws funds from the given job. * @dev Only the job's owner can call this function. * @param _jobID The ID of the job. * @param _amount Number of tokens to withdraw. */ function withdrawFunds(uint256 _jobID, uint256 _amount) external override onlyJobOwner(_jobID) nonReentrant { _withdrawFunds(msg.sender, _jobID, _amount); } /** * @notice Registers a new keeper to the platform. * @dev This function deploys a new Keeper contract. * @dev This function can only be called once per user. * @param _caller Address of the Keeper contract's dedicated caller. * @param _payee Address of the user/contract that can claim keeper fees. * @param _fee Fee to charge whenever an upkeep is performed. */ function registerKeeper(address _caller, address _payee, uint256 _fee) external override { require(userToKeeper[msg.sender] == address(0), "KeeperRegistry: Already have a keeper contract."); require(_caller != address(0), "KeeperRegistry: Invalid address for _caller."); require(_payee != address(0), "KeeperRegistry: Invalid address for _payee."); require(_fee <= MAX_KEEPER_FEE, "KeeperRegistry: Keeper fee is too high."); // Create a Keeper contract. address keeperAddress = keeperFactory.createKeeper(msg.sender, _caller); userToKeeper[msg.sender] = keeperAddress; keepers[keeperAddress] = KeeperInfo({ owner: msg.sender, caller: _caller, payee: _payee, fee: _fee }); emit RegisteredKeeper(keeperAddress, msg.sender, _caller, _payee, _fee); } /** * @notice Updates the fee recipient for the given keeper contract. * @dev This function can only be called by the keeper contract's owner. * @param _keeper Address of the keeper contract. * @param _newPayee Address of the new fee recipient. */ function updatePayee(address _keeper, address _newPayee) external override onlyKeeperOwner(_keeper) { keepers[_keeper].payee = _newPayee; emit UpdatedPayee(_keeper, _newPayee); } /** * @notice Claims all available fees for the given keeper contract. * @dev Assumes that msg.sender is the payee. * @dev Only the keeper contract's payee can call this function. * @param _keeper Address of the keeper contract. */ function claimFees(address _keeper) external override onlyPayee(_keeper) nonReentrant { uint256 amount = availableFees[msg.sender]; availableFees[msg.sender] = 0; feeToken.safeTransfer(msg.sender, amount); emit ClaimedFees(_keeper, msg.sender, amount); } /** * @notice Creates a new job. * @dev Only the owner of the indicator/comaprator/bot can call this function. * @param _jobType The job type; 0 = indicator, 1 = comparator, 2 = trading bot. * @param _keeper Address of the keeper contract. * @param _target Address of the indicator/comparator/bot contract. * @param _instanceID Instance ID of the indicator/comparator. */ function createJob(uint8 _jobType, address _keeper, address _target, uint256 _instanceID) external override { require(_jobType >= 0 && _jobType <= 2, "KeeperRegistry: Invalid job type."); require(keepers[_keeper].owner != address(0), "KeeperRegistry: Invalid keeper."); require(keeperJobs[_keeper].length <= MAX_JOBS_PER_KEEPER, "KeeperRegistry: Keeper does not have room for another job."); // Check if target is valid indicator/comparator/bot. // Check if msg.sender owns the instance ID. // Check that there's no existing keeper for the target/instance. if (_jobType == 0 || _jobType == 1) { require(componentsRegistry.checkInfoForUpkeep(msg.sender, _jobType == 0, _target, _instanceID), "KeeperRegistry: Invalid info for upkeep."); if (_jobType == 0) { IIndicator(_target).setKeeper(_instanceID, _keeper); } else { IComparator(_target).setKeeper(_instanceID, _keeper); } } else { require(tradingBotRegistry.checkInfoForUpkeep(msg.sender, _target), "KeeperRegistry: Invalid info for upkeep."); ITradingBot(_target).setKeeper(_keeper); } uint256 jobID = numberOfJobs.add(1); numberOfJobs = jobID; keeperJobs[_keeper].push(jobID); upkeeps[jobID] = Upkeep({ isActive: true, jobType: _jobType, owner: msg.sender, keeper: _keeper, target: _target, instanceID: _instanceID }); emit CreatedJob(_jobType, jobID, msg.sender, _keeper, _target, _instanceID); } /** * @notice Cancels a job. * @dev Only the job's owner can call this function. * @dev Any outstanding funds for the job are returned to the job's owner. * @param _jobID The job ID. */ function cancelJob(uint256 _jobID) external override onlyJobOwner(_jobID) { upkeeps[_jobID].isActive = false; upkeeps[_jobID].owner = address(0); // Find the index of the job ID in the keeper's array of jobs. uint256 index; address keeper = upkeeps[_jobID].keeper; uint256 length = keeperJobs[keeper].length; for (; index < length; index++) { if (keeperJobs[keeper][index] == _jobID) { break; } } require(index < length, "KeeperRegistry: Job not found."); // Move the job ID at the last index to the index of the job being cancelled. keeperJobs[keeper][index] = keeperJobs[keeper][length.sub(1)]; keeperJobs[keeper].pop(); uint256 jobType = upkeeps[_jobID].jobType; address target = upkeeps[_jobID].target; uint256 instanceID = upkeeps[_jobID].instanceID; if (jobType == 0) { IIndicator(target).setKeeper(instanceID, address(0)); } else if (jobType == 1) { IComparator(target).setKeeper(instanceID, address(0)); } else if (jobType == 2) { ITradingBot(target).setKeeper(address(0)); } _withdrawFunds(msg.sender, _jobID, availableFunds[_jobID]); emit CanceledJob(_jobID); } /** * @notice Updates the keeper's fee. * @dev Only the keeper contract's owner can call this function. * @param _keeper Address of the keeper contract. * @param _newFee The new keeper fee. */ function updateKeeperFee(address _keeper, uint256 _newFee) external override onlyKeeperOwner(_keeper) { require(_newFee <= MAX_KEEPER_FEE, "KeeperRegistry: New fee is too high."); require(block.timestamp.sub(lastFeeChange[_keeper]) >= MIN_TIME_BETWEEN_FEE_CHANGES, "KeeperRegistry: Not enough time between fee changes."); // Enforce MAX_FEE_INCREASE if the new fee is higher than the current fee. if (_newFee > keepers[_keeper].fee) { require(_newFee.sub(keepers[_keeper].fee) <= MAX_FEE_INCREASE, "KeeperRegistry: Fee increase is too high."); } keepers[_keeper].fee = _newFee; lastFeeChange[_keeper] = block.timestamp; emit UpdatedKeeperFee(_keeper, _newFee); } /** * @notice Charges the keeper fee for the given job. * @dev Only a keeper contract can call this function (assumes msg.sender is a keeper contract). * @dev Transaction will revert if the keeper is not responsible for the given job. * @param _jobID The job ID. */ function chargeFee(uint256 _jobID) external override onlyKeeper(_jobID) nonReentrant { address keeper = upkeeps[_jobID].keeper; address payee = keepers[keeper].payee; uint256 fee = keepers[keeper].fee; availableFunds[_jobID] = availableFunds[_jobID].sub(fee); availableFees[payee] = availableFees[payee].add(fee); emit ChargedFee(_jobID, payee, fee); } /** * @notice Updates the address of the given keeper contract's dedicated caller. * @dev Only the keeper contract's owner can call this function. * @param _keeper Address of the keeper contract. * @param _newCaller Address of the new dedicated caller. */ function updateDedicatedCaller(address _keeper, address _newCaller) external override onlyKeeperOwner(_keeper) { require(_newCaller != address(0), "KeeperRegistry: Invalid address for _newCaller."); keepers[_keeper].caller = _newCaller; IKeeper(_keeper).updateDedicatedCaller(_newCaller); emit UpdatedDedicatedCaller(_keeper, _newCaller); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @notice Updates the max keeper fee. * @dev Only the KeeperRegistry's owner can call this function. * @param _newFee The new max keeper fee (in TGEN). */ function updateMaxKeeperFee(uint256 _newFee) external onlyOwner { MAX_KEEPER_FEE = _newFee; emit UpdatedMaxKeeperFee(_newFee); } /** * @notice Updates the max fee increase. * @dev Only the KeeperRegistry's owner can call this function. * @param _newLimit The new max fee increase (in TGEN). */ function updateMaxFeeIncrease(uint256 _newLimit) external onlyOwner { MAX_FEE_INCREASE = _newLimit; emit UpdatedMaxFeeIncrease(_newLimit); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Deducts [_amount] from the job's available funds and transfers [_amount] of fee tokens to [_to]. * @param _to Address of the user/contract receiving the funds. * @param _jobID The job ID. * @param _amount Amount of funds to transfer. */ function _withdrawFunds(address _to, uint256 _jobID, uint256 _amount) internal { availableFunds[_jobID] = availableFunds[_jobID].sub(_amount); feeToken.safeTransfer(_to, _amount); emit WithdrewFunds(_jobID, _to, _amount); } /* ========== MODIFIERS ========== */ modifier onlyJobOwner(uint256 _jobID) { require(msg.sender == upkeeps[_jobID].owner, "KeeperRegistry: Only the job owner can call this function."); _; } modifier onlyKeeper(uint256 _jobID) { require(msg.sender == upkeeps[_jobID].keeper, "KeeperRegistry: Only the keeper contract can call this function."); _; } modifier onlyKeeperOwner(address _keeper) { require(msg.sender == keepers[_keeper].owner, "Keeper: Only the keeper owner can call this function."); _; } modifier onlyPayee(address _keeper) { require(msg.sender == keepers[_keeper].payee, "Keeper: Only the keeper's payee can call this function."); _; } /* ========== EVENTS ========== */ event AddedFunds(uint256 jobID, address from, uint256 amount); event WithdrewFunds(uint256 jobID, address to, uint256 amount); event UpdatedPayee(address keeper, address newPayee); event ClaimedFees(address keeper, address payee, uint256 amount); event CanceledJob(uint256 jobID); event ChargedFee(uint256 jobID, address payee, uint256 amount); event UpdatedKeeperFee(address keeper, uint256 newFee); event RegisteredKeeper(address keeper, address owner, address dedicatedCaller, address payee, uint256 fee); event CreatedJob(uint8 jobType, uint256 jobID, address owner, address keeper, address target, uint256 instanceID); event UpdatedDedicatedCaller(address keeper, address newCaller); event UpdatedMaxKeeperFee(uint256 newFee); event UpdatedMaxFeeIncrease(uint256 newLimit); }
Adds funds to the given job. Only the job's owner can call this function. _jobID The ID of the job. _amount Number of tokens to transfer./
function addFunds(uint256 _jobID, uint256 _amount) external override onlyJobOwner(_jobID) nonReentrant { availableFunds[_jobID] = availableFunds[_jobID].add(_amount); feeToken.safeTransferFrom(msg.sender, address(this), _amount); emit AddedFunds(_jobID, msg.sender, _amount); }
12,595,838
/** *Submitted for verification at Etherscan.io on 2021-09-03 */ // File: utils/Bytes.sol pragma solidity ^0.8.4; library Bytes { /** * @dev Converts a `uint256` to a `string`. * via OraclizeAPI - MIT licence * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol */ function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } bytes constant alphabet = "0123456789abcdef"; /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function substring( bytes memory strBytes, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { result = result * 10 + (val - 48); } } return result; } } // File: utils/Minting.sol library Minting { // Split the minting blob into token_id and blueprint portions // {token_id}:{blueprint} function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = Bytes.indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } } // File: IMintable.sol interface IMintable { function mintFor( address to, uint256 id, bytes calldata blueprint ) external; } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: Mintable.sol abstract contract Mintable is Ownable, IMintable { address public imx; mapping(uint256 => bytes) public blueprints; event AssetMinted(address to, uint256 id, bytes blueprint); constructor(address _owner, address _imx) { imx = _imx; require(_owner != address(0), "Owner must not be empty"); transferOwnership(_owner); } modifier onlyIMX() { require(msg.sender == imx, "Function can only be called by IMX"); _; } function mintFor( address user, uint256 quantity, bytes calldata mintingBlob ) external override onlyIMX { require(quantity == 1, "Mintable: invalid quantity"); (uint256 id, bytes memory blueprint) = Minting.split(mintingBlob); _mintFor(user, id, blueprint); blueprints[id] = blueprint; emit AssetMinted(user, id, blueprint); } function _mintFor( address to, uint256 id, bytes memory blueprint ) internal virtual; } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: Asset.sol contract Asset is ERC721URIStorage, Mintable { constructor( address _owner, string memory _name, string memory _symbol, address _imx ) ERC721(_name, _symbol) Mintable(_owner, _imx) {} function _mintFor( address user, uint256 id, bytes memory blueprint ) internal override { _safeMint(user, id); _setTokenURI(id, string(blueprint)); } }
See {IERC721Metadata-tokenURI}./ If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
function _beforeTokenTransfer( address from, address to, uint256 tokenId } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); }
10,704,307
./full_match/1/0x0d224228f0D024fe99681863BA325d87e8aFE30d/sources/contracts/ETHBridge.sol
Initiate a token transfer from BSC to ETH. txHash Transaction hash on BSC where the swap has been initiated. to The address on ETH to which the tokens are swapped. amount The amount of tokens swapped./ Calculate fee based on `feeRate` percentage of amount and to be at least `minFee` and at most `maxFee` fee = amount feeRate / 100 / 10000 Automatically check for amount > fee before transferring otherwise throws safemath error
function SwapIn( bytes32 txHash, address to, uint256 amount ) external onlyOwner returns (bool) { require(txHash != bytes32(0), "Bridge: invalid tx"); require(to != address(0), "Bridge: invalid addr"); require(txHashes[txHash] == false, "Bridge: dup tx"); txHashes[txHash] = true; uint256 fee = amount.mul(feeRate).div(1000000) >= minFee && amount.mul(feeRate).div(1000000) <= maxFee ? amount.mul(feeRate).div(1000000) : amount.mul(feeRate).div(1000000) < minFee ? minFee : maxFee; require( IERC20(tokenETH).transfer( to, amount.sub(fee, "Bridge: invalid amount") ), "Bridge: invalid transfer" ); accumulatedFee = accumulatedFee.add(fee); emit SwappedIn(txHash, to, amount.sub(fee), fee); return true; }
8,426,982
./full_match/4/0x3AcF5b5B023f1399786F35179B130D820Fbd177C/sources/contracts/1_Storage.sol
this method is responsible for randomizing and taking all fee, if takeFee is true.
) private { function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee if (!takeFee) { removeAllFee(); calculateProgressiveFee(amount, sender); } } else { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { }
808,681
./full_match/3/0xAEaB6350C6fa4985006bD94A99283626cc7F30b4/sources/BEP20.sol
returns address executing the method/
function _msgSender() internal view virtual returns (address payable) { return msg.sender; }
8,116,208
pragma solidity ^0.4.24; /** * @title SpinWinInterface */ interface SpinWinInterface { function refundPendingBets() external returns (bool); } /** * @title AdvertisingInterface */ interface AdvertisingInterface { function incrementBetCounter() external returns (bool); } contract SpinWinLibraryInterface { function calculateWinningReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) external pure returns (uint256); function calculateTokenReward(address settingAddress, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (uint256); function generateRandomNumber(address settingAddress, uint256 betBlockNumber, uint256 extraData, uint256 divisor) external constant returns (uint256); function calculateClearBetBlocksReward(address settingAddress, address lotteryAddress) external constant returns (uint256); function calculateLotteryContribution(address settingAddress, address lotteryAddress, uint256 betValue) external constant returns (uint256); function calculateExchangeTokenValue(address settingAddress, uint256 tokenAmount) external constant returns (uint256, uint256, uint256, uint256); } /** * @title LotteryInterface */ interface LotteryInterface { function claimReward(address playerAddress, uint256 tokenAmount) external returns (bool); function calculateLotteryContributionPercentage() external constant returns (uint256); function getNumLottery() external constant returns (uint256); function isActive() external constant returns (bool); function getCurrentTicketMultiplierHonor() external constant returns (uint256); function getCurrentLotteryTargetBalance() external constant returns (uint256, uint256); } /** * @title SettingInterface */ interface SettingInterface { function uintSettings(bytes32 name) external constant returns (uint256); function boolSettings(bytes32 name) external constant returns (bool); function isActive() external constant returns (bool); function canBet(uint256 rewardValue, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (bool); function isExchangeAllowed(address playerAddress, uint256 tokenAmount) external constant returns (bool); /******************************************/ /* SPINWIN ONLY METHODS */ /******************************************/ function spinwinSetUintSetting(bytes32 name, uint256 value) external; function spinwinIncrementUintSetting(bytes32 name) external; function spinwinSetBoolSetting(bytes32 name, bool value) external; function spinwinAddFunds(uint256 amount) external; function spinwinUpdateTokenToWeiExchangeRate() external; function spinwinRollDice(uint256 betValue) external; function spinwinUpdateWinMetric(uint256 playerProfit) external; function spinwinUpdateLoseMetric(uint256 betValue, uint256 tokenRewardValue) external; function spinwinUpdateLotteryContributionMetric(uint256 lotteryContribution) external; function spinwinUpdateExchangeMetric(uint256 exchangeAmount) external; /******************************************/ /* SPINLOTTERY ONLY METHODS */ /******************************************/ function spinlotterySetUintSetting(bytes32 name, uint256 value) external; function spinlotteryIncrementUintSetting(bytes32 name) external; function spinlotterySetBoolSetting(bytes32 name, bool value) external; function spinlotteryUpdateTokenToWeiExchangeRate() external; function spinlotterySetMinBankroll(uint256 _minBankroll) external returns (bool); } /** * @title TokenInterface */ interface TokenInterface { function getTotalSupply() external constant returns (uint256); function getBalanceOf(address account) external constant returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool success); function burn(uint256 _value) external returns (bool success); function burnFrom(address _from, uint256 _value) external returns (bool success); function mintTransfer(address _to, uint _value) external returns (bool); function burnAt(address _at, uint _value) external returns (bool); } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } contract developed { address public developer; /** * Constructor */ constructor() public { developer = msg.sender; } /** * @dev Checks only developer address is calling */ modifier onlyDeveloper { require(msg.sender == developer); _; } /** * @dev Allows developer to switch developer address * @param _developer The new developer address to be set */ function changeDeveloper(address _developer) public onlyDeveloper { developer = _developer; } /** * @dev Allows developer to withdraw ERC20 Token */ function withdrawToken(address tokenContractAddress) public onlyDeveloper { TokenERC20 _token = TokenERC20(tokenContractAddress); if (_token.balanceOf(this) > 0) { _token.transfer(developer, _token.balanceOf(this)); } } } /** * @title SpinWin */ contract SpinWin is developed, SpinWinInterface { using SafeMath for uint256; address public tokenAddress; address public settingAddress; address public lotteryAddress; TokenInterface internal _spintoken; SettingInterface internal _setting; LotteryInterface internal _lottery; SpinWinLibraryInterface internal _lib; AdvertisingInterface internal _advertising; /** * @dev Player variables */ struct Bet { address playerAddress; bytes32 betId; uint256 betValue; uint256 diceResult; uint256 playerNumber; uint256 houseEdge; uint256 rewardValue; uint256 tokenRewardValue; uint256 blockNumber; bool processed; } struct TokenExchange { address playerAddress; bytes32 exchangeId; bool processed; } mapping (uint256 => Bet) internal bets; mapping (bytes32 => uint256) internal betIdLookup; mapping (address => uint256) public playerPendingWithdrawals; mapping (address => uint256) public playerPendingTokenWithdrawals; mapping (address => address) public referees; mapping (bytes32 => TokenExchange) public tokenExchanges; mapping (address => uint256) public lotteryBlocksAmount; uint256 constant public TWO_DECIMALS = 100; uint256 constant public PERCENTAGE_DIVISOR = 10 ** 6; // 1000000 = 100% uint256 constant public CURRENCY_DIVISOR = 10**18; uint256 public totalPendingBets; /** * @dev Log when bet is placed */ event LogBet(bytes32 indexed betId, address indexed playerAddress, uint256 playerNumber, uint256 betValue, uint256 houseEdge, uint256 rewardValue, uint256 tokenRewardValue); /** * @dev Log when bet is cleared * * Status: * -2 = lose + failed mint and transfer * -1 = lose + failed send * 0 = lose * 1 = win * 2 = win + failed send * 3 = refund * 4 = refund + failed send * 5 = owner cancel + refund * 6 = owner cancel + refund + failed send */ event LogResult(bytes32 indexed betId, address indexed playerAddress, uint256 playerNumber, uint256 diceResult, uint256 betValue, uint256 houseEdge, uint256 rewardValue, uint256 tokenRewardValue, int256 status); /** * @dev Log when spinwin contributes some ETH to the lottery contract address */ event LogLotteryContribution(bytes32 indexed betId, address indexed playerAddress, uint256 weiValue); /** * @dev Log when spinwin rewards the referee of a bet or the person clears bet * rewardType * 1 = referral * 2 = clearBet */ event LogRewardLotteryBlocks(address indexed receiver, bytes32 indexed betId, uint256 lottoBlocksAmount, uint256 rewardType, uint256 status); /** * @dev Log when player clears bets */ event LogClearBets(address indexed playerAddress); /** * @dev Log when player claims the lottery blocks reward * * Status: * 0 = failed * 1 = success */ event LogClaimLotteryBlocks(address indexed playerAddress, uint256 numLottery, uint256 claimAmount, uint256 claimStatus); /** * @dev Log when player exchanges token to Wei * * Status: * 0 = failed send * 1 = success * 2 = failed destroy token */ event LogTokenExchange(bytes32 indexed exchangeId, address indexed playerAddress, uint256 tokenValue, uint256 tokenToWeiExchangeRate, uint256 weiValue, uint256 receivedWeiValue, uint256 remainderTokenValue, uint256 status); /** * @dev Log when player withdraws balance from failed transfer * * Status: * 0 = failed * 1 = success */ event LogPlayerWithdrawBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status); /** * @dev Log when player withdraw token balance from failed token transfer * * Status: * 0 = failed * 1 = success */ event LogPlayerWithdrawTokenBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status); /** * @dev Log when a bet ID is not found during clear bet */ event LogBetNotFound(bytes32 indexed betId); /** * @dev Log when developer cancel existing active bet */ event LogDeveloperCancelBet(bytes32 indexed betId, address indexed playerAddress); /** * Constructor * @param _tokenAddress SpinToken contract address * @param _settingAddress GameSetting contract address * @param _libraryAddress SpinWinLibrary contract address */ constructor(address _tokenAddress, address _settingAddress, address _libraryAddress) public { tokenAddress = _tokenAddress; settingAddress = _settingAddress; _spintoken = TokenInterface(_tokenAddress); _setting = SettingInterface(_settingAddress); _lib = SpinWinLibraryInterface(_libraryAddress); } /** * @dev Checks if contract is active */ modifier isActive { require(_setting.isActive() == true); _; } /** * @dev Checks whether a bet is allowed, and player profit, bet value, house edge and player number are within range */ modifier canBet(uint256 _betValue, uint256 _playerNumber, uint256 _houseEdge) { require(_setting.canBet(_lib.calculateWinningReward(_betValue, _playerNumber, _houseEdge), _betValue, _playerNumber, _houseEdge) == true); _; } /** * @dev Checks if bet exist */ modifier betExist(bytes32 betId, address playerAddress) { require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId && bets[betIdLookup[betId]].playerAddress == playerAddress); _; } /** * @dev Checks if token exchange is allowed */ modifier isExchangeAllowed(address playerAddress, uint256 tokenAmount) { require(_setting.isExchangeAllowed(playerAddress, tokenAmount) == true); _; } /******************************************/ /* DEVELOPER ONLY METHODS */ /******************************************/ /** * @dev Allows developer to set lottery contract address * @param _lotteryAddress The new lottery contract address to be set */ function devSetLotteryAddress(address _lotteryAddress) public onlyDeveloper { require (_lotteryAddress != address(0)); lotteryAddress = _lotteryAddress; _lottery = LotteryInterface(_lotteryAddress); } /** * @dev Allows developer to set advertising contract address * @param _advertisingAddress The new advertising contract address to be set */ function devSetAdvertisingAddress(address _advertisingAddress) public onlyDeveloper { require (_advertisingAddress != address(0)); _advertising = AdvertisingInterface(_advertisingAddress); } /** * @dev Allows developer to get bet internal ID based on public betId * @param betId The public betId * @return The bet internal ID */ function devGetBetInternalId(bytes32 betId) public onlyDeveloper constant returns (uint256) { return (betIdLookup[betId]); } /** * @dev Allows developer to get bet info based on `betInternalId` * @param betInternalId The bet internal ID to be queried * @return The bet information */ function devGetBet(uint256 betInternalId) public onlyDeveloper constant returns (address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool) { Bet memory _bet = bets[betInternalId]; return (_bet.playerAddress, _bet.betValue, _bet.diceResult, _bet.playerNumber, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue, _bet.blockNumber, _bet.processed); } /** * @dev Allows developer to manually refund existing active bet. * @param betId The ID of the bet to be cancelled * @return Return true if success */ function devRefundBet(bytes32 betId) public onlyDeveloper returns (bool) { require (betIdLookup[betId] > 0); Bet storage _bet = bets[betIdLookup[betId]]; require(_bet.processed == false); _bet.processed = true; uint256 betValue = _bet.betValue; _bet.betValue = 0; _bet.rewardValue = 0; _bet.tokenRewardValue = 0; _refundPlayer(betIdLookup[betId], betValue); return true; } /** * @dev Add funds to the contract */ function () public payable isActive { _setting.spinwinAddFunds(msg.value); } /******************************************/ /* SETTING METHODS */ /******************************************/ /** * @dev Triggered during escape hatch. Go through each pending bets * and move the bet value to playerPendingWithdrawals so that player * can withdraw later */ function refundPendingBets() public returns (bool) { require (msg.sender == settingAddress); uint256 totalBets = _setting.uintSettings('totalBets'); if (totalBets > 0) { for (uint256 i = 1; i <= totalBets; i++) { Bet storage _bet = bets[i]; if (_bet.processed == false) { uint256 _betValue = _bet.betValue; _bet.processed = true; _bet.betValue = 0; playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(_betValue); emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, 0, _betValue, _bet.houseEdge, 0, 0, 4); } } } return true; } /******************************************/ /* PUBLIC METHODS */ /******************************************/ /** * @dev Player places a bet. If it has a `referrerAddress`, we want to give reward to the referrer accordingly. * @dev If there is a bet that needs to be cleared, we will do it here too. * @param playerNumber The number that the player chose * @param houseEdge The house edge percentage that the player chose * @param clearBetId The bet ID to be cleared * @param referreeAddress The referree address if exist * @return Return true if success */ function rollDice(uint256 playerNumber, uint256 houseEdge, bytes32 clearBetId, address referreeAddress) public payable canBet(msg.value, playerNumber, houseEdge) returns (bool) { uint256 betInternalId = _storeBet(msg.value, msg.sender, playerNumber, houseEdge); // Check if we need to clear a pending bet if (clearBetId != '') { _clearSingleBet(msg.sender, clearBetId, _setting.uintSettings('blockSecurityCount')); } // Check if we need to reward the referree _rewardReferree(referreeAddress, betInternalId); _advertising.incrementBetCounter(); return true; } /** * @dev Player can clear multiple bets * @param betIds The bet ids to be cleared */ function clearBets(bytes32[] betIds) public isActive { require (betIds.length > 0 && betIds.length <= _setting.uintSettings('maxNumClearBets')); bool canClear = false; uint256 blockSecurityCount = _setting.uintSettings('blockSecurityCount'); for (uint256 i = 0; i < betIds.length; i++) { Bet memory _bet = bets[betIdLookup[betIds[i]]]; if (_bet.processed == false && _setting.uintSettings('contractBalance') >= _bet.rewardValue && (block.number.sub(_bet.blockNumber)) >= blockSecurityCount) { canClear = true; break; } } require(canClear == true); // Loop through each bets and clear it if possible for (i = 0; i < betIds.length; i++) { _clearSingleBet(msg.sender, betIds[i], blockSecurityCount); } emit LogClearBets(msg.sender); } /** * @dev Allow player to claim lottery blocks reward * and spend it on lottery blocks */ function claimLotteryBlocks() public isActive { require (_lottery.isActive() == true); require (lotteryBlocksAmount[msg.sender] > 0); uint256 claimAmount = lotteryBlocksAmount[msg.sender]; lotteryBlocksAmount[msg.sender] = 0; uint256 claimStatus = 1; if (!_lottery.claimReward(msg.sender, claimAmount)) { claimStatus = 0; lotteryBlocksAmount[msg.sender] = claimAmount; } emit LogClaimLotteryBlocks(msg.sender, _lottery.getNumLottery(), claimAmount, claimStatus); } /** * @dev Player exchanges token for Wei * @param tokenAmount The amount of token to be exchanged * @return Return true if success */ function exchangeToken(uint256 tokenAmount) public isExchangeAllowed(msg.sender, tokenAmount) { (uint256 weiValue, uint256 sendWei, uint256 tokenRemainder, uint256 burnToken) = _lib.calculateExchangeTokenValue(settingAddress, tokenAmount); _setting.spinwinIncrementUintSetting('totalTokenExchanges'); // Generate exchangeId bytes32 _exchangeId = keccak256(abi.encodePacked(this, msg.sender, _setting.uintSettings('totalTokenExchanges'))); TokenExchange storage _tokenExchange = tokenExchanges[_exchangeId]; // Make sure we don't process the exchange bet twice require (_tokenExchange.processed == false); // Update exchange metric _setting.spinwinUpdateExchangeMetric(sendWei); /* * Store the info about this exchange */ _tokenExchange.playerAddress = msg.sender; _tokenExchange.exchangeId = _exchangeId; _tokenExchange.processed = true; /* * Burn token at this address */ if (!_spintoken.burnAt(_tokenExchange.playerAddress, burnToken)) { uint256 exchangeStatus = 2; // status = failed destroy token } else { if (!_tokenExchange.playerAddress.send(sendWei)) { exchangeStatus = 0; // status = failed send // If send failed, let player withdraw via playerWithdrawPendingTransactions playerPendingWithdrawals[_tokenExchange.playerAddress] = playerPendingWithdrawals[_tokenExchange.playerAddress].add(sendWei); } else { exchangeStatus = 1; // status = success } } // Update the token to wei exchange rate _setting.spinwinUpdateTokenToWeiExchangeRate(); emit LogTokenExchange(_tokenExchange.exchangeId, _tokenExchange.playerAddress, tokenAmount, _setting.uintSettings('tokenToWeiExchangeRateHonor'), weiValue, sendWei, tokenRemainder, exchangeStatus); } /** * @dev Calculate winning ETH when player wins * @param betValue The amount of ETH for this bet * @param playerNumber The number that player chose * @param houseEdge The house edge for this bet * @return The amount of ETH to be sent to player if he/she wins */ function calculateWinningReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) public view returns (uint256) { return _lib.calculateWinningReward(betValue, playerNumber, houseEdge); } /** * @dev Calculates token reward amount when player loses * @param betValue The amount of ETH for this bet * @param playerNumber The number that player chose * @param houseEdge The house edge for this bet * @return The amount of token to be sent to player if he/she loses */ function calculateTokenReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) public constant returns (uint256) { return _lib.calculateTokenReward(settingAddress, betValue, playerNumber, houseEdge); } /** * @dev Player withdraws balance in case of a failed refund or failed win send */ function playerWithdrawPendingTransactions() public { require(playerPendingWithdrawals[msg.sender] > 0); uint256 withdrawAmount = playerPendingWithdrawals[msg.sender]; playerPendingWithdrawals[msg.sender] = 0; // External call to untrusted contract uint256 status = 1; // status = success if (!msg.sender.send(withdrawAmount)) { status = 0; // status = failed /* * If send failed, revert playerPendingWithdrawals[msg.sender] = 0 * so that player can try to withdraw again later */ playerPendingWithdrawals[msg.sender] = withdrawAmount; } emit LogPlayerWithdrawBalance(msg.sender, withdrawAmount, status); } /** * @dev Players withdraws SPIN token balance in case of a failed token transfer */ function playerWithdrawPendingTokenTransactions() public { require(playerPendingTokenWithdrawals[msg.sender] > 0); uint256 withdrawAmount = playerPendingTokenWithdrawals[msg.sender]; playerPendingTokenWithdrawals[msg.sender] = 0; // Mint and transfer token to msg.sender uint256 status = 1; // status = success if (!_spintoken.mintTransfer(msg.sender, withdrawAmount)) { status = 0; // status = failed /* * If transfer failed, revert playerPendingTokenWithdrawals[msg.sender] = 0 * so that player can try to withdraw again later */ playerPendingTokenWithdrawals[msg.sender] = withdrawAmount; } emit LogPlayerWithdrawTokenBalance(msg.sender, withdrawAmount, status); } /** * @dev Player gets bet information based on betId * @return The bet information */ function playerGetBet(bytes32 betId) public constant returns (uint256, uint256, uint256, uint256, uint256, uint256, bool) { require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId); Bet memory _bet = bets[betIdLookup[betId]]; return (_bet.betValue, _bet.diceResult, _bet.playerNumber, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue, _bet.processed); } /** * @dev Player gets pending bet IDs * @return The pending bet IDs */ function playerGetPendingBetIds() public constant returns (bytes32[]) { bytes32[] memory pendingBetIds = new bytes32[](totalPendingBets); if (totalPendingBets > 0) { uint256 counter = 0; for (uint256 i = 1; i <= _setting.uintSettings('totalBets'); i++) { Bet memory _bet = bets[i]; if (_bet.processed == false) { pendingBetIds[counter] = _bet.betId; counter++; } if (counter == totalPendingBets) { break; } } } return pendingBetIds; } /** * @dev Player gets pending bet information based on betId * @return The bet information */ function playerGetPendingBet(bytes32 betId) public constant returns (address, uint256, uint256, uint256, uint256) { require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId); Bet memory _bet = bets[betIdLookup[betId]]; return (_bet.playerAddress, _bet.playerNumber, _bet.betValue, _bet.houseEdge, _bet.blockNumber); } /** * @dev Calculates lottery block rewards when player clears a bet * @return The amount of lottery blocks to be rewarded when player clears bet */ function calculateClearBetBlocksReward() public constant returns (uint256) { return _lib.calculateClearBetBlocksReward(settingAddress, lotteryAddress); } /******************************************/ /* INTERNAL METHODS */ /******************************************/ /** * @dev Stores bet information. * @param betValue The value of the bet * @param playerAddress The player address * @param playerNumber The number that player chose * @param houseEdge The house edge for this bet * @return The internal bet ID of this bet */ function _storeBet (uint256 betValue, address playerAddress, uint256 playerNumber, uint256 houseEdge) internal returns (uint256) { // Update the setting metric _setting.spinwinRollDice(betValue); uint256 betInternalId = _setting.uintSettings('totalBets'); // Generate betId bytes32 betId = keccak256(abi.encodePacked(this, playerAddress, betInternalId)); Bet storage _bet = bets[betInternalId]; // Make sure we don't process the same bet twice require (_bet.processed == false); // Store the info about this bet betIdLookup[betId] = betInternalId; _bet.playerAddress = playerAddress; _bet.betId = betId; _bet.betValue = betValue; _bet.playerNumber = playerNumber; _bet.houseEdge = houseEdge; // Safely calculate winning reward _bet.rewardValue = calculateWinningReward(betValue, playerNumber, houseEdge); // Safely calculate token payout _bet.tokenRewardValue = calculateTokenReward(betValue, playerNumber, houseEdge); _bet.blockNumber = block.number; // Update the pendingBets counter totalPendingBets++; emit LogBet(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.betValue, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue); return betInternalId; } /** * @dev Internal function to clear single bet * @param playerAddress The player who clears this bet * @param betId The bet ID to be cleared * @param blockSecurityCount The block security count to be checked * @return true if success, false otherwise */ function _clearSingleBet(address playerAddress, bytes32 betId, uint256 blockSecurityCount) internal returns (bool) { if (betIdLookup[betId] > 0) { Bet memory _bet = bets[betIdLookup[betId]]; /* Check if we can clear this bet * - Make sure we don't process the same bet twice * - Check if contract can payout on win * - block number difference >= blockSecurityCount */ if (_bet.processed == false && _setting.uintSettings('contractBalance') >= _bet.rewardValue && (block.number.sub(_bet.blockNumber)) >= blockSecurityCount) { _processBet(playerAddress, betIdLookup[betId], true); } else { emit LogRewardLotteryBlocks(playerAddress, _bet.betId, 0, 2, 0); } return true; } else { emit LogBetNotFound(betId); return false; } } /** * @dev Internal function to process existing bet. * If no dice result, then we initiate a refund. * If player wins (dice result < player number), we send player winning ETH. * If player loses (dice result >= player number), we send player some SPIN token. * If player loses and bankroll goal is reached, spinwin will contribute some ETH to lottery contract address. * * @param triggerAddress The player who clears this bet * @param betInternalId The bet internal ID to be processed * @param isClearMultiple Whether or not this is part of clear multiple bets transaction * @return Return true if success */ function _processBet(address triggerAddress, uint256 betInternalId, bool isClearMultiple) internal returns (bool) { Bet storage _bet = bets[betInternalId]; uint256 _betValue = _bet.betValue; uint256 _rewardValue = _bet.rewardValue; uint256 _tokenRewardValue = _bet.tokenRewardValue; // Prevent re-entrancy _bet.processed = true; _bet.betValue = 0; _bet.rewardValue = 0; _bet.tokenRewardValue = 0; // Generate the result _bet.diceResult = _lib.generateRandomNumber(settingAddress, _bet.blockNumber, _setting.uintSettings('totalBets').add(_setting.uintSettings('totalWeiWagered')), 100); if (_bet.diceResult == 0) { /* * Invalid random number. Refund the player */ _refundPlayer(betInternalId, _betValue); } else if (_bet.diceResult < _bet.playerNumber) { /* * Player wins. Send the player the winning eth amount */ _payWinner(betInternalId, _betValue, _rewardValue); } else { /* * Player loses. Send the player 1 wei and the spintoken amount */ _payLoser(betInternalId, _betValue, _tokenRewardValue); } // Update the pendingBets counter totalPendingBets--; // Update the token to wei exchange rate _setting.spinwinUpdateTokenToWeiExchangeRate(); // Calculate the lottery blocks reward for this transaction uint256 lotteryBlocksReward = calculateClearBetBlocksReward(); // If this is a single clear (from placing bet), we want to multiply this with clearSingleBetMultiplier if (isClearMultiple == false) { uint256 multiplier = _setting.uintSettings('clearSingleBetMultiplier'); } else { multiplier = _setting.uintSettings('clearMultipleBetsMultiplier'); } lotteryBlocksReward = (lotteryBlocksReward.mul(multiplier)).div(TWO_DECIMALS); lotteryBlocksAmount[triggerAddress] = lotteryBlocksAmount[triggerAddress].add(lotteryBlocksReward); emit LogRewardLotteryBlocks(triggerAddress, _bet.betId, lotteryBlocksReward, 2, 1); return true; } /** * @dev Refund the player when we are unable to determine the dice result * @param betInternalId The bet internal ID * @param refundAmount The amount to be refunded */ function _refundPlayer(uint256 betInternalId, uint256 refundAmount) internal { Bet memory _bet = bets[betInternalId]; /* * Send refund - external call to an untrusted contract * If send fails, map refund value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ int256 betStatus = 3; // status = refund if (!_bet.playerAddress.send(refundAmount)) { betStatus = 4; // status = refund + failed send // If send failed, let player withdraw via playerWithdrawPendingTransactions playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(refundAmount); } emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, refundAmount, _bet.houseEdge, 0, 0, betStatus); } /** * @dev Pays the player the winning eth amount * @param betInternalId The bet internal ID * @param betValue The original wager * @param playerProfit The player profit */ function _payWinner(uint256 betInternalId, uint256 betValue, uint256 playerProfit) internal { Bet memory _bet = bets[betInternalId]; // Update setting's contract balance and total wei won _setting.spinwinUpdateWinMetric(playerProfit); // Safely calculate payout via profit plus original wager playerProfit = playerProfit.add(betValue); /* * Send win - external call to an untrusted contract * If send fails, map reward value to playerPendingWithdrawals[address] * for withdrawal later via playerWithdrawPendingTransactions */ int256 betStatus = 1; // status = win if (!_bet.playerAddress.send(playerProfit)) { betStatus = 2; // status = win + failed send // If send failed, let player withdraw via playerWithdrawPendingTransactions playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(playerProfit); } emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, betValue, _bet.houseEdge, playerProfit, 0, betStatus); } /** * @dev Pays the player 1 wei and the spintoken amount * @param betInternalId The bet internal ID * @param betValue The original wager * @param tokenRewardValue The token reward for this bet */ function _payLoser(uint256 betInternalId, uint256 betValue, uint256 tokenRewardValue) internal { Bet memory _bet = bets[betInternalId]; /* * Update the game setting metric when player loses */ _setting.spinwinUpdateLoseMetric(betValue, tokenRewardValue); int256 betStatus; // status = lose /* * Send 1 Wei to losing bet - external call to an untrusted contract */ if (!_bet.playerAddress.send(1)) { betStatus = -1; // status = lose + failed send // If send failed, let player withdraw via playerWithdrawPendingTransactions playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(1); } /* * Mint and transfer token reward to this player */ if (tokenRewardValue > 0) { if (!_spintoken.mintTransfer(_bet.playerAddress, tokenRewardValue)) { betStatus = -2; // status = lose + failed mint and transfer // If transfer token failed, let player withdraw via playerWithdrawPendingTokenTransactions playerPendingTokenWithdrawals[_bet.playerAddress] = playerPendingTokenWithdrawals[_bet.playerAddress].add(tokenRewardValue); } } emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, betValue, _bet.houseEdge, 1, tokenRewardValue, betStatus); _sendLotteryContribution(betInternalId, betValue); } /** * @dev Contribute the house win to lottery address * @param betInternalId The bet internal ID * @param betValue The original wager * @return Return true if success */ function _sendLotteryContribution(uint256 betInternalId, uint256 betValue) internal returns (bool) { /* * If contractBalance >= minBankroll, contribute the a percentage of the winning to lottery */ uint256 contractBalance = _setting.uintSettings('contractBalance'); if (contractBalance >= _setting.uintSettings('minBankroll')) { Bet memory _bet = bets[betInternalId]; uint256 lotteryContribution = _lib.calculateLotteryContribution(settingAddress, lotteryAddress, betValue); if (lotteryContribution > 0 && contractBalance >= lotteryContribution) { // Safely adjust contractBalance _setting.spinwinUpdateLotteryContributionMetric(lotteryContribution); emit LogLotteryContribution(_bet.betId, _bet.playerAddress, lotteryContribution); // Contribute to the lottery if (!lotteryAddress.call.gas(_setting.uintSettings('gasForLottery')).value(lotteryContribution)()) { return false; } } } return true; } /** * @dev Reward the referree if necessary. * @param referreeAddress The address of the referree * @param betInternalId The internal bet ID */ function _rewardReferree(address referreeAddress, uint256 betInternalId) internal { Bet memory _bet = bets[betInternalId]; // If the player already has a referee, use that address if (referees[_bet.playerAddress] != address(0)) { referreeAddress = referees[_bet.playerAddress]; } if (referreeAddress != address(0) && referreeAddress != _bet.playerAddress) { referees[_bet.playerAddress] = referreeAddress; uint256 _tokenForLotto = _bet.tokenRewardValue.mul(_setting.uintSettings('referralPercent')).div(PERCENTAGE_DIVISOR); lotteryBlocksAmount[referreeAddress] = lotteryBlocksAmount[referreeAddress].add(_tokenForLotto); emit LogRewardLotteryBlocks(referreeAddress, _bet.betId, _tokenForLotto, 1, 1); } } }
Players withdraws SPIN token balance in case of a failed token transfer/ Mint and transfer token to msg.sender
function playerWithdrawPendingTokenTransactions() public { require(playerPendingTokenWithdrawals[msg.sender] > 0); uint256 withdrawAmount = playerPendingTokenWithdrawals[msg.sender]; playerPendingTokenWithdrawals[msg.sender] = 0; if (!_spintoken.mintTransfer(msg.sender, withdrawAmount)) { playerPendingTokenWithdrawals[msg.sender] = withdrawAmount; emit LogPlayerWithdrawTokenBalance(msg.sender, withdrawAmount, status); }
6,478,584
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import "./libraries/Data.sol"; import "./libraries/Fork.sol"; import "./libraries/ForkDeposit.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IDestinationContract.sol"; import "./MessageDock/CrossDomainHelper.sol"; import "./PoolTokenApprovable.sol"; import "hardhat/console.sol"; contract NewDestination is IDestinationContract, CrossDomainHelper, Ownable, PoolTokenApprovable { using SafeERC20 for IERC20; using HashOnions for mapping(uint256 => HashOnions.Info); using Fork for mapping(bytes32 => Fork.Info); using ForkDeposit for mapping(bytes32 => ForkDeposit.Info); address private tokenAddress; mapping(bytes32 => Fork.Info) public hashOnionForks; mapping(uint256 => mapping(bytes32 => bool)) private isRespondOnions; mapping(uint256 => HashOnions.Info) private hashOnions; mapping(bytes32 => address) private onionsAddress; // !!! Conflict with using zk scheme, new scheme needs to be considered when using zk mapping(address => uint256) private source_chainIds; mapping(address => bool) private _committerDeposits; // Submitter's bond record mapping(bytes32 => ForkDeposit.Info) private hashOnionForkDeposits; uint256 public immutable ONEFORK_MAX_LENGTH = 5; // !!! The final value is 50 , the higher the value, the longer the wait time and the less storage consumption uint256 public immutable DEPOSIT_AMOUNT = 1 * 10**18; // !!! The final value is 2 * 10**17 /* 1. every LP need deposit `DEPOSIT_AMOUNT` ETH, DEPOSIT_AMOUNT = OnebondGaslimit * max_fork.length * Average_gasPrice 2. when LP call zfork()、mfork()、claim(). lock deposit, and unlock the preHashOnions LP's deposit. 3. When bonder is settling `middle fork`, will get `DEPOSIT_AMOUNT` ETH back from destContract. 4. LP's deposit can only be withdrawn if they are unlocked. 5. No one wants to pay for someone else's mistakes, so the perpetrator's deposit will never be unlocked */ constructor(address _tokenAddress, address _dockAddr) CrossDomainHelper(_dockAddr) { tokenAddress = _tokenAddress; } function _onlyApprovedSources(address _sourceSender, uint256 _sourChainId) internal view override { require(_sourChainId != 0, "ZERO_CHAINID"); require(source_chainIds[_sourceSender] == _sourChainId, "NOTAPPROVE"); } /* * call from source * TODO it is not already ok */ function bondSourceHashOnion(uint256 chainId, bytes32 hashOnion) external sourceSafe { HashOnions.Info memory info = hashOnions[chainId]; if (info.onWorkHashOnion == "" || info.onWorkHashOnion == hashOnion) { hashOnions[chainId].onWorkHashOnion = hashOnion; } hashOnions[chainId].sourceHashOnion = hashOnion; } /** * Add domain. Init hashOnionForks, bind source & chainId */ function addDomain(uint256 chainId, address source) external onlyOwner { hashOnionForks.initialize(chainId, ONEFORK_MAX_LENGTH); source_chainIds[source] = chainId; } // TODO need deposit ETH function becomeCommiter() external { _committerDeposits[msg.sender] = true; } function getHashOnionFork( uint256 chainId, bytes32 hashOnion, uint16 index ) external view returns (Fork.Info memory) { bytes32 forkKey = Fork.generateForkKey(chainId, hashOnion, index); return hashOnionForks.getForkEnsure(forkKey); } function getHashOnionInfo(uint256 chainId) external view returns (HashOnions.Info memory) { return hashOnions[chainId]; } /* A. Ensure that a single correct fork link is present: There are three behaviors of commiters related to fork: 1. Create a 0-bit fork 2. Create a non-zero fork 3. Add OnionHead to any Fork The rules are as follows: 1. Accept any submission, zero-bit Fork needs to pass in PreForkkey 2. Fork starting with non-zero bits, length == ONEFORK_MAX_LENGTH - index (value range 1-49) B. Ensure that only the only correct fork link will be settled: 1. onWorkHashOnion's index % ONEFORK_MAX_LENGTH == ONEFORK_MAX_LENGTH 2. When bonding, the bond is the bond from the back to the front. If the fork being bonded is a non-zero fork, you need to provide preForkKey, onions1, onions2, and the parameters must meet the following conditions: 2.1 f(onions) == preFork.onionHead 2.2 onions[0] != fork.key //If there is an equal situation, then give the allAmount of the fork to onions[0].address . The bonder gets a deposit to compensate the gas fee. 2.3 fork.onionHead == onWorkHashOnion C. Guarantee that bad commits will be penalized: 1. CommiterA deposits the deposit, initiates a commit or fork, and the deposit is locked 2. The margin can only be unlocked by the addition of another Committer */ // if index % ONEFORK_MAX_LENGTH == 0 function zFork( uint256 chainId, bytes32 workForkKey, address dest, uint256 amount, uint256 fee, bool _isRespond ) external override { (Fork.Info memory workFork, Fork.Info memory newFork) = hashOnionForks .createZFork(chainId, workForkKey, dest, amount, fee); if (_committerDeposits[msg.sender] == false) { // If same commiter, don't need deposit require(msg.sender == workFork.lastCommiterAddress, "a2"); } // Determine whether the maker only submits or submits and responds if (_isRespond) { IERC20(tokenAddress).safeTransferFrom(msg.sender, dest, amount); } else { // !!! Whether to add the identification position of the index isRespondOnions[chainId][newFork.onionHead] = true; } // Locks the new committer's bond, unlocks the previous committer's bond state if (workFork.lastCommiterAddress != msg.sender) { _committerDeposits[workFork.lastCommiterAddress] = true; _committerDeposits[msg.sender] = false; } emit newClaim(dest, amount, fee, 0, newFork.onionHead); } // just deppend function claim( uint256 chainId, bytes32 workForkKey, uint256 _workIndex, Data.TransferData[] calldata _transferDatas, bool[] calldata _isResponds ) external override { // incoming data length is correct require(_transferDatas.length > 0, "a1"); Fork.Info memory workFork = hashOnionForks.getForkEnsure(workForkKey); // Determine the eligibility of the submitter if (_committerDeposits[msg.sender] == false) { require(msg.sender == workFork.lastCommiterAddress, "a3"); } // Determine whether someone has submitted it before. If it has been submitted by the predecessor, tx.origin thinks that the submission is incorrect and can be forked and resubmitted through forkFromInput // !!! Avoid duplicate submissions require(_workIndex == workFork.length, "b2"); // Judge _transferDatas not to exceed the limit require(_workIndex + _transferDatas.length <= ONEFORK_MAX_LENGTH, "a2"); bytes32 onionHead = workFork.onionHead; bytes32 destOnionHead = workFork.destOnionHead; uint256 allAmount = 0; // just append for (uint256 i; i < _transferDatas.length; i++) { onionHead = Fork.generateOnionHead(onionHead, _transferDatas[i]); if (_isResponds[i]) { IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferDatas[i].destination, _transferDatas[i].amount ); } else { // TODO need change to transferData hash isRespondOnions[chainId][onionHead] = true; } destOnionHead = Fork.generateDestOnionHead( destOnionHead, onionHead, msg.sender ); allAmount += _transferDatas[i].amount + _transferDatas[i].fee; emit newClaim( _transferDatas[i].destination, _transferDatas[i].amount, _transferDatas[i].fee, _workIndex + i, onionHead ); } // change deposit , deposit token is ETH , need a function to deposit and with draw if (workFork.lastCommiterAddress != msg.sender) { _committerDeposits[workFork.lastCommiterAddress] = true; _committerDeposits[msg.sender] = false; } workFork = Fork.Info( 0, onionHead, destOnionHead, allAmount + workFork.allAmount, _workIndex + _transferDatas.length, msg.sender, workFork.needBond, 0 ); // storage hashOnionForks.update(workForkKey, workFork); } // if source index % ONEFORK_MAX_LENGTH != 0 function mFork( uint256 chainId, bytes32 _lastOnionHead, bytes32 _lastDestOnionHead, uint16 _index, Data.TransferData calldata _transferData, bool _isRespond ) external override { // Determine whether tx.origin is eligible to submit require(_committerDeposits[msg.sender] == true, "a3"); Fork.Info memory newFork = hashOnionForks.createMFork( chainId, _lastOnionHead, _lastDestOnionHead, _index, _transferData ); // Determine whether the maker only submits or submits and also responds, so as to avoid the large amount of unresponsiveness of the maker and block subsequent commints if (_isRespond) { IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferData.destination, _transferData.amount ); } else { isRespondOnions[chainId][newFork.onionHead] = true; } // Freeze Margin _committerDeposits[msg.sender] = false; } // clearing zfork function zbond( uint256 chainId, bytes32 prevForkKey, bytes32 forkKey, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) external override { // incoming data length is correct require(_transferDatas.length > 0, "a1"); require(_committers.length == _transferDatas.length, "a2"); Fork.Info memory workFork = hashOnionForks.getForkEnsure(forkKey); bool isEarlyBonded = Fork.isEarlyBonded( workFork.verifyStatus, workFork.needBond ); // When verified and not needBond, throw error require(workFork.verifyStatus == 0 || workFork.needBond, "a3"); // Determine whether the onion of the fork has been recognized require( workFork.onionHead == hashOnions[chainId].onWorkHashOnion, "a4" ); Fork.Info memory prevWorkFork = hashOnionForks.getForkEnsure( prevForkKey ); (bytes32[] memory onionHeads, bytes32 destOnionHead) = Fork .getVerifyOnions(prevWorkFork, _transferDatas, _committers); // Assert that the replay result is equal to the stored value of the fork, which means that the incoming _transferdatas are valid require(destOnionHead == workFork.destOnionHead, "a5"); // storage workFork workFork.verifyStatus = 1; workFork.needBond = false; hashOnionForks.update(forkKey, workFork); // If the prefork also needs to be settled, push the onWorkHashOnion forward a fork _setOnWorkHashOnion(chainId, prevWorkFork); // When earlyBonded, donnot transfer to committers if (isEarlyBonded) { return; } _settlement( chainId, workFork.allAmount, onionHeads, _transferDatas, _committers ); // When has forkDeposit, send token to fork's endorser ForkDeposit.Info memory forkDeposit = hashOnionForkDeposits[forkKey]; if (forkDeposit.endorser != address(0)) { IERC20(tokenAddress).safeTransfer( forkDeposit.endorser, forkDeposit.amount // TODO Add reward and denyer amount ); } // !!! Reward bonder } function buyOneOnion( uint256 chainId, bytes32 preHashOnion, Data.TransferData calldata _transferData ) external override { bytes32 key = keccak256( abi.encode(preHashOnion, keccak256(abi.encode(_transferData))) ); require(isRespondOnions[chainId][key], "a1"); require(onionsAddress[key] == address(0), "a2"); IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferData.destination, _transferData.amount ); onionsAddress[key] = msg.sender; } // Depostit one fork function depositWithOneFork(bytes32 forkKey) public { Fork.Info memory fork = hashOnionForks.getForkEnsure(forkKey); require(fork.workIndex == 0, "Only zFork"); require(fork.length == ONEFORK_MAX_LENGTH, "Insufficient length"); uint256 amount = fork.allAmount / ForkDeposit.DEPOSIT_SCALE; IERC20(tokenAddress).safeTransferFrom( msg.sender, address(this), amount ); hashOnionForkDeposits.deposit(forkKey, amount, false); // Event } // Deposit mForks function depositMForks( uint256 chainId, bytes32 _prevForkKey, Data.MForkData[] calldata _mForkDatas, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) external { require( _transferDatas.length == ONEFORK_MAX_LENGTH, "Insufficient length" ); Fork.Info memory prevFork = hashOnionForks.getForkEnsure(_prevForkKey); // Create unitedForkKey bytes32 hashOnion = Fork.generateOnionHead( prevFork.onionHead, _transferDatas[0] ); bytes32 unitedForkKey = Fork.generateForkKey( chainId, hashOnion, ForkDeposit.MFORK_UNITED_WORK_INDEX ); uint256 allAmount = 0; uint16 fi = 0; for (uint16 i = 0; i < _transferDatas.length; i++) { Data.TransferData memory transferData = _transferDatas[i]; allAmount += transferData.amount + transferData.fee; if (fi < _mForkDatas.length && _mForkDatas[fi].forkIndex == i) { // Ensure fork exist require( hashOnionForks.isExist(_mForkDatas[fi].forkKey), "Fork is null" ); fi += 1; } } Fork.Info memory unitedFork; unitedFork.allAmount = allAmount; unitedFork.length = ONEFORK_MAX_LENGTH; unitedFork.needBond = true; // Set onionHead, destOnionHead and lastCommiterAddress bytes32 onionHead = prevFork.onionHead; bytes32 destOnionHead = prevFork.destOnionHead; for (uint256 i; i < _transferDatas.length; i++) { onionHead = Fork.generateOnionHead(onionHead, _transferDatas[i]); destOnionHead = Fork.generateDestOnionHead( destOnionHead, onionHead, _committers[i] ); unitedFork.lastCommiterAddress = _committers[i]; } unitedFork.onionHead = onionHead; unitedFork.destOnionHead = destOnionHead; hashOnionForks.update(unitedForkKey, unitedFork); depositWithOneFork(unitedForkKey); } // Deny depostit one fork function denyDepositOneFork(bytes32 forkKey) external { ForkDeposit.Info memory forkDeposit = hashOnionForkDeposits .getDepositEnsure(forkKey); IERC20(tokenAddress).safeTransferFrom( msg.sender, address(this), forkDeposit.amount ); hashOnionForkDeposits.deposit(forkKey, forkDeposit.amount, true); } function earlyBond( uint256 chainId, bytes32 prevForkKey, bytes32 forkKey, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) external { ForkDeposit.Info memory forkDeposit = hashOnionForkDeposits .getDepositEnsure(forkKey); require(forkDeposit.denyer == address(0), "Dispute"); require( ForkDeposit.isBlockNumberArrive(forkDeposit.prevBlockNumber), "No arrive" ); Fork.Info memory prevFork = hashOnionForks.getForkEnsure(prevForkKey); Fork.Info memory fork = hashOnionForks.getForkEnsure(forkKey); require(fork.verifyStatus == 0, "Invalid verifyStatus"); // Check destOnionHead (bytes32[] memory onionHeads, bytes32 destOnionHead) = Fork .getVerifyOnions(prevFork, _transferDatas, _committers); require(destOnionHead == fork.destOnionHead, "Different destOnionHead"); _settlement( chainId, fork.allAmount, onionHeads, _transferDatas, _committers ); // Send token to fork's endorser IERC20(tokenAddress).safeTransfer( forkDeposit.endorser, forkDeposit.amount // TODO Add reward(No denyer here) ); // storage fork fork.needBond = false; hashOnionForks.update(forkKey, fork); } function disputeSolve( uint256 chainId, bytes32 prevForkKey, bytes32 forkKey, bytes32 forkTxHash, bytes32[] memory wrongForkKeys, bytes32[] memory wrongForkTxHashs ) external { Fork.Info memory prevFork = hashOnionForks.getForkEnsure(prevForkKey); Fork.Info memory fork = hashOnionForks.getForkEnsure(forkKey); // Verify forkKey bytes32 forkOnionHead = keccak256( abi.encode(prevFork.onionHead, forkTxHash) ); require( Fork.generateForkKey(chainId, forkOnionHead, fork.workIndex) == forkKey, "ForkKey verify faild" ); require(fork.verifyStatus == 1, "Fork verify failed"); bytes32 wrongForkOnionHead = prevFork.onionHead; for (uint256 i = 0; i < wrongForkKeys.length; i++) { Fork.Info memory wrongFork = hashOnionForks.getForkEnsure( wrongForkKeys[i] ); // Verify wrong forkKey, verifyStatus wrongForkOnionHead = keccak256( abi.encode(wrongForkOnionHead, wrongForkTxHashs[i]) ); require( Fork.generateForkKey( chainId, wrongForkOnionHead, wrongFork.workIndex ) == wrongForkKeys[i], "Wrong forkKey verify faild" ); require(wrongFork.verifyStatus != 0, "Exception verifyStatus"); // Check deposit ForkDeposit.Info memory wrongForkDeposit = hashOnionForkDeposits .getDepositEnsure(wrongForkKeys[i]); require(wrongForkDeposit.denyer != address(0), "No exist denyer"); IERC20(tokenAddress).safeTransfer( wrongForkDeposit.denyer, wrongForkDeposit.amount ); // Change wrongFork.verifyStatus wrongFork.verifyStatus = 2; hashOnionForks.update(wrongForkKeys[i], wrongFork); } } function loanFromLPPool(uint256 amount) internal { // Send bondToken to LPPool, LPPool send real token to dest PoolToken(poolTokenAddress()).exchange(tokenAddress, amount); } // buy bond token function buyOneFork( uint256 chainId, uint256 _forkKey, uint256 _forkId ) external override {} // 1. Dest borrow token from the liquidity poo.(When liquidity is insufficient) // 2. Dest send token to committers function _settlement( uint256 chainId, uint256 forkAllAmount, bytes32[] memory onionHeads, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) internal { // When token.balanceOf(this) < fork.allAmount, get token from LP if (IERC20(tokenAddress).balanceOf(address(this)) < forkAllAmount) { uint256 diffAmount = forkAllAmount - IERC20(tokenAddress).balanceOf(address(this)); // Ensure LP has sufficient token require( IERC20(tokenAddress).balanceOf(poolTokenAddress()) >= diffAmount, "Pool insufficient" ); // Calculate lever PoolToken poolToken = PoolToken(poolTokenAddress()); uint256 poolTokenAmount = diffAmount / poolToken.scale(); // TODO Debug, mint poolToken poolToken.mint(poolTokenAmount); // Exchange poolToken.exchange(tokenAddress, poolTokenAmount); } // Send token to committers for (uint256 i; i < _transferDatas.length; i++) { bytes32 onionHead = onionHeads[i]; if (isRespondOnions[chainId][onionHead]) { address onionAddress = onionsAddress[onionHead]; if (onionAddress != address(0)) { IERC20(tokenAddress).safeTransfer( onionAddress, _transferDatas[i].amount + _transferDatas[i].fee ); } else { IERC20(tokenAddress).safeTransfer( _transferDatas[i].destination, _transferDatas[i].amount + _transferDatas[i].fee ); } } else { IERC20(tokenAddress).safeTransfer( _committers[i], _transferDatas[i].amount + _transferDatas[i].fee ); } } } function _setOnWorkHashOnion(uint256 chainId, Fork.Info memory fork) internal { HashOnions.Info memory info = hashOnions[chainId]; if ( fork.needBond || Fork.isEarlyBonded(fork.verifyStatus, fork.needBond) ) { info.onWorkHashOnion = fork.onionHead; } else { // If no settlement is required, it means that the previous round of settlement is completed, and a new value is set info.onWorkHashOnion = info.sourceHashOnion; } hashOnions[chainId] = info; } }
if source index % ONEFORK_MAX_LENGTH != 0 Determine whether tx.origin is eligible to submit Determine whether the maker only submits or submits and also responds, so as to avoid the large amount of unresponsiveness of the maker and block subsequent commints
function mFork( uint256 chainId, bytes32 _lastOnionHead, bytes32 _lastDestOnionHead, uint16 _index, Data.TransferData calldata _transferData, bool _isRespond ) external override { require(_committerDeposits[msg.sender] == true, "a3"); Fork.Info memory newFork = hashOnionForks.createMFork( chainId, _lastOnionHead, _lastDestOnionHead, _index, _transferData ); if (_isRespond) { IERC20(tokenAddress).safeTransferFrom( msg.sender, _transferData.destination, _transferData.amount ); isRespondOnions[chainId][newFork.onionHead] = true; } }
5,533,098
//SPDX-License-Identifier: MIT pragma solidity 0.8.9; // import './interfaces/IGanacheChainlinkClient.sol'; import './interfaces/IMinionFactory.sol'; import './interfaces/IMinion.sol'; import './BaseFeeContract.sol'; interface IOracleFeed { function request() external view returns (bytes memory response); } contract Automaton is BaseFeeContract { using SafeMath for uint256; enum State { Open, Forwarded, Completed, Closed, Failed } enum Comparator { EQ, GT, NOT, LT } struct Condition { address oracle; Comparator comparator; bytes subject; } struct Action { bytes data; uint gasLimit; uint gasPrice; uint amount; address target; } struct Automation { address creator; address minion; Action action; Condition condition; State state; } IMinionFactory MINION_FACTORY; uint256 public autoId; uint256 public lastAutoIdChecked; mapping(address => address) public clientForMinion; mapping(uint256 => Automation) public automations; /** * === === === === === Events === === === === === === */ event MinionRegistered(address indexed creator, address minion); event AutomationCreated(address indexed creator, uint256 automationId, Automation automation); event AutomationFailed(address indexed creator, uint256 automationId, bytes reason); event AutomationCompleted(address indexed creator, uint256 automationId); event AutomationValueForwarded(address indexed minion, uint256 automationId, uint256 amount); /** * === === === === === Modifiers === === === === === === */ modifier existingNotFinalAutomation(uint256 _autoId) { Automation memory automation = automations[_autoId]; require(automation.creator != address(0), 'Automaton: invalid automation'); require( automation.state != State.Completed && automation.state != State.Closed && automation.state != State.Failed, 'Automaton: automation state is final' ); _; } modifier validExternalAddress(address _address) { require(_address != address(0), 'Automaton: invalid address, none passed'); require(_address != address(this), 'Automaton: invalid address, self passed'); _; } /** * === === === === === Functions === === === === === === * * Automation functions responsible for running the automaton logic */ function initialize( address minionFactoryAddress, uint256 initialFee ) public validExternalAddress(minionFactoryAddress) { require(address(MINION_FACTORY) == address(0), 'Automaton: Already initialized'); MINION_FACTORY = IMinionFactory(minionFactoryAddress); super.initialize(initialFee); } function _getOrRegisterMinion() internal returns (address minion) { address _minion = clientForMinion[msg.sender]; if (_minion == address(0)) { minion = MINION_FACTORY.spawn(msg.sender); clientForMinion[msg.sender] = minion; emit MinionRegistered(msg.sender, minion); } else { minion = _minion; } } function _forwardAutomationValue(uint256 amount, uint256 _autoId) internal whenNotPaused { Automation storage automation = automations[_autoId]; require(automation.state == State.Open, 'Automaton: automation already initiated'); automation.state = State.Forwarded; _chargeFeeAndSendRest(amount, payable(automation.minion)); emit AutomationValueForwarded(automation.minion, _autoId, amount); } function setupAutomation( address target, uint256 amount, uint256 gasPrice, bytes memory data, bytes memory subject, Comparator comparator, address oracle ) public payable whenNotPaused validExternalAddress(target) returns (uint256) { uint256 usableCarriedGas = _calculateUsableGasFromAmount(gasPrice, amount); address minion = _getOrRegisterMinion(); autoId++; Action memory action = Action({ target: target, data: data, gasLimit: usableCarriedGas, gasPrice: gasPrice, amount: amount }); automations[autoId] = Automation({ creator: msg.sender, minion: minion, action: action, condition: Condition({ oracle: oracle, comparator: comparator, subject: subject }), state: State.Open }); emit AutomationCreated(msg.sender, autoId, automations[autoId]); _forwardAutomationValue(amount, autoId); return autoId; } function checkCondition( address oracle, Comparator comparator, bytes memory subject ) public view returns (bool) { require(oracle != address(this), 'Automaton: invalid oracle address'); require(oracle != address(0), 'Automaton: zero oracle address'); // require(clientForMinion[msg.sender] != address(0), 'Automaton: you need to create a minion first'); // IGanacheChainlinkClient(client).requestEthereumPrice(oracle, job); // It is expected to receive bytes as response. If lt/gt condition check needed // will be casted to int256 bytes memory response = IOracleFeed(oracle).request(); if (comparator == Comparator.EQ) { if (keccak256(subject) == keccak256(response)) { return true; } return false; } if (comparator == Comparator.NOT) { if (keccak256(subject) != keccak256(response)) { return true; } return false; } if (comparator == Comparator.GT) { int responseDecoded = abi.decode(response, (int)); int subjectDecoded = abi.decode(subject, (int)); if (subjectDecoded > responseDecoded) { return true; } return false; } if (comparator == Comparator.LT) { int responseDecoded = abi.decode(response, (int)); int subjectDecoded = abi.decode(subject, (int)); if (subjectDecoded < responseDecoded) { return true; } return false; } return false; } function executeAutomation(uint256 _autoId) public whenNotPaused nonReentrant existingNotFinalAutomation(_autoId) returns (bool executed, bytes memory result) { Automation storage automation = automations[_autoId]; require(tx.gasprice <= automation.action.gasPrice); (executed, result) = IMinion(payable(automation.minion)).executeOrder({ target: automation.action.target, data: automation.action.data, gas: automation.action.gasLimit.mul(automation.action.gasPrice), value: automation.action.amount }); if (executed) { automation.state = State.Completed; emit AutomationCompleted(automation.creator, _autoId); } else { automation.state = State.Failed; emit AutomationFailed(automation.creator, _autoId, result); revert(); } } // function checkUpkeep( // bytes calldata checkData // ) // external // view // returns ( // bool upkeepNeeded, // bytes memory performData // ) { // address _oracle; // assembly { // _oracle := calldataload(add(checkData.offset, 20)) // } // require(_oracle != address(0)); // int value = _getChainlinkValue(_oracle); // uint _currentAutoId = lastAutoIdChecked.add(1); // if (lastAutoIdChecked >= autoId) { // _currentAutoId = 0; // } // Automation memory _auto = automations[_currentAutoId]; // while (_auto.oracle != _oracle && _currentAutoId <= autoId && ) { // } // } // /** // * @notice method that is actually executed by the keepers, via the registry. // * The data returned by the checkUpkeep simulation will be passed into // * this method to actually be executed. // * @dev The input to this method should not be trusted, and the caller of the // * method should not even be restricted to any single registry. Anyone should // * be able call it, and the input should be validated, there is no guarantee // * that the data passed in is the performData returned from checkUpkeep. This // * could happen due to malicious keepers, racing keepers, or simply a state // * change while the performUpkeep transaction is waiting for confirmation. // * Always validate the data passed in. // * @param performData is the data which was passed back from the checkData // * simulation. If it is encoded, it can easily be decoded into other types by // * calling `abi.decode`. This data should not be trusted, and should be // * validated against the contract's current state. // */ // function performUpkeep( // bytes calldata performData // ) external { // } }
require(clientForMinion[msg.sender] != address(0), 'Automaton: you need to create a minion first'); IGanacheChainlinkClient(client).requestEthereumPrice(oracle, job); It is expected to receive bytes as response. If lt/gt condition check needed will be casted to int256
function checkCondition( address oracle, Comparator comparator, bytes memory subject ) public view returns (bool) { require(oracle != address(this), 'Automaton: invalid oracle address'); require(oracle != address(0), 'Automaton: zero oracle address'); bytes memory response = IOracleFeed(oracle).request(); if (comparator == Comparator.EQ) { if (keccak256(subject) == keccak256(response)) { return true; } return false; } if (comparator == Comparator.NOT) { if (keccak256(subject) != keccak256(response)) { return true; } return false; } if (comparator == Comparator.GT) { int responseDecoded = abi.decode(response, (int)); int subjectDecoded = abi.decode(subject, (int)); if (subjectDecoded > responseDecoded) { return true; } return false; } if (comparator == Comparator.LT) { int responseDecoded = abi.decode(response, (int)); int subjectDecoded = abi.decode(subject, (int)); if (subjectDecoded < responseDecoded) { return true; } return false; } return false; }
13,032,309
// contracts/PMV.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Optimized.sol"; import "./PMVMixin.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; contract PiratesOfTheMetaverse is PMVMixin, ERC721Optimized, VRFConsumerBase { using Strings for uint256; using MerkleProof for bytes32[]; mapping (address => uint256) public presaleMints; mapping (address => uint256) public freeMints; bytes32 private s_keyHash; uint256 private s_fee; bool public allowBurning = false; constructor(bytes32 merkleroot, string memory uri, bytes32 _rootMintFree, bytes32 _provenanceHash, address vrfCoordinator, address link, bytes32 keyhash, uint256 fee, address _multiSigWallet) ERC721Optimized("Pirates of the Metaverse", "POMV") VRFConsumerBase(vrfCoordinator, link){ root = merkleroot; notRevealedUri = uri; rootMintFree = _rootMintFree; provenanceHash = _provenanceHash; s_keyHash = keyhash; s_fee = fee; multiSigWallet = _multiSigWallet; } function mintPresale(uint256 allowance, bytes32[] calldata proof, uint256 tokenQuantity) external payable { require(presaleActive, "PRESALE NOT ACTIVE"); require(proof.verify(root, keccak256(abi.encodePacked(msg.sender, allowance))), "NOT ON ALLOWLIST"); require(presaleMints[msg.sender] + tokenQuantity <= allowance, "MINTING MORE THAN ALLOWED"); uint256 currentSupply = totalNonBurnedSupply(); require(tokenQuantity + currentSupply <= maxSupply, "NOT ENOUGH LEFT IN STOCK"); require(tokenQuantity * presalePrice <= msg.value, "INCORRECT PAYMENT AMOUNT"); for(uint256 i = 1; i <= tokenQuantity; i++) { _mint(msg.sender, currentSupply + i); } presaleMints[msg.sender] += tokenQuantity; } function mintFree(uint256 allowance, bytes32[] calldata proof, uint256 tokenQuantity) external { require(presaleActive, "Free mint not allowed"); require(proof.verify(rootMintFree, keccak256(abi.encodePacked(msg.sender, allowance))), "NOT ON FREE MINT ALLOWLIST"); require(freeMints[msg.sender] + tokenQuantity <= allowance, "MINTING MORE THAN ALLOWED"); uint256 currentSupply = totalNonBurnedSupply(); require(tokenQuantity + currentSupply <= maxSupply, "NOT ENOUGH LEFT IN STOCK"); for(uint256 i = 1; i <= tokenQuantity; i++) { _mint(msg.sender, currentSupply + i); } freeMints[msg.sender] += tokenQuantity; } function mint(uint256 tokenQuantity) external payable { if (!letContractMint){ require(msg.sender == tx.origin, "CONTRACT NOT ALLOWED TO MINT IN PUBLIC SALE"); } require(saleActive, "SALE NOT ACTIVE"); require(tokenQuantity <= maxPerTransaction, "MINTING MORE THAN ALLOWED IN A SINGLE TRANSACTION"); uint256 currentSupply = totalNonBurnedSupply(); require(tokenQuantity + currentSupply <= maxSupply, "NOT ENOUGH LEFT IN STOCK"); require(tokenQuantity * salePrice <= msg.value, "INCORRECT PAYMENT AMOUNT"); for(uint256 i = 1; i <= tokenQuantity; i++) { _mint(msg.sender, currentSupply + i); } } function ownerMint(uint256 tokenQuantity) external onlyOwner { uint256 currentSupply = totalNonBurnedSupply(); require(tokenQuantity + currentSupply <= ownerMintBuffer, "NOT ENOUGH LEFT IN STOCK"); for(uint256 i = 1; i <= tokenQuantity; i++) { _mint(multiSigWallet, currentSupply + i); } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); return _tokenURI(tokenId); } function generateRandomOffset() public onlyOwner returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= s_fee, "Not enough LINK to pay fee"); require(!offsetRequested, "Already generated random offset"); requestId = requestRandomness(s_keyHash, s_fee); } function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { // transform the result to a number between 0 and 9,997 inclusively // token 1 and 2 are fixed and are not included for purposes of offsetting uint256 newOffset = (randomness % (maxSupply - 2)); offset = newOffset; offsetRequested = true; } function setAllowBurning(bool _allowBurning) external onlyOwner { allowBurning = _allowBurning; } function burn(uint256 tokenId) public virtual { require(allowBurning, "Burning not currently allowed"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Optimized is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Array containing mapping zero-indexed tokens to owners address[] private _owners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 private _numBurned; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); uint256 count = 0; for (uint256 index = 0; index < _owners.length; index++){ if (owner == _owners[index]) count++; } return count; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); return _owners[tokenId - 1]; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Optimized.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { bool positive = tokenId > 0; bool inBounds = tokenId < totalNonBurnedSupply() + 1; bool notBurned = true; // if 1 <= tokenId <= 10,000 need to make sure it wasn't burned. if (inBounds){ address owner = _owners[tokenId - 1]; notBurned = owner != address(0); } return positive && inBounds && notBurned; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Optimized.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); delete _owners[tokenId - 1]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId - 1] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * Call OffChain to not pay high gas costs. */ function tokenOfOwnerByIndexOffChain(address owner, uint256 index) public view virtual returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint count; for (uint i; i < _owners.length; i ++){ if (owner == _owners[i]){ if (count == index) return i + 1; else count++; } } require(false, "ERC721Enumerable: owner index out of bounds"); } /** * @dev Get all tokens owned by an address in two passes of the owner array. * Call OffChain to not pay high gas costs. */ function tokensOfOwnerOffChain(address owner) public view returns (uint[] memory) { uint balance = balanceOf(owner); uint[] memory _tokens = new uint[](balance); uint count; for (uint i; i < _owners.length; i ++){ if (owner == _owners[i]){ _tokens[count] = i + 1; count++; } } return _tokens; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _owners.length - _numBurned; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalNonBurnedSupply() public view virtual returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndexOffChain(uint256 index) public view virtual returns (uint256) { require(index < ERC721Optimized.totalSupply(), "ERC721Enumerable: global index out of bounds"); uint256 count; // When a token is burned, the index of all tokens above that index // should be shifted by 1 to the left. Since we do not pop entries of _owners, we need // to add back the missing shift. for(uint i = 0; i < _owners.length; i++ ){ if(_owners[i] == address(0)) count += 1; if(int(i) - int(count) == int(index)) return uint256(i) + 1; } require(false, "ERC721Enumerable: index not found"); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { _numBurned += 1; } } // contracts/PMV.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Optimized.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract PMVMixin is Ownable { using Strings for uint256; using Address for address payable; uint256 public constant maxSupply = 10000; uint256 public maxPerTransaction = 10; uint public salePrice = 0.1 ether; uint public presalePrice = 0.077 ether; bool public presaleActive = false; bool public saleActive = false; string private tokenBaseURI; string internal notRevealedUri; bool private revealed = false; bytes32 public root; bytes32 public rootMintFree; bytes32 public provenanceHash; uint256 public offset; bool public offsetRequested = false; address public multiSigWallet; bool public letContractMint = false; uint256 public ownerMintBuffer = 200; function _tokenURI(uint256 tokenId) public view virtual returns (string memory) { if(revealed == false) { return notRevealedUri; } else { return string(abi.encodePacked(tokenBaseURI, tokenId.toString())); } } function setPresale(bool _presaleStatus) external onlyOwner { presaleActive = _presaleStatus; } function setSale(bool _saleStatus) external onlyOwner { saleActive = _saleStatus; } function setURIStatus(bool _revealed, string calldata _tokenBaseURI) external onlyOwner { require(bytes(_tokenBaseURI).length > 0, "_tokenBaseURI is empty"); revealed = _revealed; tokenBaseURI = _tokenBaseURI; } function setRoot(bytes32 _root) external onlyOwner { require(_root.length > 0, "_root is empty"); root = _root; } function setRootMintFree(bytes32 _root) external onlyOwner { require(_root.length > 0, "_root is empty"); rootMintFree = _root; } function withdraw() external onlyOwner { payable(multiSigWallet).sendValue(address(this).balance); } function setMaxPerTransaction(uint256 _maxPerTransaction) external onlyOwner { require(_maxPerTransaction > 0, "maxPerTransaction should be positive"); maxPerTransaction = _maxPerTransaction; } function setPrice(uint _salePrice) external onlyOwner { salePrice = _salePrice; } function setPresalePrice(uint _presalePrice) external onlyOwner { presalePrice = _presalePrice; } function setLetContractMint(bool _letContractMint) external onlyOwner { letContractMint = _letContractMint; } function setOwnerMintBuffer(uint256 _ownerMintBuffer) external onlyOwner { ownerMintBuffer = _ownerMintBuffer; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } }
Private function to add a token to this extension's token tracking data structures. tokenId uint256 ID of the token to be added to the tokens list/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { }
10,190,965
pragma solidity 0.4.26; import "./ERC20.sol"; import "./Oracle.sol"; import "./DSMath.sol"; /** * @title Atomic Loans Medianizer Contract * @author Atomic Loans */ contract Medianizer is DSMath { bool hasPrice; bytes32 assetPrice; uint256 public minOraclesRequired = 5; bool on; address deployer; uint256 constant public MIN_ORACLIZE_GAS_LIMIT = 200000; uint256 constant public MAX_ORACLIZE_GAS_LIMIT = 1000000; Oracle[] public oracles; event Fund(uint256 amount_, ERC20 token_); event Poke(bytes32 assetPrice, bool hasPrice); /** * @notice Construct a new Medianizer */ constructor() public { deployer = msg.sender; } // NOTE: THE FOLLOWING FUNCTION CAN ONLY BE CALLED BY THE DEPLOYER OF THE // CONTRACT ONCE. THIS IS TO ALLOW FOR MEDIANIZER AND ORACLE // CONTRACTS TO BE DEPLOYED SEPARATELY (DUE TO GAS LIMIT RESTRICTIONS). // IF YOU ARE USING THIS CONTRACT, ENSURE THAT THESE FUNCTIONS HAVE // ALREADY BEEN CALLED BEFORE USING. // ====================================================================== /** * @notice Sets Oracle contracts * @param addrs Addresses of Oracle contracts */ function setOracles(address[10] addrs) public { require(!on, "Funds.setOracles: Oracles already set"); require(msg.sender == deployer, "Funds.setOracles: msg.sender isn't deployer"); oracles.push(Oracle(addrs[0])); oracles.push(Oracle(addrs[1])); oracles.push(Oracle(addrs[2])); oracles.push(Oracle(addrs[3])); oracles.push(Oracle(addrs[4])); oracles.push(Oracle(addrs[5])); oracles.push(Oracle(addrs[6])); oracles.push(Oracle(addrs[7])); oracles.push(Oracle(addrs[8])); oracles.push(Oracle(addrs[9])); on = true; } // ====================================================================== // NOTE: THE FOLLOWING FUNCTION ALLOW THE MAX REWARD TO BE MODIFIED BY THE // DEPLOYER, SINCE CHAINLINK ORACLES DON'T HAVE A SET PAYMENT // AND CHAINLINK OPERATORS CAN INDEPENDENTLY SET THEIR OWN LINK PRICES. // ADDITIONALLY EVEN IF THE MAX REWARD IS SET TO ZERO, THE ORACLES // CAN STILL BE UPDATED. // ====================================================================== /** * @notice Sets Max Reward for Chainlink Contracts * @param maxReward_ Max Reward amount that can be awarded for updating Chainlink Oracle */ function setMaxReward(uint256 maxReward_) public { require(on, "Funds.setMaxReward: Oracles not set"); require(msg.sender == deployer, "Funds.setMaxReward: msg.sender isn't deployer"); oracles[0].setMaxReward(maxReward_); oracles[1].setMaxReward(maxReward_); oracles[2].setMaxReward(maxReward_); oracles[3].setMaxReward(maxReward_); oracles[4].setMaxReward(maxReward_); oracles[5].setMaxReward(maxReward_); oracles[6].setMaxReward(maxReward_); oracles[7].setMaxReward(maxReward_); oracles[8].setMaxReward(maxReward_); oracles[9].setMaxReward(maxReward_); } // ====================================================================== // NOTE: THE FOLLOWING FUNCTION ALLOW THE GAS LIMIT TO BE MODIFIED BY THE // DEPLOYER, SINCE ORACLIZE ORACLES HAVE A MINIMUM GAS LIMIT OF // 200,000 AND THERE COULD BE CASES WHERE THERE IS NOT ENOUGH GAS TO // COVER UPDATING THE PRICE. THE GAS LIMIT CAN BE CHANGED BETWEEN // A MINIMUM OF 200,000 GAS AND A MAXIMUM OF 1,000,000 GAS. // ====================================================================== /** * @notice Sets Gas Limit for Oraclize Contracts * @param gasLimit_ Gas Limit that Oraclize will use when updating the contracts */ function setGasLimit(uint256 gasLimit_) public { require(on, "Funds.setGasLimit: Oracles not set"); require(msg.sender == deployer, "Funds.setGasLimit: msg.sender isn't deployer"); require(gasLimit_ >= MIN_ORACLIZE_GAS_LIMIT, "Funds.setGasLimit: gasLimit_ cannot be less than min oraclize gas limit"); require(gasLimit_ <= MAX_ORACLIZE_GAS_LIMIT, "Funds.setGasLimit: gasLimit_ cannot be greater than max oraclize gas limit"); oracles[0].setGasLimit(gasLimit_); oracles[1].setGasLimit(gasLimit_); oracles[2].setGasLimit(gasLimit_); oracles[3].setGasLimit(gasLimit_); oracles[4].setGasLimit(gasLimit_); oracles[5].setGasLimit(gasLimit_); oracles[6].setGasLimit(gasLimit_); oracles[7].setGasLimit(gasLimit_); oracles[8].setGasLimit(gasLimit_); oracles[9].setGasLimit(gasLimit_); } // ====================================================================== /** * @notice Return Medianizer price without asserting */ function peek() public view returns (bytes32, bool) { return (assetPrice,hasPrice); } /** * @notice Return Medianizer price and assert that value has been set recently * @dev Reverts if price is not set or has not been set within expiry for enough Oracles */ function read() public returns (bytes32) { (assetPrice, hasPrice) = peek(); assert(hasPrice); return assetPrice; } /** * @notice Add funds to oracle reserve that is used to compensate users to updating oracles * @param amount_ Amount of ERC20 stablecoin token to fund * @param token_ Address of ERC20 stablecoin token */ function fund(uint256 amount_, ERC20 token_) public { require(amount_ < 2**128-1, "Medianizer.fund: amount is greater than max uint128"); // Ensure amount fits in uint128 for (uint256 i = 0; i < oracles.length; i++) { require( token_.transferFrom(msg.sender, address(oracles[i]), uint256(hdiv(uint128(amount_), uint128(oracles.length)))), "Medianizer.fund: failed to transfer tokens to oracles" ); } emit Fund(amount_, token_); } /** * @notice Compute and set Medianizer price */ function poke() public { poke(0); } /** * @notice Compute and set Medianizer price */ function poke(bytes32) public { (assetPrice, hasPrice) = compute(); emit Poke(assetPrice, hasPrice); } /** * @notice Compute Medianizer price based on current price of oracles * @return Asset price and bool true if price is set */ function compute() public view returns (bytes32, bool) { bytes32 wut; bool wuz; bytes32[] memory wuts = new bytes32[](oracles.length); uint256 ctr = 0; for (uint256 i = 0; i < oracles.length; i++) { if (address(oracles[i]) != 0) { (wut, wuz) = oracles[i].peek(); if (wuz) { if (ctr == 0 || wut >= wuts[ctr - 1]) { wuts[ctr] = wut; } else { uint256 j = 0; while (wut >= wuts[j]) { j++; } for (uint256 k = ctr; k > j; k--) { wuts[k] = wuts[k - 1]; } wuts[j] = wut; } ctr++; } } } if (ctr < minOraclesRequired) return (assetPrice, false); bytes32 value; if (ctr % 2 == 0) { uint128 val1 = uint128(wuts[(ctr / 2) - 1]); uint128 val2 = uint128(wuts[ctr / 2]); value = bytes32((val1 + val2) / 2); } else { value = wuts[(ctr - 1) / 2]; } return (value, true); } }
Return Medianizer price without asserting/
function peek() public view returns (bytes32, bool) { return (assetPrice,hasPrice); }
2,576,419
./full_match/1/0x556d9E146CC7Fe7DF93fBdd90347Af8930acb104/sources/browser/Contract_Code_Min.sol
Show contract state view return info contract state view/
function stateView() public view returns (uint[8] memory info) { info[0] = _getCurrentUserID(); info[1] = rid; info[2] = resonanceDataMapping[rid].ratio; info[3] = resonanceDataMapping[rid].investMoney; info[4] = resonanceDataMapping[rid].time; info[5] = AddupInvestUSD; info[6] = ETTPool_Dev_RwAddup; info[7] = ETTPool_Dev_LastRwTime; return (info); }
3,090,366
./full_match/1/0xb2883633995c5a88073db20CE6C658EC1f459d46/sources/contracts/TestUpcycleThird.sol
To change signer wallet address _signer address/
function setSignerWallet(address _signer) external onlyOwner { signer = _signer; }
3,078,388
./partial_match/1/0x912338295ADB416ca81c4a743c0aC5b32fE2A569/sources/NFT.sol
cut the free supply
function setFreesupply(uint256 _newsupply) public onlyOwner { FreeSupply = _newsupply; }
16,170,630
./partial_match/42/0x352f5D411B37706C8cce266AbF7d63dE8856c0f4/sources/MerryMenPair.sol
this low-level function should be called from a contract which performs important safety checks scope for _token{0,1}, avoids stack too deep errors scope for reserve{0,1}Adjusted, avoids stack too deep errors
function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external lock { require( amount0Out > 0 || amount1Out > 0, "MerryMen: INSUFFICIENT_OUTPUT_AMOUNT" ); require( amount0Out < _reserve0 && amount1Out < _reserve1, "MerryMen: INSUFFICIENT_LIQUIDITY" ); uint256 balance0; uint256 balance1; { address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, "MerryMen: INVALID_TO"); if (data.length > 0) IMerryMenCallee(to).MerryMenCall( msg.sender, amount0Out, amount1Out, data ); balance0 = IERC20MerryMen(_token0).balanceOf(address(this)); balance1 = IERC20MerryMen(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require( amount0In > 0 || amount1In > 0, "MerryMen: INSUFFICIENT_INPUT_AMOUNT" ); { uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require( balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), "MerryMen: K" ); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); }
3,351,932
./partial_match/1/0x85018CF6F53c8bbD03c3137E71F4FCa226cDa92C/sources/contracts/ApeStaking.sol
Get user's rewards and borrowing interest per block userAddr User address return totalIncome Rewards per block return totalPay Borrowing interest per block/
function getUserHealth(address userAddr) public returns (uint256 totalIncome, uint256 totalPay) { UserInfo storage userInfo = _userInfo[userAddr]; for(uint256 poolId = BAYC_POOL_ID; poolId <= BAKC_POOL_ID; poolId++) { uint256 poolStakingRatePerBlock = getRewardRatePerBlock(poolId, 0); totalIncome += userInfo.stakeAmount[poolId] * poolStakingRatePerBlock / BASE_PERCENTS; } uint256 borrowRate = IApePool(apePool).borrowRatePerBlock(); uint256 borrowedAmount = IApePool(apePool).borrowBalanceCurrent(userAddr); totalPay = borrowedAmount * borrowRate / BASE_PERCENTS; }
4,470,125
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.5.0; import "./RoleManager.sol"; import "./AccountManager.sol"; import "./VoterManager.sol"; import "./NodeManager.sol"; import "./OrgManager.sol"; import "./PermissionsUpgradable.sol"; /** @title Permissions Implementation Contract * @notice This contract holds implementation logic for all permissions related functionality. This can be called only by the interface contract. */ contract PermissionsImplementation { AccountManager private accountManager; RoleManager private roleManager; VoterManager private voterManager; NodeManager private nodeManager; OrgManager private orgManager; PermissionsUpgradable private permUpgradable; string private adminOrg; string private adminRole; string private orgAdminRole; uint256 private fullAccess = 3; /** @dev this variable is meant for tracking the initial network boot up once the network boot up is done the value is set to true */ bool private networkBoot = false; event PermissionsInitialized(bool _networkBootStatus); /** @notice modifier to confirm that caller is the interface contract */ modifier onlyInterface{ require(msg.sender == permUpgradable.getPermInterface(), "can be called by interface contract only"); _; } /** @notice modifier to confirm that caller is the upgradable contract */ modifier onlyUpgradeable { require(msg.sender == address(permUpgradable), "invalid caller"); _; } /** @notice confirms if the network boot status is equal to passed value * @param _status true/false */ modifier networkBootStatus(bool _status){ require(networkBoot == _status, "Incorrect network boot status"); _; } /** @notice confirms that the account passed is network admin account * @param _account account id */ modifier networkAdmin(address _account) { require(isNetworkAdmin(_account) == true, "account is not a network admin account"); _; } /** @notice confirms that the account passed is org admin account * @param _account account id * @param _orgId org id to which the account belongs */ modifier orgAdmin(address _account, string memory _orgId) { require(isOrgAdmin(_account, _orgId) == true, "account is not a org admin account"); _; } /** @notice confirms that org does not exist * @param _orgId org id */ modifier orgNotExists(string memory _orgId) { require(_checkOrgExists(_orgId) != true, "org exists"); _; } /** @notice confirms that org exists * @param _orgId org id */ modifier orgExists(string memory _orgId) { require(_checkOrgExists(_orgId) == true, "org does not exist"); _; } /** @notice checks of the passed org id is in approved status * @param _orgId org id */ modifier orgApproved(string memory _orgId) { require(checkOrgApproved(_orgId) == true, "org not in approved status"); _; } /** @notice constructor accepts the contracts addresses of other deployed contracts of the permissions model * @param _permUpgradable - address of permissions upgradable contract * @param _orgManager - address of org manager contract * @param _rolesManager - address of role manager contract * @param _accountManager - address of account manager contract * @param _voterManager - address of voter manager contract * @param _nodeManager - address of node manager contract */ constructor (address _permUpgradable, address _orgManager, address _rolesManager, address _accountManager, address _voterManager, address _nodeManager) public { permUpgradable = PermissionsUpgradable(_permUpgradable); orgManager = OrgManager(_orgManager); roleManager = RoleManager(_rolesManager); accountManager = AccountManager(_accountManager); voterManager = VoterManager(_voterManager); nodeManager = NodeManager(_nodeManager); } // initial set up related functions /** @notice for permissions its necessary to define the initial admin org id, network admin role id and default org admin role id. this sets these values at the time of network boot up * @param _nwAdminOrg - address of permissions upgradable contract * @param _nwAdminRole - address of org manager contract * @param _oAdminRole - address of role manager contract * @dev this function will be executed only once as part of the boot up */ function setPolicy(string calldata _nwAdminOrg, string calldata _nwAdminRole, string calldata _oAdminRole) external onlyInterface networkBootStatus(false) { adminOrg = _nwAdminOrg; adminRole = _nwAdminRole; orgAdminRole = _oAdminRole; } /** @notice when migrating implementation contract, the values of these key values need to be set from the previous implementation contract. this function allows these values to be set * @param _nwAdminOrg - address of permissions upgradable contract * @param _nwAdminRole - address of org manager contract * @param _oAdminRole - address of role manager contract * @param _networkBootStatus - network boot status true/false */ function setMigrationPolicy(string calldata _nwAdminOrg, string calldata _nwAdminRole, string calldata _oAdminRole, bool _networkBootStatus) external onlyUpgradeable networkBootStatus(false) { adminOrg = _nwAdminOrg; adminRole = _nwAdminRole; orgAdminRole = _oAdminRole; networkBoot = _networkBootStatus; } /** @notice called at the time of network initialization. sets up network admin org with allowed sub org depth and breadth creates the network admin for the network admin org sets the default values required by account manager contract * @param _breadth - number of sub orgs allowed at parent level * @param _depth - levels of sub org nesting allowed at parent level */ function init(uint256 _breadth, uint256 _depth) external onlyInterface networkBootStatus(false) { orgManager.setUpOrg(adminOrg, _breadth, _depth); roleManager.addRole(adminRole, adminOrg, fullAccess, true, true); accountManager.setDefaults(adminRole, orgAdminRole); } /** @notice as a part of network initialization add all nodes which are part of static-nodes.json as nodes belonging to network admin org * @param _enodeId - enode id * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node */ function addAdminNode(string calldata _enodeId, string calldata _ip, uint16 _port, uint16 _raftport) external onlyInterface networkBootStatus(false) { nodeManager.addAdminNode(_enodeId, _ip, _port, _raftport, adminOrg); } /** @notice as a part of network initialization add all accounts which are passed via permission-config.json as network administrator accounts * @param _account - account id */ function addAdminAccount(address _account) external onlyInterface networkBootStatus(false) { updateVoterList(adminOrg, _account, true); accountManager.assignAdminRole(_account, adminOrg, adminRole, 2); } /** @notice once the network initialization is complete, sets the network boot status to true * @return network boot status * @dev this will be called only once from geth as a part of * @dev network initialization */ function updateNetworkBootStatus() external onlyInterface networkBootStatus(false) returns (bool){ networkBoot = true; emit PermissionsInitialized(networkBoot); return networkBoot; } /** @notice function to add a new organization to the network. creates org record and marks it as pending approval. adds the passed node node manager contract. adds the account with org admin role to account manager contracts. creates voting record for approval by other network admin accounts * @param _orgId unique organization id * @param _enodeId enode id linked to the organization * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node * @param _account account id. this will have the org admin privileges */ function addOrg(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _account, address _caller) public onlyInterface { require(networkBoot == true, "Incorrect network boot status"); require(isNetworkAdmin(_caller) == true, "account is not a network admin account"); voterManager.addVotingItem(adminOrg, _orgId, _enodeId, _account, 1); orgManager.addOrg(_orgId); nodeManager.addNode(_enodeId, _ip, _port, _raftport, _orgId); require(validateAccount(_account, _orgId) == true, "Operation cannot be performed"); accountManager.assignAdminRole(_account, _orgId, orgAdminRole, 1); } /** @notice functions to approve a pending approval org record by networ admin account. once majority votes are received the org is marked as approved * @param _orgId unique organization id * @param _enodeId enode id linked to the organization * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node * @param _account account id this will have the org admin privileges */ function approveOrg(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _account, address _caller) public onlyInterface { require(isNetworkAdmin(_caller) == true, "account is not a network admin account"); require(_checkOrgStatus(_orgId, 1) == true, "Nothing to approve"); if ((processVote(adminOrg, _caller, 1))) { orgManager.approveOrg(_orgId); roleManager.addRole(orgAdminRole, _orgId, fullAccess, true, true); nodeManager.approveNode(_enodeId, _ip, _port, _raftport, _orgId); accountManager.addNewAdmin(_orgId, _account); } } /** @notice function to create a sub org under a given parent org. * @param _pOrgId parent org id under which the sub org is being added * @param _orgId unique id for the sub organization * @param _enodeId enode id linked to the sjb organization * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node * @dev _enodeId is optional. parent org id should contain the complete org hierarchy from master org id to the immediate parent. The org hierarchy is separated by. For example, if master org ABC has a sub organization SUB1, then while creating the sub organization at SUB1 level, the parent org should be given as ABC.SUB1 */ function addSubOrg(string calldata _pOrgId, string calldata _orgId, string calldata _enodeId, string calldata _ip, uint16 _port, uint16 _raftport, address _caller) external onlyInterface orgExists(_pOrgId) orgAdmin(_caller, _pOrgId) { orgManager.addSubOrg(_pOrgId, _orgId); string memory pOrgId = string(abi.encodePacked(_pOrgId, ".", _orgId)); if (bytes(_enodeId).length > 0) { nodeManager.addOrgNode(_enodeId, _ip, _port, _raftport, pOrgId); } } /** @notice function to update the org status. it updates the org status and adds a voting item for network admins to approve * @param _orgId unique id of the organization * @param _action 1 for suspending an org and 2 for revoke of suspension */ function updateOrgStatus(string calldata _orgId, uint256 _action, address _caller) external onlyInterface networkAdmin(_caller) { uint256 pendingOp; pendingOp = orgManager.updateOrg(_orgId, _action); voterManager.addVotingItem(adminOrg, _orgId, "", address(0), pendingOp); } /** @notice function to approve org status change. the org status is changed once the majority votes are received from network admin accounts. * @param _orgId unique id for the sub organization * @param _action 1 for suspending an org and 2 for revoke of suspension */ function approveOrgStatus(string calldata _orgId, uint256 _action, address _caller) external onlyInterface networkAdmin(_caller) { require((_action == 1 || _action == 2), "Operation not allowed"); uint256 pendingOp; uint256 orgStatus; if (_action == 1) { pendingOp = 2; orgStatus = 3; } else if (_action == 2) { pendingOp = 3; orgStatus = 5; } require(_checkOrgStatus(_orgId, orgStatus) == true, "operation not allowed"); if ((processVote(adminOrg, _caller, pendingOp))) { orgManager.approveOrgStatusUpdate(_orgId, _action); } } // Role related functions /** @notice function to add new role definition to an organization can be executed by the org admin account only * @param _roleId unique id for the role * @param _orgId unique id of the organization to which the role belongs * @param _access account access type allowed for the role * @param _voter bool indicates if the role is voter role or not * @param _admin bool indicates if the role is an admin role * @dev account access type can have of the following four values: 0 - Read only 1 - value transfer 2 - contract deploy 3 - full access 4 - contract call 5 - value transfer and contract call 6 - value transfer and contract deploy 7 - contract call and deploy */ function addNewRole(string calldata _roleId, string calldata _orgId, uint256 _access, bool _voter, bool _admin, address _caller) external onlyInterface orgApproved(_orgId) orgAdmin(_caller, _orgId) { //add new roles can be created by org admins only roleManager.addRole(_roleId, _orgId, _access, _voter, _admin); } /** @notice function to remove a role definition from an organization can be executed by the org admin account only * @param _roleId unique id for the role * @param _orgId unique id of the organization to which the role belongs */ function removeRole(string calldata _roleId, string calldata _orgId, address _caller) external onlyInterface orgApproved(_orgId) orgAdmin(_caller, _orgId) { require(((keccak256(abi.encode(_roleId)) != keccak256(abi.encode(adminRole))) && (keccak256(abi.encode(_roleId)) != keccak256(abi.encode(orgAdminRole)))), "admin roles cannot be removed"); roleManager.removeRole(_roleId, _orgId); } // Account related functions /** @notice function to assign network admin/org admin role to an account this can be executed by network admin accounts only. it assigns the role to the accounts and creates voting record for network admin accounts * @param _orgId unique id of the organization to which the account belongs * @param _account account id * @param _roleId role id to be assigned to the account */ function assignAdminRole(string calldata _orgId, address _account, string calldata _roleId, address _caller) external onlyInterface orgExists(_orgId) networkAdmin(_caller) { accountManager.assignAdminRole(_account, _orgId, _roleId, 1); //add voting item voterManager.addVotingItem(adminOrg, _orgId, "", _account, 4); } /** @notice function to approve network admin/org admin role assigment this can be executed by network admin accounts only. * @param _orgId unique id of the organization to which the account belongs * @param _account account id */ function approveAdminRole(string calldata _orgId, address _account, address _caller) external onlyInterface networkAdmin(_caller) { if ((processVote(adminOrg, _caller, 4))) { (bool ret, address account) = accountManager.removeExistingAdmin(_orgId); if (ret) { updateVoterList(adminOrg, account, false); } bool ret1 = accountManager.addNewAdmin(_orgId, _account); if (ret1) { updateVoterList(adminOrg, _account, true); } } } /** @notice function to update account status. can be executed by org admin account only. * @param _orgId unique id of the organization to which the account belongs * @param _account account id * @param _action 1-suspend 2-activate back 3-blacklist */ function updateAccountStatus(string calldata _orgId, address _account, uint256 _action, address _caller) external onlyInterface orgAdmin(_caller, _orgId) { // ensure that the action passed to this call is proper and is not // called with action 4 and 5 which are actions for blacklisted account // recovery require((_action == 1 || _action == 2 || _action == 3), "invalid action. operation not allowed"); accountManager.updateAccountStatus(_orgId, _account, _action); } // Node related functions /** @notice function to add a new node to the organization. can be invoked org admin account only * @param _orgId unique id of the organization to which the account belongs * @param _enodeId enode id being dded to the org * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node */ function addNode(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _caller) public onlyInterface orgApproved(_orgId) { // check that the node is not part of another org require(isOrgAdmin(_caller, _orgId) == true, "account is not a org admin account"); nodeManager.addOrgNode(_enodeId, _ip, _port, _raftport, _orgId); } /** @notice function to update node status. can be invoked by org admin account only * @param _orgId unique id of the organization to which the account belongs * @param _enodeId enode id being dded to the org * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node * @param _action 1-deactivate, 2-activate back, 3-blacklist the node */ function updateNodeStatus(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, uint256 _action, address _caller) public onlyInterface { require(isOrgAdmin(_caller, _orgId) == true, "account is not a org admin account"); // ensure that the action passed to this call is proper and is not // called with action 4 and 5 which are actions for blacklisted node // recovery require((_action == 1 || _action == 2 || _action == 3), "invalid action. operation not allowed"); nodeManager.updateNodeStatus(_enodeId, _ip, _port, _raftport, _orgId, _action); } /** @notice function to initiate blacklisted nodes recovery. this can be invoked by an network admin account only * @param _orgId unique id of the organization to which the account belongs * @param _enodeId enode id being dded to the org * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node * @dev this function creates a voting record for other network admins to approve the operation. The recovery is complete only after majority voting */ function startBlacklistedNodeRecovery(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _caller) public onlyInterface networkAdmin(_caller) { // update the node status as recovery initiated. action for this is 4 nodeManager.updateNodeStatus(_enodeId, _ip, _port, _raftport, _orgId, 4); // add a voting record with pending op of 5 which corresponds to blacklisted node // recovery voterManager.addVotingItem(adminOrg, _orgId, _enodeId, address(0), 5); } /** @notice function to initiate blacklisted nodes recovery. this can be invoked by an network admin account only * @param _orgId unique id of the organization to which the account belongs * @param _enodeId enode id being dded to the org * @param _ip IP of node * @param _port tcp port of node * @param _raftport raft port of node * @dev this function creates a voting record for other network admins to approve the operation. The recovery is complete only after majority voting */ function approveBlacklistedNodeRecovery(string memory _orgId, string memory _enodeId, string memory _ip, uint16 _port, uint16 _raftport, address _caller) public onlyInterface networkAdmin(_caller) { // check if majority votes are received. pending op type is passed as 5 // which stands for black listed node recovery if ((processVote(adminOrg, _caller, 5))) { // update the node back to active nodeManager.updateNodeStatus(_enodeId, _ip, _port, _raftport, _orgId, 5); } } /** @notice function to initaite blacklisted nodes recovery. this can be invoked by an network admin account only * @param _orgId unique id of the organization to which the account belongs * @param _account account id being dded to the org * @dev this function creates a voting record for other network admins to approve the operation. The recovery is complete only after majority voting */ function startBlacklistedAccountRecovery(string calldata _orgId, address _account, address _caller) external onlyInterface networkAdmin(_caller) { // update the account status as recovery initiated. action for this is 4 accountManager.updateAccountStatus(_orgId, _account, 4); // add a voting record with pending op of 5 which corresponds to blacklisted node // recovery voterManager.addVotingItem(adminOrg, _orgId, "", _account, 6); } /** @notice function to initaite blacklisted nodes recovery. this can be invoked by an network admin account only * @param _orgId unique id of the organization to which the account belongs * @param _account account id being dded to the org * @dev this function creates a voting record for other network admins to approve the operation. The recovery is complete only after majority voting */ function approveBlacklistedAccountRecovery(string calldata _orgId, address _account, address _caller) external onlyInterface networkAdmin(_caller) { // check if majority votes are received. pending op type is passed as 6 // which stands for black listed account recovery if ((processVote(adminOrg, _caller, 6))) { // update the node back to active accountManager.updateAccountStatus(_orgId, _account, 5); } } /** @notice function to fetch network boot status * @return bool network boot status */ function getNetworkBootStatus() external view returns (bool){ return networkBoot; } /** @notice function to fetch detail of any pending approval activities for network admin organization * @param _orgId unique id of the organization to which the account belongs */ function getPendingOp(string calldata _orgId) external view returns (string memory, string memory, address, uint256){ return voterManager.getPendingOpDetails(_orgId); } /** @notice function to assigns a role id to the account given account can be executed by org admin account only * @param _account account id * @param _orgId organization id to which the account belongs * @param _roleId role id to be assigned to the account */ function assignAccountRole(address _account, string memory _orgId, string memory _roleId, address _caller) public onlyInterface orgAdmin(_caller, _orgId) orgApproved(_orgId) { require(validateAccount(_account, _orgId) == true, "operation cannot be performed"); require(_roleExists(_roleId, _orgId) == true, "role does not exists"); bool admin = roleManager.isAdminRole(_roleId, _orgId, _getUltimateParent(_orgId)); accountManager.assignAccountRole(_account, _orgId, _roleId, admin); } /** @notice function to check if passed account is an network admin account * @param _account account id * @return true/false */ function isNetworkAdmin(address _account) public view returns (bool){ return (keccak256(abi.encode(accountManager.getAccountRole(_account))) == keccak256(abi.encode(adminRole))); } /** @notice function to check if passed account is an org admin account * @param _account account id * @param _orgId organization id * @return true/false */ function isOrgAdmin(address _account, string memory _orgId) public view returns (bool){ if (accountManager.checkOrgAdmin(_account, _orgId, _getUltimateParent(_orgId))) { return true; } return roleManager.isAdminRole(accountManager.getAccountRole(_account), _orgId, _getUltimateParent(_orgId)); } /** @notice function to validate the account for access change operation * @param _account account id * @param _orgId organization id * @return true/false */ function validateAccount(address _account, string memory _orgId) public view returns (bool){ return (accountManager.validateAccount(_account, _orgId)); } /** @notice function to update the voter list at network level. this will be called whenever an account is assigned a network admin role or an account having network admin role is being assigned different role * @param _orgId org id to which the account belongs * @param _account account which needs to be added/removed as voter * @param _add bool indicating if its an add or delete operation */ function updateVoterList(string memory _orgId, address _account, bool _add) internal { if (_add) { voterManager.addVoter(_orgId, _account); } else { voterManager.deleteVoter(_orgId, _account); } } /** @notice whenever a network admin account votes on a pending item, this function processes the vote. * @param _orgId org id of the caller * @param _caller account which approving the operation * @param _pendingOp operation for which the approval is being done * @dev the list of pending ops are managed in voter manager contract */ function processVote(string memory _orgId, address _caller, uint256 _pendingOp) internal returns (bool){ return voterManager.processVote(_orgId, _caller, _pendingOp); } /** @notice returns various permissions policy related parameters * @return adminOrg admin org id * @return adminRole default network admin role * @return orgAdminRole default org admin role * @return networkBoot network boot status */ function getPolicyDetails() external view returns (string memory, string memory, string memory, bool){ return (adminOrg, adminRole, orgAdminRole, networkBoot); } /** @notice checks if the passed org exists or not * @param _orgId org id * @return true/false */ function _checkOrgExists(string memory _orgId) internal view returns (bool){ return orgManager.checkOrgExists(_orgId); } /** @notice checks if the passed org is in approved status * @param _orgId org id * @return true/false */ function checkOrgApproved(string memory _orgId) internal view returns (bool){ return orgManager.checkOrgStatus(_orgId, 2); } /** @notice checks if the passed org is in the status passed * @param _orgId org id * @param _status status to be checked for * @return true/false */ function _checkOrgStatus(string memory _orgId, uint256 _status) internal view returns (bool){ return orgManager.checkOrgStatus(_orgId, _status); } /** @notice checks if org admin account exists for the passed org id * @param _orgId org id * @return true/false */ function _checkOrgAdminExists(string memory _orgId) internal view returns (bool){ return accountManager.orgAdminExists(_orgId); } /** @notice checks if role id exists for the passed org_id * @param _roleId role id * @param _orgId org id * @return true/false */ function _roleExists(string memory _roleId, string memory _orgId) internal view returns (bool){ return roleManager.roleExists(_roleId, _orgId, _getUltimateParent(_orgId)); } /** @notice checks if the role id for the org is a voter role * @param _roleId role id * @param _orgId org id * @return true/false */ function _isVoterRole(string memory _roleId, string memory _orgId) internal view returns (bool){ return roleManager.isVoterRole(_roleId, _orgId, _getUltimateParent(_orgId)); } /** @notice returns the ultimate parent for a given org id * @param _orgId org id * @return ultimate parent org id */ function _getUltimateParent(string memory _orgId) internal view returns (string memory){ return orgManager.getUltimateParent(_orgId); } /** @notice checks if the node is allowed to connect or not * @param _enodeId enode id * @param _ip IP of node * @param _port tcp port of node * @return bool indicating if the node is allowed to connect or not */ function connectionAllowed(string calldata _enodeId, string calldata _ip, uint16 _port) external view returns (bool) { if (!networkBoot){ return true; } return nodeManager.connectionAllowed(_enodeId, _ip, _port); } /** @notice checks if the account is allowed to transact or not * @param _sender source account * @param _target target account * @param _value value being transferred * @param _gasPrice gas price * @param _gasLimit gas limit * @param _payload payload for transactions on contracts * @return bool indicating if the account is allowed to transact or not */ function transactionAllowed(address _sender, address _target, uint256 _value, uint256 _gasPrice, uint256 _gasLimit, bytes calldata _payload) external view returns (bool) { if (!networkBoot){ return true; } if (accountManager.getAccountStatus(_sender) == 2) { (string memory act_org, string memory act_role) = accountManager.getAccountOrgRole(_sender); string memory act_uOrg = _getUltimateParent(act_org); if (orgManager.checkOrgActive(act_org)) { if (isNetworkAdmin(_sender) || isOrgAdmin(_sender, act_org)) { return true; } uint256 typeOfxn = 1; if (_target == address(0)) { typeOfxn = 2; } else if (_payload.length > 0) { typeOfxn = 3; } return roleManager.transactionAllowed(act_role, act_org, act_uOrg, typeOfxn); } } return false; } }
_orgId unique id of the organization to which the account belongs/
function getPendingOp(string calldata _orgId) external view returns (string memory, string memory, address, uint256){ return voterManager.getPendingOpDetails(_orgId); }
5,379,403
./full_match/80001/0xBd99517e1994226FB8124D37087A0b835829D593/sources/contracts/Portfolio.sol
Write function to delete project Move the last element to the deleted index Clear the last element, making the array compact Reduce the array length by one
function deleteProject(uint256 _index) public onlyOwner { require(_index < _projects.length, "Invalid index"); uint256 lastIndex = _projects.length - 1; _projects[_index] = _projects[lastIndex]; delete _projects[lastIndex]; _projects.pop(); }
5,572,192
./partial_match/1/0x50f91a74da9Fa68F4b7405B36f3Db1Ce09De0D72/sources/ModerateBullZap.sol
Transfers ownership of the contract to a new account (`newOwner`)./
function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); owner = newOwner; }
4,258,099
/** * In this place you can write any text before deploy the contract in MainNet */ pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b,"Math error"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0,"Math error"); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a,"Math error"); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a,"Math error"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0,"Math error"); return a % b; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances_[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed_[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances_[msg.sender],"Invalid value"); require(_to != address(0),"Invalid address"); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances_[_from],"Value is more than balance"); require(_value <= allowed_[_from][msg.sender],"Value is more than alloved"); require(_to != address(0),"Invalid address"); balances_[_from] = balances_[_from].sub(_value); balances_[_to] = balances_[_to].add(_value); allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed_[msg.sender][_spender] = (allowed_[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed_[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed_[msg.sender][_spender] = 0; } else { allowed_[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); require(_amount <= balances_[_account],"Amount is more than balance"); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed_[_account][msg.sender],"Amount is more than alloved"); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed_[_account][msg.sender] = allowed_[_account][msg.sender].sub(_amount); _burn(_account, _amount); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value),"Transfer error"); } function safeTransferFrom( IERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value),"Tranfer error"); } function safeApprove( IERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value),"Approve error"); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable { event Paused(); event Unpaused(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused,"Contract is paused, sorry"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "Contract is running now"); _; } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Contract RESTO token * @dev ERC20 compatible token contract */ contract RESTOToken is ERC20Pausable { string public constant name = "RESTO"; string public constant symbol = "RESTO"; uint32 public constant decimals = 18; uint256 public INITIAL_SUPPLY = 1100000000 * 1 ether; // 1 100 000 000 address public CrowdsaleAddress; uint64 crowdSaleEndTime = 1544745600; // 14.12.2018 mapping (address => bool) internal kyc; constructor(address _CrowdsaleAddress) public { CrowdsaleAddress = _CrowdsaleAddress; _mint(_CrowdsaleAddress, INITIAL_SUPPLY); } modifier kyc_passed(address _investor) { if (_investor != CrowdsaleAddress){ require(kyc[_investor],"For transfer tokens you need to go through the procedure KYC"); } _; } modifier onlyOwner() { require(msg.sender == CrowdsaleAddress,"Only CrowdSale contract can run this"); _; } modifier validDestination( address to ) { require(to != address(0x0),"Empty address"); require(to != address(this),"RESTO Token address"); _; } modifier isICOover { if (msg.sender != CrowdsaleAddress){ require(now > crowdSaleEndTime,"Transfer of tokens is prohibited until the end of the ICO"); } _; } /** * @dev Override for testing address destination */ function transfer(address _to, uint256 _value) public validDestination(_to) kyc_passed(msg.sender) isICOover returns (bool) { return super.transfer(_to, _value); } /** * @dev Override for testing address destination */ function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) kyc_passed(msg.sender) isICOover returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev function set kyc bool to true * can run only from crowdsale contract * @param _investor The investor who passed the procedure KYC */ function kycPass(address _investor) public onlyOwner { kyc[_investor] = true; } /** * @dev function transfer tokens from special address to users * can run only from crowdsale contract * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromSpecialAddress(address _from, address _to, uint256 _value) public onlyOwner whenNotPaused returns (bool){ uint256 value = _value; require (value >= 1,"Min value is 1"); value = value.mul(1 ether); require (balances_[_from] >= value,"Decrease value"); balances_[_from] = balances_[_from].sub(value); balances_[_to] = balances_[_to].add(value); emit Transfer(_from, _to, value); return true; } /** * @dev called from crowdsale contract to pause, triggers stopped state * can run only from crowdsale contract */ function pause() public onlyOwner whenNotPaused { paused = true; emit Paused(); } /** * @dev called from crowdsale contract to unpause, returns to normal state * can run only from crowdsale contract */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpaused(); } function() external payable { revert("The token contract don`t receive ether"); } } /** * @title Ownable * @dev The Ownable contract has an owner and manager addresses, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public manager; address candidate; constructor() public { owner = msg.sender; manager = msg.sender; } modifier onlyOwner() { require(msg.sender == owner,"Access denied"); _; } modifier restricted() { require(msg.sender == owner || msg.sender == manager,"Access denied"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0),"Invalid address"); candidate = _newOwner; } function setManager(address _newManager) public onlyOwner { require(_newManager != address(0),"Invalid address"); manager = _newManager; } function confirmOwnership() public { require(candidate == msg.sender,"Only from candidate"); owner = candidate; delete candidate; } } contract TeamAddress1 { function() external payable { revert("The contract don`t receive ether"); } } contract TeamAddress2 { function() external payable { revert("The contract don`t receive ether"); } } contract MarketingAddress { function() external payable { revert("The contract don`t receive ether"); } } contract RetailersAddress { function() external payable { revert("The contract don`t receive ether"); } } contract ReserveAddress { function() external payable { revert("The contract don`t receive ether"); } } contract BountyAddress { function() external payable { revert("The contract don`t receive ether"); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale */ contract Crowdsale is Ownable { using SafeMath for uint256; using SafeERC20 for RESTOToken; uint256 hardCap = 50000 * 1 ether; address myAddress = this; RESTOToken public token = new RESTOToken(myAddress); uint64 crowdSaleStartTime = 1537401600; // 20.09.2018 uint64 crowdSaleEndTime = 1544745600; // 14.12.2018 //Addresses for store tokens TeamAddress1 public teamAddress1 = new TeamAddress1(); TeamAddress2 public teamAddress2 = new TeamAddress2(); MarketingAddress public marketingAddress = new MarketingAddress(); RetailersAddress public retailersAddress = new RetailersAddress(); ReserveAddress public reserveAddress = new ReserveAddress(); BountyAddress public bountyAddress = new BountyAddress(); // How many token units a buyer gets per wei. uint256 public rate; // Amount of wei raised uint256 public weiRaised; event Withdraw( address indexed from, address indexed to, uint256 amount ); event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor() public { uint256 totalTokens = token.INITIAL_SUPPLY(); /** * @dev Inicial distributing tokens to special adresses * TeamAddress1 - 4.5% * TeamAddress2 - 13.5% (hold one year) * MarketingAddress - 18% * RetailersAddress - 9% * ReserveAddress - 8% * BountyAddress - 1% */ _deliverTokens(teamAddress1, totalTokens.mul(45).div(1000)); _deliverTokens(teamAddress2, totalTokens.mul(135).div(1000)); _deliverTokens(marketingAddress, totalTokens.mul(18).div(100)); _deliverTokens(retailersAddress, totalTokens.mul(9).div(100)); _deliverTokens(reserveAddress, totalTokens.mul(8).div(100)); _deliverTokens(bountyAddress, totalTokens.div(100)); rate = 1000; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function */ function () external payable { require(msg.data.length == 0,"Only for simple payments"); buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokensPurchased( msg.sender, _beneficiary, weiAmount, tokens ); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev called by the owner to pause, triggers stopped state */ function pauseCrowdsale() public onlyOwner { token.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpauseCrowdsale() public onlyOwner { token.unpause(); } /** * @dev function set kyc bool to true * @param _investor The investor who passed the procedure KYC */ function setKYCpassed(address _investor) public restricted returns(bool){ token.kycPass(_investor); return true; } /** * @dev the function tranfer tokens from TeamAddress1 to investor * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromTeamAddress1(address _investor, uint256 _value) public restricted returns(bool){ token.transferTokensFromSpecialAddress(address(teamAddress1), _investor, _value); return true; } /** * @dev the function tranfer tokens from TeamAddress1 to investor * only after 1 year * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromTeamAddress2(address _investor, uint256 _value) public restricted returns(bool){ require (now >= (crowdSaleEndTime + 365 days), "Only after 1 year"); token.transferTokensFromSpecialAddress(address(teamAddress2), _investor, _value); return true; } /** * @dev the function tranfer tokens from MarketingAddress to investor * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromMarketingAddress(address _investor, uint256 _value) public restricted returns(bool){ token.transferTokensFromSpecialAddress(address(marketingAddress), _investor, _value); return true; } /** * @dev the function tranfer tokens from RetailersAddress to investor * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromRetailersAddress(address _investor, uint256 _value) public restricted returns(bool){ token.transferTokensFromSpecialAddress(address(retailersAddress), _investor, _value); return true; } /** * @dev the function tranfer tokens from ReserveAddress to investor * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromReserveAddress(address _investor, uint256 _value) public restricted returns(bool){ token.transferTokensFromSpecialAddress(address(reserveAddress), _investor, _value); return true; } /** * @dev the function tranfer tokens from BountyAddress to investor * @param _value is entered in whole tokens (1 = 1 token) */ function transferTokensFromBountyAddress(address _investor, uint256 _value) public restricted returns(bool){ token.transferTokensFromSpecialAddress(address(bountyAddress), _investor, _value); return true; } /** * @dev Validation of an incoming purchase. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase * Start Crowdsale 20/09/2018 - 1537401600 * Finish Crowdsale 14/12/2018 - 1544745600 * Greate pause until 01/11/2020 - 1604188800 */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view{ require(_beneficiary != address(0),"Invalid address"); require(_weiAmount != 0,"Invalid amount"); require((now > crowdSaleStartTime && now <= crowdSaleEndTime) || now > 1604188800,"At this time contract don`t sell tokens, sorry"); require(weiRaised < hardCap,"HardCap is passed, contract don`t accept ether."); } /** * @dev internal function * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Function transfer token to new investors * Access restricted owner and manager */ function transferTokens(address _newInvestor, uint256 _tokenAmount) public restricted { uint256 value = _tokenAmount; require (value >= 1,"Min _tokenAmount is 1"); value = value.mul(1 ether); _deliverTokens(_newInvestor, value); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev this function is ether converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 bonus = 0; uint256 resultAmount = _weiAmount; /** * Start PreSale 20/09/2018 - 1537401600 * Start ICO 10/10/2018 - 1539129600 * Finish ICO 14/12/2018 - 1544745600 */ if (now < 1539129600) { // Calculating bonus for PreSale period if (_weiAmount >= 100 * 1 ether) { bonus = 300; } else { bonus = 100; } } else { // Calculating bonus for ICO period if (_weiAmount >= 100 * 1 ether) { bonus = 200; } else { /** * ICO bonus UnisTimeStamp * Start date End date * 10.10.2018-16.10.2018 - 40% 1539129600 * 17.10.2018-23.10.2018 - 30% 1539734400 * 24.10.2018-31.10.2018 - 20% 1540339200 * 01.11.2018-16.11.2018 - 10% 1541030400 1542326400 */ if (now >= 1539129600 && now < 1539734400) { bonus = 40; } if (now >= 1539734400 && now < 1540339200) { bonus = 30; } if (now >= 1540339200 && now < 1541030400) { bonus = 20; } if (now >= 1541030400 && now < 1542326400) { bonus = 10; } } } if (bonus > 0) { resultAmount += _weiAmount.mul(bonus).div(100); } return resultAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function forwardFunds() public onlyOwner { uint256 transferValue = myAddress.balance.div(8); // Addresses where funds are collected address wallet1 = 0xcE3685fA1D8F7552a55F044dC8695477e705dbEd; address wallet2 = 0x1745CBBE7a986c1309006535AadA971CB1ecD7Bd; address wallet3 = 0x56c6A074b2fA480898c1c9fc6337401594F0B2BF; address wallet4 = 0xC053f9138593B109A8d83975506b7B29Feb53824; address wallet5 = 0x980F6EE9DCd0Ca5aD8e24bf47D43021bBC66b282; address wallet6 = 0x3b78a31326F8d4932295Beb0A79D7A0C50a92aE4; address wallet7 = 0x7b09024782744693E01E04A8ceb7Bc849684A423; address wallet8 = 0x2C057c64647911996b455b3338cBcEF5024d294f; wallet1.transfer(transferValue); wallet2.transfer(transferValue); wallet3.transfer(transferValue); wallet4.transfer(transferValue); wallet5.transfer(transferValue); wallet6.transfer(transferValue); wallet7.transfer(transferValue); wallet8.transfer(myAddress.balance); } function withdrawFunds (address _to, uint256 _value) public onlyOwner { require (now > crowdSaleEndTime, "CrowdSale is not finished yet. Access denied."); require (myAddress.balance >= _value,"Value is more than balance"); require(_to != address(0),"Invalid address"); _to.transfer(_value); emit Withdraw(msg.sender, _to, _value); } }
fallback function/
function () external payable { require(msg.data.length == 0,"Only for simple payments"); buyTokens(msg.sender); }
7,852,224
// Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.3.0 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/hyphen/metatx/ERC2771ContextUpgradeable.sol pragma solidity 0.8.0; /** * @dev Context variant with ERC2771 support. * Here _trustedForwarder is made internal instead of private * so it can be changed via Child contracts with a setter method. */ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable { address internal _trustedForwarder; function __ERC2771Context_init(address trustedForwarder) internal initializer { __Context_init_unchained(); __ERC2771Context_init_unchained(trustedForwarder); } function __ERC2771Context_init_unchained(address trustedForwarder) internal initializer { _trustedForwarder = trustedForwarder; } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == _trustedForwarder; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File contracts/security/Pausable.sol pragma solidity 0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Initializable, PausableUpgradeable { address private _pauser; event PauserChanged(address indexed previousPauser, address indexed newPauser); /** * @dev The pausable constructor sets the original `pauser` of the contract to the sender * account & Initializes the contract in unpaused state.. */ function __Pausable_init(address pauser) internal initializer { require(pauser != address(0), "Pauser Address cannot be 0"); __Pausable_init(); _pauser = pauser; } /** * @return true if `msg.sender` is the owner of the contract. */ function isPauser(address pauser) public view returns (bool) { return pauser == _pauser; } /** * @dev Throws if called by any account other than the pauser. */ modifier onlyPauser() { require(isPauser(msg.sender), "Only pauser is allowed to perform this operation"); _; } /** * @dev Allows the current pauser to transfer control of the contract to a newPauser. * @param newPauser The address to transfer pauserShip to. */ function changePauser(address newPauser) public onlyPauser { _changePauser(newPauser); } /** * @dev Transfers control of the contract to a newPauser. * @param newPauser The address to transfer ownership to. */ function _changePauser(address newPauser) internal { require(newPauser != address(0)); emit PauserChanged(_pauser, newPauser); _pauser = newPauser; } function renouncePauser() external virtual onlyPauser { emit PauserChanged(_pauser, address(0)); _pauser = address(0); } function pause() public onlyPauser { _pause(); } function unpause() public onlyPauser { _unpause(); } } // File contracts/hyphen/structures/TokenConfig.sol pragma solidity 0.8.0; struct TokenInfo { uint256 transferOverhead; bool supportedToken; uint256 equilibriumFee; // Percentage fee Represented in basis points uint256 maxFee; // Percentage fee Represented in basis points TokenConfig tokenConfig; } struct TokenConfig { uint256 min; uint256 max; } // File contracts/hyphen/interfaces/IExecutorManager.sol pragma solidity 0.8.0; interface IExecutorManager { function getExecutorStatus(address executor) external view returns (bool status); function getAllExecutors() external view returns (address[] memory); //Register new Executors function addExecutors(address[] calldata executorArray) external; // Register single executor function addExecutor(address executorAddress) external; //Remove registered Executors function removeExecutors(address[] calldata executorArray) external; // Remove Register single executor function removeExecutor(address executorAddress) external; } // File contracts/hyphen/interfaces/ILiquidityProviders.sol pragma solidity 0.8.0; interface ILiquidityProviders { function BASE_DIVISOR() external view returns (uint256); function initialize(address _trustedForwarder, address _lpToken) external; function addLPFee(address _token, uint256 _amount) external; function addNativeLiquidity() external; function addTokenLiquidity(address _token, uint256 _amount) external; function claimFee(uint256 _nftId) external; function getFeeAccumulatedOnNft(uint256 _nftId) external view returns (uint256); function getSuppliedLiquidityByToken(address tokenAddress) external view returns (uint256); function getTokenPriceInLPShares(address _baseToken) external view returns (uint256); function getTotalLPFeeByToken(address tokenAddress) external view returns (uint256); function getTotalReserveByToken(address tokenAddress) external view returns (uint256); function getSuppliedLiquidity(uint256 _nftId) external view returns (uint256); function increaseNativeLiquidity(uint256 _nftId) external; function increaseTokenLiquidity(uint256 _nftId, uint256 _amount) external; function isTrustedForwarder(address forwarder) external view returns (bool); function owner() external view returns (address); function paused() external view returns (bool); function removeLiquidity(uint256 _nftId, uint256 amount) external; function renounceOwnership() external; function setLiquidityPool(address _liquidityPool) external; function setLpToken(address _lpToken) external; function setWhiteListPeriodManager(address _whiteListPeriodManager) external; function sharesToTokenAmount(uint256 _shares, address _tokenAddress) external view returns (uint256); function totalLPFees(address) external view returns (uint256); function totalLiquidity(address) external view returns (uint256); function totalReserve(address) external view returns (uint256); function totalSharesMinted(address) external view returns (uint256); function transferOwnership(address newOwner) external; function whiteListPeriodManager() external view returns (address); function increaseCurrentLiquidity(address tokenAddress, uint256 amount) external; function decreaseCurrentLiquidity(address tokenAddress, uint256 amount) external; function getCurrentLiquidity(address tokenAddress) external view returns (uint256); } // File contracts/interfaces/IERC20Permit.sol pragma solidity 0.8.0; interface IERC20Detailed is IERC20Upgradeable { function name() external view returns(string memory); function decimals() external view returns(uint256); } interface IERC20Nonces is IERC20Detailed { function nonces(address holder) external view returns(uint); } interface IERC20Permit is IERC20Nonces { function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function permit(address holder, address spender, uint256 value, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external; } // File contracts/hyphen/interfaces/ITokenManager.sol pragma solidity 0.8.0; interface ITokenManager { function getEquilibriumFee(address tokenAddress) external view returns (uint256); function getMaxFee(address tokenAddress) external view returns (uint256); function changeFee( address tokenAddress, uint256 _equilibriumFee, uint256 _maxFee ) external; function tokensInfo(address tokenAddress) external view returns ( uint256 transferOverhead, bool supportedToken, uint256 equilibriumFee, uint256 maxFee, TokenConfig memory config ); function getTokensInfo(address tokenAddress) external view returns (TokenInfo memory); function getDepositConfig(uint256 toChainId, address tokenAddress) external view returns (TokenConfig memory); function getTransferConfig(address tokenAddress) external view returns (TokenConfig memory); } // File contracts/hyphen/LiquidityPool.sol // $$\ $$\ $$\ $$$$$$$\ $$\ // $$ | $$ | $$ | $$ __$$\ $$ | // $$ | $$ |$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$$\ $$ | $$ | $$$$$$\ $$$$$$\ $$ | // $$$$$$$$ |$$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ $$$$$$$ |$$ __$$\ $$ __$$\ $$ | // $$ __$$ |$$ | $$ |$$ / $$ |$$ | $$ |$$$$$$$$ |$$ | $$ | $$ ____/ $$ / $$ |$$ / $$ |$$ | // $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ ____|$$ | $$ | $$ | $$ | $$ |$$ | $$ |$$ | // $$ | $$ |\$$$$$$$ |$$$$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ | $$ | \$$$$$$ |\$$$$$$ |$$ | // \__| \__| \____$$ |$$ ____/ \__| \__| \_______|\__| \__| \__| \______/ \______/ \__| // $$\ $$ |$$ | // \$$$$$$ |$$ | // \______/ \__| // pragma solidity 0.8.0; pragma abicoder v2; contract LiquidityPoolOld is Initializable, ReentrancyGuardUpgradeable, Pausable, OwnableUpgradeable, ERC2771ContextUpgradeable { address private constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 private constant BASE_DIVISOR = 10000000000; // Basis Points * 100 for better accuracy uint256 public baseGas; IExecutorManager private executorManager; ITokenManager public tokenManager; ILiquidityProviders public liquidityProviders; struct PermitRequest { uint256 nonce; uint256 expiry; bool allowed; uint8 v; bytes32 r; bytes32 s; } mapping(bytes32 => bool) public processedHash; mapping(address => uint256) public gasFeeAccumulatedByToken; // Gas fee accumulated by token address => executor address mapping(address => mapping(address => uint256)) public gasFeeAccumulated; // Incentive Pool amount per token address mapping(address => uint256) public incentivePool; event AssetSent( address indexed asset, uint256 indexed amount, uint256 indexed transferredAmount, address target, bytes depositHash, uint256 fromChainId, uint256 lpFee, uint256 transferFee, uint256 gasFee ); event Received(address indexed from, uint256 indexed amount); event Deposit( address indexed from, address indexed tokenAddress, address indexed receiver, uint256 toChainId, uint256 amount, uint256 reward, string tag ); event GasFeeWithdraw(address indexed tokenAddress, address indexed owner, uint256 indexed amount); event TrustedForwarderChanged(address indexed forwarderAddress); event LiquidityProvidersChanged(address indexed liquidityProvidersAddress); event TokenManagerChanged(address indexed tokenManagerAddress); event EthReceived(address, uint256); // MODIFIERS modifier onlyExecutor() { require(executorManager.getExecutorStatus(_msgSender()), "Only executor is allowed"); _; } modifier onlyLiquidityProviders() { require(_msgSender() == address(liquidityProviders), "Only liquidityProviders is allowed"); _; } modifier tokenChecks(address tokenAddress) { (, bool supportedToken, , , ) = tokenManager.tokensInfo(tokenAddress); require(supportedToken, "Token not supported"); _; } function initialize( address _executorManagerAddress, address _pauser, address _trustedForwarder, address _tokenManager, address _liquidityProviders ) public initializer { require(_executorManagerAddress != address(0), "ExecutorManager cannot be 0x0"); require(_trustedForwarder != address(0), "TrustedForwarder cannot be 0x0"); require(_liquidityProviders != address(0), "LiquidityProviders cannot be 0x0"); __ERC2771Context_init(_trustedForwarder); __ReentrancyGuard_init(); __Ownable_init(); __Pausable_init(_pauser); executorManager = IExecutorManager(_executorManagerAddress); tokenManager = ITokenManager(_tokenManager); liquidityProviders = ILiquidityProviders(_liquidityProviders); baseGas = 21000; } function setTrustedForwarder(address trustedForwarder) external onlyOwner { require(trustedForwarder != address(0), "TrustedForwarder can't be 0"); _trustedForwarder = trustedForwarder; emit TrustedForwarderChanged(trustedForwarder); } function setLiquidityProviders(address _liquidityProviders) external onlyOwner { require(_liquidityProviders != address(0), "LiquidityProviders can't be 0"); liquidityProviders = ILiquidityProviders(_liquidityProviders); emit LiquidityProvidersChanged(_liquidityProviders); } function setTokenManager(address _tokenManager) external onlyOwner { require(_tokenManager != address(0), "TokenManager can't be 0"); tokenManager = ITokenManager(_tokenManager); emit TokenManagerChanged(_tokenManager); } function setBaseGas(uint128 gas) external onlyOwner { baseGas = gas; } function getExecutorManager() external view returns (address) { return address(executorManager); } function setExecutorManager(address _executorManagerAddress) external onlyOwner { require(_executorManagerAddress != address(0), "Executor Manager cannot be 0"); executorManager = IExecutorManager(_executorManagerAddress); } function getCurrentLiquidity(address tokenAddress) public view returns (uint256 currentLiquidity) { uint256 liquidityPoolBalance = liquidityProviders.getCurrentLiquidity(tokenAddress); currentLiquidity = liquidityPoolBalance - liquidityProviders.totalLPFees(tokenAddress) - gasFeeAccumulatedByToken[tokenAddress] - incentivePool[tokenAddress]; } /** * @dev Function used to deposit tokens into pool to initiate a cross chain token transfer. * @param toChainId Chain id where funds needs to be transfered * @param tokenAddress ERC20 Token address that needs to be transfered * @param receiver Address on toChainId where tokens needs to be transfered * @param amount Amount of token being transfered */ function depositErc20( uint256 toChainId, address tokenAddress, address receiver, uint256 amount, string calldata tag ) public tokenChecks(tokenAddress) whenNotPaused nonReentrant { TokenConfig memory config = tokenManager.getDepositConfig(toChainId, tokenAddress); require(config.min <= amount && config.max >= amount, "Deposit amount not in Cap limit"); require(receiver != address(0), "Receiver address cannot be 0"); require(amount != 0, "Amount cannot be 0"); address sender = _msgSender(); uint256 rewardAmount = getRewardAmount(amount, tokenAddress); if (rewardAmount != 0) { incentivePool[tokenAddress] = incentivePool[tokenAddress] - rewardAmount; } liquidityProviders.increaseCurrentLiquidity(tokenAddress, amount); SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(tokenAddress), sender, address(this), amount); // Emit (amount + reward amount) in event emit Deposit(sender, tokenAddress, receiver, toChainId, amount + rewardAmount, rewardAmount, tag); } function getRewardAmount(uint256 amount, address tokenAddress) public view returns (uint256 rewardAmount) { uint256 currentLiquidity = getCurrentLiquidity(tokenAddress); uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress); if (currentLiquidity < providedLiquidity) { uint256 liquidityDifference = providedLiquidity - currentLiquidity; if (amount >= liquidityDifference) { rewardAmount = incentivePool[tokenAddress]; } else { // Multiply by 10000000000 to avoid 0 reward amount for small amount and liquidity difference rewardAmount = (amount * incentivePool[tokenAddress] * 10000000000) / liquidityDifference; rewardAmount = rewardAmount / 10000000000; } } } /** * DAI permit and Deposit. */ function permitAndDepositErc20( address tokenAddress, address receiver, uint256 amount, uint256 toChainId, PermitRequest calldata permitOptions, string calldata tag ) external { IERC20Permit(tokenAddress).permit( _msgSender(), address(this), permitOptions.nonce, permitOptions.expiry, permitOptions.allowed, permitOptions.v, permitOptions.r, permitOptions.s ); depositErc20(toChainId, tokenAddress, receiver, amount, tag); } /** * EIP2612 and Deposit. */ function permitEIP2612AndDepositErc20( address tokenAddress, address receiver, uint256 amount, uint256 toChainId, PermitRequest calldata permitOptions, string calldata tag ) external { IERC20Permit(tokenAddress).permit( _msgSender(), address(this), amount, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s ); depositErc20(toChainId, tokenAddress, receiver, amount, tag); } /** * @dev Function used to deposit native token into pool to initiate a cross chain token transfer. * @param receiver Address on toChainId where tokens needs to be transfered * @param toChainId Chain id where funds needs to be transfered */ function depositNative( address receiver, uint256 toChainId, string calldata tag ) external payable whenNotPaused nonReentrant { require( tokenManager.getDepositConfig(toChainId, NATIVE).min <= msg.value && tokenManager.getDepositConfig(toChainId, NATIVE).max >= msg.value, "Deposit amount not in Cap limit" ); require(receiver != address(0), "Receiver address cannot be 0"); require(msg.value != 0, "Amount cannot be 0"); uint256 rewardAmount = getRewardAmount(msg.value, NATIVE); if (rewardAmount != 0) { incentivePool[NATIVE] = incentivePool[NATIVE] - rewardAmount; } liquidityProviders.increaseCurrentLiquidity(NATIVE, msg.value); emit Deposit(_msgSender(), NATIVE, receiver, toChainId, msg.value + rewardAmount, rewardAmount, tag); } function sendFundsToUser( address tokenAddress, uint256 amount, address payable receiver, bytes calldata depositHash, uint256 tokenGasPrice, uint256 fromChainId ) external nonReentrant onlyExecutor whenNotPaused { uint256 initialGas = gasleft(); TokenConfig memory config = tokenManager.getTransferConfig(tokenAddress); require(config.min <= amount && config.max >= amount, "Withdraw amount not in Cap limit"); require(receiver != address(0), "Bad receiver address"); (bytes32 hashSendTransaction, bool status) = checkHashStatus(tokenAddress, amount, receiver, depositHash); require(!status, "Already Processed"); processedHash[hashSendTransaction] = true; // uint256 amountToTransfer, uint256 lpFee, uint256 transferFeeAmount, uint256 gasFee uint256[4] memory transferDetails = getAmountToTransfer(initialGas, tokenAddress, amount, tokenGasPrice); liquidityProviders.decreaseCurrentLiquidity(tokenAddress, transferDetails[0]); if (tokenAddress == NATIVE) { (bool success, ) = receiver.call{value: transferDetails[0]}(""); require(success, "Native Transfer Failed"); } else { SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), receiver, transferDetails[0]); } emit AssetSent( tokenAddress, amount, transferDetails[0], receiver, depositHash, fromChainId, transferDetails[1], transferDetails[2], transferDetails[3] ); } /** * @dev Internal function to calculate amount of token that needs to be transfered afetr deducting all required fees. * Fee to be deducted includes gas fee, lp fee and incentive pool amount if needed. * @param initialGas Gas provided initially before any calculations began * @param tokenAddress Token address for which calculation needs to be done * @param amount Amount of token to be transfered before deducting the fee * @param tokenGasPrice Gas price in the token being transfered to be used to calculate gas fee * @return [ amountToTransfer, lpFee, transferFeeAmount, gasFee ] */ function getAmountToTransfer( uint256 initialGas, address tokenAddress, uint256 amount, uint256 tokenGasPrice ) internal returns (uint256[4] memory) { TokenInfo memory tokenInfo = tokenManager.getTokensInfo(tokenAddress); uint256 transferFeePerc = _getTransferFee(tokenAddress, amount, tokenInfo); uint256 lpFee; if (transferFeePerc > tokenInfo.equilibriumFee) { // Here add some fee to incentive pool also lpFee = (amount * tokenInfo.equilibriumFee) / BASE_DIVISOR; unchecked { incentivePool[tokenAddress] += (amount * (transferFeePerc - tokenInfo.equilibriumFee)) / BASE_DIVISOR; } } else { lpFee = (amount * transferFeePerc) / BASE_DIVISOR; } uint256 transferFeeAmount = (amount * transferFeePerc) / BASE_DIVISOR; liquidityProviders.addLPFee(tokenAddress, lpFee); uint256 totalGasUsed = initialGas + tokenInfo.transferOverhead + baseGas - gasleft(); uint256 gasFee = totalGasUsed * tokenGasPrice; gasFeeAccumulatedByToken[tokenAddress] += gasFee; gasFeeAccumulated[tokenAddress][_msgSender()] += gasFee; uint256 amountToTransfer = amount - (transferFeeAmount + gasFee); return [amountToTransfer, lpFee, transferFeeAmount, gasFee]; } function _getTransferFee( address tokenAddress, uint256 amount, TokenInfo memory tokenInfo ) private view returns (uint256 fee) { uint256 currentLiquidity = getCurrentLiquidity(tokenAddress); uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress); uint256 resultingLiquidity = currentLiquidity - amount; // Fee is represented in basis points * 10 for better accuracy uint256 numerator = providedLiquidity * tokenInfo.equilibriumFee * tokenInfo.maxFee; // F(max) * F(e) * L(e) uint256 denominator = tokenInfo.equilibriumFee * providedLiquidity + (tokenInfo.maxFee - tokenInfo.equilibriumFee) * resultingLiquidity; // F(e) * L(e) + (F(max) - F(e)) * L(r) if (denominator == 0) { fee = 0; } else { fee = numerator / denominator; } } function getTransferFee(address tokenAddress, uint256 amount) external view returns (uint256) { return _getTransferFee(tokenAddress, amount, tokenManager.getTokensInfo(tokenAddress)); } function checkHashStatus( address tokenAddress, uint256 amount, address payable receiver, bytes calldata depositHash ) public view returns (bytes32 hashSendTransaction, bool status) { hashSendTransaction = keccak256(abi.encode(tokenAddress, amount, receiver, keccak256(depositHash))); status = processedHash[hashSendTransaction]; } function withdrawErc20GasFee(address tokenAddress) external onlyExecutor whenNotPaused nonReentrant { require(tokenAddress != NATIVE, "Can't withdraw native token fee"); // uint256 gasFeeAccumulated = gasFeeAccumulatedByToken[tokenAddress]; uint256 _gasFeeAccumulated = gasFeeAccumulated[tokenAddress][_msgSender()]; require(_gasFeeAccumulated != 0, "Gas Fee earned is 0"); gasFeeAccumulatedByToken[tokenAddress] = gasFeeAccumulatedByToken[tokenAddress] - _gasFeeAccumulated; gasFeeAccumulated[tokenAddress][_msgSender()] = 0; SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), _msgSender(), _gasFeeAccumulated); emit GasFeeWithdraw(tokenAddress, _msgSender(), _gasFeeAccumulated); } function withdrawNativeGasFee() external onlyExecutor whenNotPaused nonReentrant { uint256 _gasFeeAccumulated = gasFeeAccumulated[NATIVE][_msgSender()]; require(_gasFeeAccumulated != 0, "Gas Fee earned is 0"); gasFeeAccumulatedByToken[NATIVE] = gasFeeAccumulatedByToken[NATIVE] - _gasFeeAccumulated; gasFeeAccumulated[NATIVE][_msgSender()] = 0; (bool success, ) = payable(_msgSender()).call{value: _gasFeeAccumulated}(""); require(success, "Native Transfer Failed"); emit GasFeeWithdraw(address(this), _msgSender(), _gasFeeAccumulated); } function transfer( address _tokenAddress, address receiver, uint256 _tokenAmount ) external whenNotPaused onlyLiquidityProviders nonReentrant { require(receiver != address(0), "Invalid receiver"); if (_tokenAddress == NATIVE) { require(address(this).balance >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE"); (bool success, ) = receiver.call{value: _tokenAmount}(""); require(success, "ERR__NATIVE_TRANSFER_FAILED"); } else { IERC20Upgradeable baseToken = IERC20Upgradeable(_tokenAddress); require(baseToken.balanceOf(address(this)) >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE"); SafeERC20Upgradeable.safeTransfer(baseToken, receiver, _tokenAmount); } } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } receive() external payable { emit EthReceived(_msgSender(), msg.value); } }
Fee is represented in basis points 10 for better accuracy
function _getTransferFee( address tokenAddress, uint256 amount, TokenInfo memory tokenInfo ) private view returns (uint256 fee) { uint256 currentLiquidity = getCurrentLiquidity(tokenAddress); uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress); uint256 resultingLiquidity = currentLiquidity - amount; uint256 denominator = tokenInfo.equilibriumFee * providedLiquidity + (tokenInfo.maxFee - tokenInfo.equilibriumFee) * if (denominator == 0) { fee = 0; fee = numerator / denominator; } }
12,902,929
// SPDX-License-Identifier: MI pragma solidity ^0.4.24; import "./DualSortitionSumTreeFactory.sol"; /** * @title ExposedDualSortitionSumTreeFactory * @authors [@epiqueras, @shotaronowhere] - <shawtarohgn@gmail.com> * @dev Exposed version of DualSortitionSumTreeFactory for testing. */ contract ExposedDualSortitionSumTreeFactory { /* Storage */ using DualSortitionSumTreeFactory for DualSortitionSumTreeFactory.DualSortitionSumTrees; DualSortitionSumTreeFactory.DualSortitionSumTrees internal dualSortitionSumTrees; /** * @dev Public getter for sortitionSumTrees. * @param _key The key of the tree to get. * @return All of the tree's properties. */ function _sortitionSumTrees(bytes32 _key) public view returns(uint K_draw, uint[] stackDraw, uint[] nodesDraw,uint K_set, uint[] stackSet, uint[] nodesSet, uint _threshold, uint _lastThresholdUpdate) { return ( dualSortitionSumTrees.sortitionSumDrawTrees[_key].K, dualSortitionSumTrees.sortitionSumDrawTrees[_key].stack, dualSortitionSumTrees.sortitionSumDrawTrees[_key].nodes, dualSortitionSumTrees.sortitionSumSetTrees[_key].K, dualSortitionSumTrees.sortitionSumSetTrees[_key].stack, dualSortitionSumTrees.sortitionSumSetTrees[_key].nodes, dualSortitionSumTrees.threshold, dualSortitionSumTrees.lastThresholdUpdate ); } /* Public */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K_draw The number of children each node in the draw tree should have. * @param _K_set The number of children each node in the set tree should have. */ function _createTree(bytes32 _key, uint _K_draw, uint _K_set) public { dualSortitionSumTrees.createTree(_key, _K_draw, _K_set); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. */ function _set(bytes32 _key, uint _value, bytes32 _ID) public { dualSortitionSumTrees.set(_key, _value, _ID); } /* Public Views */ /** * @dev Query the leaves of a tree. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @param _isSetTree true for Set Tree, false for Draw tree * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. */ function _queryLeafs(bytes32 _key, uint _cursor, uint _count, bool _isSetTree) public view returns(uint startIndex, uint[] values, bool hasMore) { return dualSortitionSumTrees.queryLeafs(_key, _cursor, _count, _isSetTree); } /** * @dev Draw an ID from a tree using a number. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. */ function _draw(bytes32 _key, uint _drawnNumber) public view returns(bytes32 ID) { return dualSortitionSumTrees.draw(_key, _drawnNumber); } /** @dev Gets a specified candidate's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function _stakeOf(bytes32 _key, bytes32 _ID) public view returns(uint value) { return dualSortitionSumTrees.stakeOf(_key, _ID); } }
Query the leaves of a tree. _key The key of the tree to get the leaves from. _cursor The pagination cursor. _count The number of items to return. _isSetTree true for Set Tree, false for Draw tree return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination./
function _queryLeafs(bytes32 _key, uint _cursor, uint _count, bool _isSetTree) public view returns(uint startIndex, uint[] values, bool hasMore) { return dualSortitionSumTrees.queryLeafs(_key, _cursor, _count, _isSetTree); }
12,573,206
pragma solidity ^0.4.24; import {FranklinCommon} from "./common/FranklinCommon.sol"; import {TwistedEdwards} from "./common/TwistedEdwards.sol"; // interface ExitorInterface { // function exit() external payable; // function cancelExit() external; // function startNextExitBatch() external; // function changeExitBatchFee(uint128 newBatchFee) external; // function commitExitBlock( // uint256 batchNumber, // uint24[EXIT_BATCH_SIZE] accoundIDs, // uint32 blockNumber, // bytes txDataPacked, // bytes32 newRoot // ) external; // function verifyExitBlock( // uint256 batchNumber, // uint32 blockNumber, // uint256[8] proof // ) external; // function withdrawUserBalance( // uint256 iterationsLimit // ) external; // } // this procedure is a one-time full exit with a removal // of the public key from the tree contract Exitor is FranklinCommon { function exit() public payable { uint128 userFee = scaleIntoPlasmaUnitsFromWei(msg.value); require(userFee >= currentExitBatchFee, "exit fee should be more than required by the operator"); uint24 accountID = ethereumAddressToAccountID[msg.sender]; require(accountID != 0, "empty accounts can not exit"); uint256 currentBatch = totalExitRequests/EXIT_BATCH_SIZE; // write aux info about the batch ExitBatch storage batch = exitBatches[currentBatch]; // batch countdown start from the first request if (batch.timestamp == 0) { batch.state = uint8(ExitBatchState.CREATED); batch.timestamp = uint64(block.timestamp); batch.batchFee = currentExitBatchFee; } Account storage account = accounts[accountID]; require(account.state == uint8(AccountState.REGISTERED), "only accounts that are registered and not pending exit can exit"); account.state = uint8(AccountState.PENDING_EXIT); account.exitBatchNumber = uint32(currentBatch); totalExitRequests++; emit LogExitRequest(currentBatch, accountID); } // allow users to cancel an exit if the work on the next proof is not yet started function cancelExit() public { uint24 accountID = ethereumAddressToAccountID[msg.sender]; require(accountID != 0, "trying to cancel a deposit for non-existing account"); uint256 currentBatch = totalExitRequests/EXIT_BATCH_SIZE; uint256 requestsInThisBatch = totalExitRequests % EXIT_BATCH_SIZE; // if the first request in a batch is canceled - clear it to stop the countdown if (requestsInThisBatch == 0) { delete exitBatches[currentBatch]; } Account storage account = accounts[accountID]; require(account.state == uint8(AccountState.PENDING_EXIT), "can only cancel exits for accounts that are pending exit"); require(account.exitBatchNumber == uint32(currentBatch), "can not cancel an exit in the batch that was already accepted"); account.state = uint8(AccountState.REGISTERED); account.exitBatchNumber = 0; emit LogCancelExitRequest(currentBatch, accountID); totalExitRequests--; // TODO may be return an fee that was collected } // this does not work in multi-operator mode function startNextExitBatch() public operator_only() { uint256 currentBatch = totalExitRequests/EXIT_BATCH_SIZE; uint256 inTheCurrentBatch = totalExitRequests % EXIT_BATCH_SIZE; if (inTheCurrentBatch != 0) { totalExitRequests = (currentBatch + 1) * EXIT_BATCH_SIZE; } else { revert("it's not necessary to bump the batch number"); } } // this does not work in multi-operator mode function changeExitBatchFee(uint128 newBatchFee) public operator_only() { if (currentExitBatchFee == 0) { revert("fee is already at minimum"); } if (newBatchFee < currentExitBatchFee) { currentExitBatchFee = newBatchFee; } else { revert("can not increase an exit fee"); } } // pure function to calculate commitment formats function createPublicDataCommitmentForExit(uint32 blockNumber, bytes memory txDataPacked) public pure returns (bytes32 h) { bytes32 initialHash = sha256(abi.encodePacked(uint256(blockNumber))); bytes32 finalHash = sha256(abi.encodePacked(initialHash, txDataPacked)); return finalHash; } // on commitment to some block we just commit to SOME public data, that will be parsed // ONLY when proof is presented function commitExitBlock( uint256 batchNumber, uint24[EXIT_BATCH_SIZE] memory accoundIDs, uint32 blockNumber, bytes memory txDataPacked, bytes32 newRoot ) public operator_only { require(blockNumber == lastCommittedBlockNumber + 1, "may only commit next block"); require(batchNumber == lastCommittedExitBatch, "trying to commit batch out of order"); ExitBatch storage batch = exitBatches[batchNumber]; batch.state = uint8(ExitBatchState.COMMITTED); batch.blockNumber = blockNumber; batch.timestamp = uint64(block.timestamp); bytes32 publicDataCommitment = createPublicDataCommitmentForExit(blockNumber, txDataPacked); blocks[blockNumber] = Block( uint8(Circuit.EXIT), uint64(block.timestamp + MAX_DELAY), 0, newRoot, publicDataCommitment, msg.sender ); emit BlockCommitted(blockNumber); lastCommittedBlockNumber++; lastCommittedExitBatch++; // process the block information processExitBlockData(batchNumber, blockNumber, accoundIDs, txDataPacked); } // exit block is special - to avoid storge writes an exit data is sent on verification, // but not on commitment function verifyExitBlock( uint256 batchNumber, uint32 blockNumber, uint256[8] memory proof ) public operator_only { require(lastVerifiedBlockNumber < lastCommittedBlockNumber, "no committed block to verify"); require(blockNumber == lastVerifiedBlockNumber + 1, "may only verify next block"); require(batchNumber == lastVerifiedExitBatch, "trying to prove batch out of order"); Block storage committed = blocks[blockNumber]; require(committed.circuit == uint8(Circuit.EXIT), "trying to prove the invalid circuit for this block number"); ExitBatch storage batch = exitBatches[batchNumber]; require(batch.blockNumber == blockNumber, "block number in referencing invalid batch number"); batch.state = uint8(ExitBatchState.VERIFIED); batch.timestamp = uint64(block.timestamp); // do actual verification bool verification_success = verifyProof( Circuit.EXIT, proof, lastVerifiedRoot, committed.newRoot, committed.publicDataCommitment ); require(verification_success, "invalid proof"); emit BlockVerified(blockNumber); lastVerifiedBlockNumber++; lastVerifiedExitBatch++; lastVerifiedRoot = committed.newRoot; } // transaction data is trivial: 3 bytes of in-plasma address, 16 bytes of amount // same a for partial exits - write to storage, so users can pull the balances later function processExitBlockData( uint256 batchNumber, uint32 blockNumber, uint24[EXIT_BATCH_SIZE] memory accountIDs, bytes memory txData ) internal { uint256 chunk; uint256 pointer = 32; address accountOwner; uint128 scaledAmount; uint32 tail; for (uint256 i = 0; i < EXIT_BATCH_SIZE; i++) { // this is a cheap way to ensure that all requests are unique, without O(n) MSTORE // it also automatically guarantees that all requests requests from the batch have been executed if (accountIDs[i] == 0) { continue; } require(i == 0 || accountIDs[i] > accountIDs[i-1], "accountIDs are not properly ordered"); assembly { chunk := mload(add(txData, pointer)) } pointer += 19; require(accountIDs[i] == chunk >> 232, "invalid account ID in commitment"); Account storage account = accounts[accountIDs[i]]; require(account.state == uint8(AccountState.PENDING_EXIT), "there was no such exit request"); require(account.exitBatchNumber == uint32(batchNumber), "account was registered for exit in another batch"); // accountOwner = accounts[accountIDs[i]].owner; scaledAmount = uint128(chunk << 24 >> 128); ExitLeaf memory newLeaf; tail = account.exitListTail; if (tail == 0) { // create a fresh list that is both head and tail newLeaf = ExitLeaf(0, scaledAmount); exitLeafs[account.owner][blockNumber] = newLeaf; account.exitListTail = blockNumber; } else { // previous tail is somewhere in the past ExitLeaf storage previousExitLeaf = exitLeafs[account.owner][tail]; newLeaf = ExitLeaf(0, scaledAmount); previousExitLeaf.nextID = blockNumber; exitLeafs[account.owner][blockNumber] = newLeaf; account.exitListTail = blockNumber; } // if there was no head - point to here if (account.exitListHead == 0) { account.exitListHead = blockNumber; } // exitAmounts[accountOwner][blockNumber] = scaledAmount; account.state = uint8(AccountState.UNCONFIRMED_EXIT); emit LogCompleteExit(accountOwner, blockNumber, accountIDs[i]); } } // function withdrawUserBalance( // uint32[] blockNumbers // ) // public // { // require(blockNumbers.length > 0, "requires non-empty set"); // uint256 totalAmountInWei; // uint32 blockNumber; // for (uint256 i = 0; i < blockNumbers.length; i++) { // blockNumber = blockNumbers[i]; // require(blockNumber <= lastVerifiedBlockNumber, "can only process exits from verified blocks"); // uint24 accountID = ethereumAddressToAccountID[msg.sender]; // uint128 balance; // uint256 amountInWei; // if (accountID != 0) { // // user either didn't fully exit or didn't take full exit balance yet // Account storage account = accounts[accountID]; // if (account.state == uint8(AccountState.UNCONFIRMED_EXIT)) { // uint256 batchNumber = account.exitBatchNumber; // ExitBatch storage batch = exitBatches[batchNumber]; // if (blockNumber == batch.blockNumber) { // balance = exitAmounts[msg.sender][blockNumber]; // delete accounts[accountID]; // delete ethereumAddressToAccountID[msg.sender]; // delete exitAmounts[msg.sender][blockNumber]; // amountInWei = scaleFromPlasmaUnitsIntoWei(balance); // totalAmountInWei += amountInWei; // continue; // } // } // } // // user account information is already deleted or it's not the block number where a full exit has happened // // we require a non-zero balance in this case cause chain cleanup is not required // balance = exitAmounts[msg.sender][blockNumber]; // require(balance != 0, "nothing to exit"); // delete exitAmounts[msg.sender][blockNumber]; // amountInWei = scaleFromPlasmaUnitsIntoWei(balance); // totalAmountInWei += amountInWei; // } // msg.sender.transfer(totalAmountInWei); // } function withdrawUserBalance( uint256 iterationsLimit ) public { require(iterationsLimit > 0, "must iterate"); uint256 totalAmountInWei; uint256 amountInWei; uint24 accountID = ethereumAddressToAccountID[msg.sender]; require(accountID != 0, "this should not happen as exiting happens one by one until the complete one"); Account storage account = accounts[accountID]; uint32 currentHead = account.exitListHead; uint32 nextHead = currentHead; for (uint256 i = 0; i < iterationsLimit; i++) { if (currentHead > lastVerifiedBlockNumber) { if (i == 0) { revert("nothing to process"); } else { return; } } ExitLeaf storage leaf = exitLeafs[msg.sender][currentHead]; amountInWei = scaleFromPlasmaUnitsIntoWei(leaf.amount); totalAmountInWei += amountInWei; // no matter if the next leafID is empty or not we can assign it nextHead = leaf.nextID; delete exitLeafs[msg.sender][currentHead]; if (nextHead == 0 && account.state == uint8(AccountState.UNCONFIRMED_EXIT)) { // there is no next element AND account is exiting, so it must be the complete exit leaf uint256 batchNumber = account.exitBatchNumber; ExitBatch storage batch = exitBatches[batchNumber]; require(currentHead == batch.blockNumber, "last item in the list should match the complete exit block"); delete accounts[accountID]; delete ethereumAddressToAccountID[msg.sender]; } if (nextHead == 0) { // this is an end of the list break; } else { currentHead = nextHead; } } account.exitListHead = nextHead; if (nextHead == 0) { account.exitListTail = 0; } msg.sender.transfer(totalAmountInWei); } }
pure function to calculate commitment formats
function createPublicDataCommitmentForExit(uint32 blockNumber, bytes memory txDataPacked) public pure returns (bytes32 h) { bytes32 initialHash = sha256(abi.encodePacked(uint256(blockNumber))); bytes32 finalHash = sha256(abi.encodePacked(initialHash, txDataPacked)); return finalHash; }
942,070
/** * @title: VenusAdaptor */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IAdaptor.sol"; import "../AdaptorRouter.sol"; interface CERC20 { function mint(uint256 mintAmount) external returns (uint256); function comptroller() external view returns (address); function redeem(uint256 redeemTokens) external returns (uint256); function exchangeRateStored() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function totalReserves() external view returns (uint256); function getCash() external view returns (uint256); function totalBorrows() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function interestRateModel() external view returns (address); function underlying() external view returns (address); } interface VBNB { function mint() external payable; } interface WhitePaperInterestRateModel { function getBorrowRate(uint256 cash, uint256 borrows, uint256 _reserves) external view returns (uint256, uint256); function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa) external view returns (uint256); function multiplier() external view returns (uint256); function baseRate() external view returns (uint256); function blocksPerYear() external view returns (uint256); function dsrPerBlock() external view returns (uint256); } contract VenusAdaptor is IAdaptor { using SafeERC20 for IERC20; using SafeMath for uint256; address public router; address public saver; uint256 public secondsPerBlock; event Withdraw(address token_, uint256 amount, uint256 _bamount, uint256 tokenPrice); constructor(address router_, address saver_) public { router = router_; saver = saver_; secondsPerBlock = 3; } modifier onlySaver() { require(msg.sender == saver, "Ownable: caller is not Saver"); _; } function getName() public override view returns (string memory) { return "VenusAdaptor"; } /** * Calculate next supply rate for Venus, given an `_amount` supplied */ function nextSupplyRate(address token_, uint256 _amount) external override view returns (uint256) { address cToken_ = AdaptorRouter(router).getPair(token_, getName()); CERC20 cToken = CERC20(cToken_); WhitePaperInterestRateModel white = WhitePaperInterestRateModel( CERC20(cToken_).interestRateModel() ); uint256 ratePerBlock = white.getSupplyRate( cToken.getCash().add(_amount), cToken.totalBorrows(), cToken.totalReserves(), cToken.reserveFactorMantissa() ); return ratePerBlock.div(secondsPerBlock); } /** * @return current price of cTokenLike token */ function getPriceInToken(address token_) public override view returns (uint256) { require(router != address(0), "router not found"); address cToken_ = AdaptorRouter(router).getPair(token_, getName()); require(cToken_ != address(0), "token_ target empty"); return CERC20(cToken_).exchangeRateStored(); } /** * get Amount */ function getAmount(address baseToken) external override view returns (uint256 amount) { address alpacaAddr = AdaptorRouter(router).getPair(baseToken, getName()); uint256 tokenPrice = getPriceInToken(baseToken); uint256 holdAmount = IERC20(alpacaAddr).balanceOf(address(this)); amount = tokenPrice.mul(holdAmount).div(10**18); } /** * getRate * interest rate per second, scaled by 1e18 */ function getRate(address token_) external override view returns (uint256) { address cToken_ = AdaptorRouter(router).getPair(token_, getName()); return CERC20(cToken_).supplyRatePerBlock().div(secondsPerBlock); } /** * * deposit * */ function deposit(address token_) external override payable onlySaver returns (uint256 crTokens) { require(router != address(0), "router not found"); AdaptorRouter config = AdaptorRouter(router); address cToken_ = config.getPair(token_, getName()); require(cToken_ != address(0), "token_ target empty"); uint256 balance = IERC20(token_).balanceOf(address(this)); if (balance != 0) { // if current token is wBNB, convert wBNB to BNB if (token_ == config.getWrappedNativeAddr()) { IWETH(config.getWrappedNativeAddr()).withdraw(balance); VBNB(cToken_).mint{ value: balance }(); } else { IERC20(token_).safeApprove(cToken_, balance); require(CERC20(cToken_).mint(balance) == 0, "Error minting crTokens"); } crTokens = IERC20(cToken_).balanceOf(address(this)); } } /** * * withdraw * */ function withdraw(address token_, uint256 _bamount) external override onlySaver returns (uint256 tokens) { AdaptorRouter config = AdaptorRouter(router); address cToken_ = config.getPair(token_, getName()); uint256 tokenPrice = getPriceInToken(token_); uint256 _amount = _bamount.mul(10**18).div(tokenPrice); require(CERC20(cToken_).redeem(_amount) == 0, "Error redeeming crTokens"); // if current token is wBNB, convert BNB to wBNB if (token_ == config.getWrappedNativeAddr()) { IWETH(config.getWrappedNativeAddr()).deposit{ value: _bamount }(); } IERC20 _underlying = IERC20(token_); tokens = _underlying.balanceOf(address(this)); _underlying.safeTransfer(msg.sender, tokens); emit Withdraw(token_, _amount, _bamount, tokenPrice); } /** * * Get the underlying balance on the lending protocol * */ function availableLiquidity(address token_) external override view returns (uint256) { address cToken_ = AdaptorRouter(router).getPair(token_, getName()); return CERC20(cToken_).getCash(); } fallback() external payable{} }
getRate interest rate per second, scaled by 1e18/
function getRate(address token_) external override view returns (uint256) { address cToken_ = AdaptorRouter(router).getPair(token_, getName()); return CERC20(cToken_).supplyRatePerBlock().div(secondsPerBlock); }
975,656
./partial_match/1/0xC61b9439F9C3D74011b59fe8E28cE4fffB41D3B5/sources/InvestementBeta.sol
from The sender's address. to The receiver's address. tokenId The deposit token proof id./
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { if ((to != address(0)) && (from != address(0))){ uint256 indexFrom = pendingDepositPerAddress[from].listPointer; pendingDepositPerAddress[to] = pendingDepositPerAddress[from]; pendingDepositPerAddress[from].state = Data.State.NONE; pendingDepositPerAddress[from].amount = 0; usersOnPendingDeposit[indexFrom] = to; tokenIdPerAddress[to] = tokenId; delete pendingDepositPerAddress[from]; delete tokenIdPerAddress[from]; } }
3,702,172
./partial_match/1/0x00F3823D6bf45DF3c34354CbeC54F087479A6A11/sources/MerkleClaim.sol
Allows claiming tokens if address is part of merkle tree amount of tokens owed to claimee proof merkle proof to prove address and amount are in tree Throw if not on claim period and claimDeadline reached Verify merkle proof, or revert if not in tree Throw if address has already claimed tokens Set address to claimed Send tokens to address Emit claim event
function claim(uint256 amount, bytes32[] calldata proof) external { if (block.timestamp > claimDeadline) revert ClaimDeadlineReached(); bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount)); bool isValidLeaf = MerkleProof.verify(proof, merkleRoot, leaf); if (!isValidLeaf) revert NotInMerkle(); if (hasClaimed[leaf]) revert AlreadyClaimed(); hasClaimed[leaf] = true; token.safeTransfer(msg.sender, amount); emit Claim(msg.sender, amount); }
4,157,211
./full_match/43114/0x3209D05e834AC52950dEFfec0129A853F57d4779/sources/project_/contracts/TigerMasterChef.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tigerReward = multiplier.mul(tigerPerBlock).mul(pool.allocPoint).div(totalAllocPoint); tiger.mint(devaddr, tigerReward.div(10)); tiger.mint(address(this), tigerReward); pool.accTigerPerShare = pool.accTigerPerShare.add(tigerReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
4,586,056
pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "../Governance/Claimable.sol"; import "../libraries/ERC20WithFees.sol"; /// @notice DarknodePaymentStore is responsible for tracking balances which have /// been allocated to the darknodes. It is also responsible for holding /// the tokens to be paid out to darknodes. contract DarknodePaymentStore is Claimable { using SafeMath for uint256; using SafeERC20 for ERC20; using ERC20WithFees for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address public constant ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Mapping of darknode -> token -> balance. mapping(address => mapping(address => uint256)) public darknodeBalances; /// @notice Mapping of token -> lockedAmount. mapping(address => uint256) public lockedBalances; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string memory _VERSION) public { Claimable.initialize(msg.sender); VERSION = _VERSION; } /// @notice Allow direct ETH payments to be made to the DarknodePaymentStore. function() external payable {} /// @notice Get the total balance of the contract for a particular token. /// /// @param _token The token to check balance of. /// @return The total balance of the contract. function totalBalance(address _token) public view returns (uint256) { if (_token == ETHEREUM) { return address(this).balance; } else { return ERC20(_token).balanceOf(address(this)); } } /// @notice Get the available balance of the contract for a particular token /// This is the free amount which has not yet been allocated to /// darknodes. /// /// @param _token The token to check balance of. /// @return The available balance of the contract. function availableBalance(address _token) public view returns (uint256) { return totalBalance(_token).sub( lockedBalances[_token], "DarknodePaymentStore: locked balance exceed total balance" ); } /// @notice Increments the amount of funds allocated to a particular /// darknode. /// /// @param _darknode The address of the darknode to increase balance of. /// @param _token The token which the balance should be incremented. /// @param _amount The amount that the balance should be incremented by. function incrementDarknodeBalance( address _darknode, address _token, uint256 _amount ) external onlyOwner { require(_amount > 0, "DarknodePaymentStore: invalid amount"); require( availableBalance(_token) >= _amount, "DarknodePaymentStore: insufficient contract balance" ); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][ _token ] .add(_amount); lockedBalances[_token] = lockedBalances[_token].add(_amount); } /// @notice Transfers an amount out of balance to a specified address. /// /// @param _darknode The address of the darknode. /// @param _token Which token to transfer. /// @param _amount The amount to transfer. /// @param _recipient The address to withdraw it to. function transfer( address _darknode, address _token, uint256 _amount, address payable _recipient ) external onlyOwner { require( darknodeBalances[_darknode][_token] >= _amount, "DarknodePaymentStore: insufficient darknode balance" ); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][ _token ] .sub( _amount, "DarknodePaymentStore: insufficient darknode balance for transfer" ); lockedBalances[_token] = lockedBalances[_token].sub( _amount, "DarknodePaymentStore: insufficient token balance for transfer" ); if (_token == ETHEREUM) { _recipient.transfer(_amount); } else { ERC20(_token).safeTransfer(_recipient, _amount); } } }
Transfers an amount out of balance to a specified address. _darknode The address of the darknode. _token Which token to transfer. _amount The amount to transfer. _recipient The address to withdraw it to.
function transfer( address _darknode, address _token, uint256 _amount, address payable _recipient ) external onlyOwner { require( darknodeBalances[_darknode][_token] >= _amount, "DarknodePaymentStore: insufficient darknode balance" ); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][ _token ] .sub( _amount, "DarknodePaymentStore: insufficient darknode balance for transfer" ); lockedBalances[_token] = lockedBalances[_token].sub( _amount, "DarknodePaymentStore: insufficient token balance for transfer" ); if (_token == ETHEREUM) { _recipient.transfer(_amount); ERC20(_token).safeTransfer(_recipient, _amount); } }
12,851,731
./full_match/11155111/0x89A67DaEe494C976b06d675ad7295a11aBdeC402/sources/contracts/Contract.sol
a function that shows me the leaf hash of addresses
function getLeafHash(address _claimer) public pure returns (bytes32) { return keccak256(abi.encodePacked(_claimer)); }
3,805,643
// Sources flattened with hardhat v2.3.0 https://hardhat.org // File contracts/lib/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/lib/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/lib/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/lib/Permissioned.sol abstract contract Permissioned is Ownable { using SafeMath for uint; uint public numberOfAllowedDepositors; mapping(address => bool) public allowedDepositors; event AllowDepositor(address indexed account); event RemoveDepositor(address indexed account); modifier onlyAllowedDeposits() { if (numberOfAllowedDepositors > 0) { require(allowedDepositors[msg.sender] == true, "Permissioned::onlyAllowedDeposits, not allowed"); } _; } /** * @notice Add an allowed depositor * @param depositor address */ function allowDepositor(address depositor) external onlyOwner { require(allowedDepositors[depositor] == false, "Permissioned::allowDepositor"); allowedDepositors[depositor] = true; numberOfAllowedDepositors = numberOfAllowedDepositors.add(1); emit AllowDepositor(depositor); } /** * @notice Remove an allowed depositor * @param depositor address */ function removeDepositor(address depositor) external onlyOwner { require(numberOfAllowedDepositors > 0, "Permissioned::removeDepositor, no allowed depositors"); require(allowedDepositors[depositor] == true, "Permissioned::removeDepositor, not allowed"); allowedDepositors[depositor] = false; numberOfAllowedDepositors = numberOfAllowedDepositors.sub(1); emit RemoveDepositor(depositor); } } // File contracts/interfaces/IERC20.sol interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/YakERC20.sol abstract contract YakERC20 { using SafeMath for uint256; string public name = "Yield Yak"; string public symbol = "YRT"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => mapping (address => uint256)) internal allowances; mapping (address => uint256) internal balances; bytes32 public constant DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() {} /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * It is recommended to use increaseAllowance and decreaseAllowance instead * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(amount, "transferFrom: transfer amount exceeds allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Approval implementation * @param owner The address of the account which owns tokens * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "_approve::owner zero address"); require(spender != address(0), "_approve::spender zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Transfer implementation * @param from The address of the account which owns tokens * @param to The address of the account which is receiving tokens * @param value The number of tokens that are being transferred */ function _transferTokens(address from, address to, uint256 value) internal { require(to != address(0), "_transferTokens: cannot transfer to the zero address"); balances[from] = balances[from].sub(value, "_transferTokens: transfer exceeds from balance"); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balances[to] = balances[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balances[from] = balances[from].sub(value, "_burn: burn amount exceeds from balance"); totalSupply = totalSupply.sub(value, "_burn: burn amount exceeds total supply"); emit Transfer(from, address(0), value); } /** * @notice Triggers an approval from owner to spender * @param owner The address to approve from * @param spender The address to be approved * @param value The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, "permit::expired"); bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); _validateSignedData(owner, encodeData, v, r, s); _approve(owner, spender, value); } /** * @notice Recovers address from signed data and validates the signature * @param signer Address that signed the data * @param encodeData Data signed by the address * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", getDomainSeparator(), encodeData ) ); address recoveredAddress = ecrecover(digest, v, r, s); // Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages require(recoveredAddress != address(0) && recoveredAddress == signer, "Arch::validateSig: invalid signature"); } /** * @notice EIP-712 Domain separator * @return Separator */ function getDomainSeparator() public view returns (bytes32) { return keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), VERSION_HASH, _getChainId(), address(this) ) ); } /** * @notice Current id of the chain where this contract is deployed * @return Chain id */ function _getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File contracts/YakStrategy.sol /** * @notice YakStrategy should be inherited by new strategies */ abstract contract YakStrategy is YakERC20, Ownable, Permissioned { using SafeMath for uint; uint public totalDeposits; IERC20 public depositToken; IERC20 public rewardToken; address public devAddr; uint public MIN_TOKENS_TO_REINVEST; uint public MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST; bool public DEPOSITS_ENABLED; uint public REINVEST_REWARD_BIPS; uint public ADMIN_FEE_BIPS; uint public DEV_FEE_BIPS; uint constant internal BIPS_DIVISOR = 10000; uint constant internal MAX_UINT = uint(-1); event Deposit(address indexed account, uint amount); event Withdraw(address indexed account, uint amount); event Reinvest(uint newTotalDeposits, uint newTotalSupply); event Recovered(address token, uint amount); event UpdateAdminFee(uint oldValue, uint newValue); event UpdateDevFee(uint oldValue, uint newValue); event UpdateReinvestReward(uint oldValue, uint newValue); event UpdateMinTokensToReinvest(uint oldValue, uint newValue); event UpdateMaxTokensToDepositWithoutReinvest(uint oldValue, uint newValue); event UpdateDevAddr(address oldValue, address newValue); event DepositsEnabled(bool newValue); /** * @notice Throws if called by smart contract */ modifier onlyEOA() { require(tx.origin == msg.sender, "YakStrategy::onlyEOA"); _; } /** * @notice Approve tokens for use in Strategy * @dev Should use modifier `onlyOwner` to avoid griefing */ function setAllowances() public virtual; /** * @notice Revoke token allowance * @param token address * @param spender address */ function revokeAllowance(address token, address spender) external onlyOwner { require(IERC20(token).approve(spender, 0)); } /** * @notice Deposit and deploy deposits tokens to the strategy * @dev Must mint receipt tokens to `msg.sender` * @param amount deposit tokens */ function deposit(uint amount) external virtual; /** * @notice Deposit using Permit * @dev Should revert for tokens without Permit * @param amount Amount of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external virtual; /** * @notice Deposit on behalf of another account * @dev Must mint receipt tokens to `account` * @param account address to receive receipt tokens * @param amount deposit tokens */ function depositFor(address account, uint amount) external virtual; /** * @notice Redeem receipt tokens for deposit tokens * @param amount receipt tokens */ function withdraw(uint amount) external virtual; /** * @notice Reinvest reward tokens into deposit tokens */ function reinvest() external virtual; /** * @notice Estimate reinvest reward * @return reward tokens */ function estimateReinvestReward() external view returns (uint) { uint unclaimedRewards = checkReward(); if (unclaimedRewards >= MIN_TOKENS_TO_REINVEST) { return unclaimedRewards.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); } return 0; } /** * @notice Reward tokens avialable to strategy, including balance * @return reward tokens */ function checkReward() public virtual view returns (uint); /** * @notice Estimated deposit token balance deployed by strategy, excluding balance * @return deposit tokens */ function estimateDeployedBalance() external virtual view returns (uint); /** * @notice Rescue all available deployed deposit tokens back to Strategy * @param minReturnAmountAccepted min deposit tokens to receive * @param disableDeposits bool */ function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external virtual; /** * @notice Calculate receipt tokens for a given amount of deposit tokens * @dev If contract is empty, use 1:1 ratio * @dev Could return zero shares for very low amounts of deposit tokens * @param amount deposit tokens * @return receipt tokens */ function getSharesForDepositTokens(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return amount; } return amount.mul(totalSupply).div(totalDeposits); } /** * @notice Calculate deposit tokens for a given amount of receipt tokens * @param amount receipt tokens * @return deposit tokens */ function getDepositTokensForShares(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return 0; } return amount.mul(totalDeposits).div(totalSupply); } /** * @notice Update reinvest min threshold * @param newValue threshold */ function updateMinTokensToReinvest(uint newValue) public onlyOwner { emit UpdateMinTokensToReinvest(MIN_TOKENS_TO_REINVEST, newValue); MIN_TOKENS_TO_REINVEST = newValue; } /** * @notice Update reinvest max threshold before a deposit * @param newValue threshold */ function updateMaxTokensToDepositWithoutReinvest(uint newValue) public onlyOwner { emit UpdateMaxTokensToDepositWithoutReinvest(MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST, newValue); MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST = newValue; } /** * @notice Update developer fee * @param newValue fee in BIPS */ function updateDevFee(uint newValue) public onlyOwner { require(newValue.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR); emit UpdateDevFee(DEV_FEE_BIPS, newValue); DEV_FEE_BIPS = newValue; } /** * @notice Update admin fee * @param newValue fee in BIPS */ function updateAdminFee(uint newValue) public onlyOwner { require(newValue.add(DEV_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR); emit UpdateAdminFee(ADMIN_FEE_BIPS, newValue); ADMIN_FEE_BIPS = newValue; } /** * @notice Update reinvest reward * @param newValue fee in BIPS */ function updateReinvestReward(uint newValue) public onlyOwner { require(newValue.add(ADMIN_FEE_BIPS).add(DEV_FEE_BIPS) <= BIPS_DIVISOR); emit UpdateReinvestReward(REINVEST_REWARD_BIPS, newValue); REINVEST_REWARD_BIPS = newValue; } /** * @notice Enable/disable deposits * @param newValue bool */ function updateDepositsEnabled(bool newValue) public onlyOwner { require(DEPOSITS_ENABLED != newValue); DEPOSITS_ENABLED = newValue; emit DepositsEnabled(newValue); } /** * @notice Update devAddr * @param newValue address */ function updateDevAddr(address newValue) public { require(msg.sender == devAddr); emit UpdateDevAddr(devAddr, newValue); devAddr = newValue; } /** * @notice Recover ERC20 from contract * @param tokenAddress token address * @param tokenAmount amount to recover */ function recoverERC20(address tokenAddress, uint tokenAmount) external onlyOwner { require(tokenAmount > 0); require(IERC20(tokenAddress).transfer(msg.sender, tokenAmount)); emit Recovered(tokenAddress, tokenAmount); } /** * @notice Recover AVAX from contract * @param amount amount */ function recoverAVAX(uint amount) external onlyOwner { require(amount > 0); msg.sender.transfer(amount); emit Recovered(address(0), amount); } } // File contracts/interfaces/ILydiaChef.sol interface ILydiaChef { function lyd() external view returns (address); function electrum() external view returns (address); function lydPerSec() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function startTimestamp() external view returns (uint256); function poolLength() external view returns (uint256); function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) external; function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function pendingLyd(uint256 _pid, address _user) external view returns (uint256); function massUpdatePools() external; function updatePool(uint256 _pid) external; function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function enterStaking(uint256 _amount) external; function leaveStaking(uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; function dev(address _devaddr) external; function updateEmissionRate(uint256 _lydPerSec) external; function poolInfo(uint pid) external view returns ( address lpToken, uint allocPoint, uint lastRewardTimestamp, uint accLydPerShare ); function userInfo(uint pid, address user) external view returns ( uint256 amount, uint256 rewardDebt ); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 _lydPerSec); } // File contracts/interfaces/IRouter.sol interface IRouter { function addLiquidity(address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityAVAX(address token, uint amountTokenDesired, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external payable returns (uint amountToken, uint amountAVAX, uint liquidity); function removeLiquidity(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB); function removeLiquidityAVAX(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external returns (uint amountToken, uint amountAVAX); function removeLiquidityWithPermit(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountA, uint amountB); function removeLiquidityAVAXWithPermit(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountToken, uint amountAVAX); function removeLiquidityAVAXSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external returns (uint amountAVAX); function removeLiquidityAVAXWithPermitSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountAVAX); function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapTokensForExactTokens(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactAVAXForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactAVAX(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForAVAX(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapAVAXForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactAVAXForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline) external payable; function swapExactTokensForAVAXSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) external view returns (uint[] memory amounts); } // File contracts/interfaces/IPair.sol interface IPair is IERC20 { function token0() external pure returns (address); function token1() external pure returns (address); } // File contracts/strategies/LydiaStrategyForLPa.sol /** * @notice Token0 strategy for Lydia Farms */ contract LydiaStrategyForLPa is YakStrategy { using SafeMath for uint; IRouter public router; ILydiaChef public stakingContract; address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; uint public PID; constructor( string memory _name, address _depositToken, address _rewardToken, address _stakingContract, address _router, address _timelock, uint _pid, uint _minTokensToReinvest, uint _adminFeeBips, uint _devFeeBips, uint _reinvestRewardBips ) { name = _name; depositToken = IPair(_depositToken); rewardToken = IERC20(_rewardToken); stakingContract = ILydiaChef(_stakingContract); router = IRouter(_router); PID = _pid; devAddr = msg.sender; setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } /** * @notice Approve tokens for use in Strategy * @dev Restricted to avoid griefing attacks */ function setAllowances() public override onlyOwner { depositToken.approve(address(stakingContract), MAX_UINT); rewardToken.approve(address(router), MAX_UINT); IERC20(IPair(address(depositToken)).token0()).approve(address(router), MAX_UINT); IERC20(IPair(address(depositToken)).token1()).approve(address(router), MAX_UINT); } /** * @notice Deposit tokens to receive receipt tokens * @param amount Amount of tokens to deposit */ function deposit(uint amount) external override { _deposit(msg.sender, amount); } /** * @notice Deposit using Permit * @param amount Amount of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint amount) external override { _deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "LydiaStrategyForLP::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function withdraw(uint amount) external override { uint depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); require(depositToken.transfer(msg.sender, depositTokenAmount), "LydiaStrategyForLP::withdraw"); _burn(msg.sender, amount); totalDeposits = totalDeposits.sub(depositTokenAmount); emit Withdraw(msg.sender, depositTokenAmount); } } function _withdrawDepositTokens(uint amount) private { require(amount > 0, "LydiaStrategyForLP::_withdrawDepositTokens"); stakingContract.withdraw(PID, amount); } function reinvest() external override onlyEOA { uint unclaimedRewards = checkReward(); require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "LydiaStrategyForLP::reinvest"); _reinvest(unclaimedRewards); } /** * @notice Reinvest rewards from staking contract to deposit tokens * @dev Reverts if the expected amount of tokens are not returned from `stakingContract` * @param amount deposit tokens to reinvest */ function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { require(rewardToken.transfer(devAddr, devFee), "LydiaStrategyForLP::_reinvest, dev"); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { require(rewardToken.transfer(owner(), adminFee), "LydiaStrategyForLP::_reinvest, admin"); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { require(rewardToken.transfer(msg.sender, reinvestFee), "LydiaStrategyForLP::_reinvest, reward"); } uint depositTokenAmount = _convertRewardTokensToDepositTokens( amount.sub(devFee).sub(adminFee).sub(reinvestFee) ); _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _stakeDepositTokens(uint amount) private { require(amount > 0, "LydiaStrategyForLP::_stakeDepositTokens"); stakingContract.deposit(PID, amount); } function checkReward() public override view returns (uint) { uint pendingReward = stakingContract.pendingLyd(PID, address(this)); uint contractBalance = rewardToken.balanceOf(address(this)); return pendingReward.add(contractBalance); } /** * @notice Converts reward tokens to deposit tokens * @dev Always converts through router; there are no price checks enabled * @return deposit tokens received */ function _convertRewardTokensToDepositTokens(uint amount) private returns (uint) { uint amountIn = amount.div(2); require(amountIn > 0, "LydiaStrategyForLP::_convertRewardTokensToDepositTokens"); // swap to token0 uint path0Length = 3; address[] memory path0 = new address[](path0Length); path0[0] = address(rewardToken); path0[1] = WAVAX; path0[2] = IPair(address(depositToken)).token0(); uint amountOutToken0 = amountIn; if (path0[0] != path0[path0Length - 1]) { uint[] memory amountsOutToken0 = router.getAmountsOut(amountIn, path0); amountOutToken0 = amountsOutToken0[amountsOutToken0.length - 1]; router.swapExactTokensForTokens(amountIn, amountOutToken0, path0, address(this), block.timestamp); } // swap to token1 uint path1Length = 2; address[] memory path1 = new address[](path1Length); path1[0] = path0[0]; path1[1] = IPair(address(depositToken)).token1(); uint amountOutToken1 = amountIn; if (path1[0] != path1[path1Length - 1]) { uint[] memory amountsOutToken1 = router.getAmountsOut(amountIn, path1); amountOutToken1 = amountsOutToken1[amountsOutToken1.length - 1]; router.swapExactTokensForTokens(amountIn, amountOutToken1, path1, address(this), block.timestamp); } (,,uint liquidity) = router.addLiquidity( path0[path0Length - 1], path1[path1Length - 1], amountOutToken0, amountOutToken1, 0, 0, address(this), block.timestamp ); return liquidity; } /** * @notice Estimate recoverable balance * @return deposit tokens */ function estimateDeployedBalance() external override view returns (uint) { (uint depositBalance, ) = stakingContract.userInfo(PID, address(this)); return depositBalance; } function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint balanceBefore = depositToken.balanceOf(address(this)); stakingContract.emergencyWithdraw(PID); uint balanceAfter = depositToken.balanceOf(address(this)); require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "LydiaStrategyForLP::rescueDeployedFunds"); totalDeposits = balanceAfter; emit Reinvest(totalDeposits, totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
Calculate deposit tokens for a given amount of receipt tokens amount receipt tokens return deposit tokens/
function getDepositTokensForShares(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return 0; } return amount.mul(totalDeposits).div(totalSupply); }
914,038
./partial_match/1/0xf351fda87025Ad93E7405757b5f2974dc4c02fd9/sources/DSHIBA.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Dungeon Shiba", "DSHIB") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 20; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 20; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,542,968
./full_match/1/0xa6630B22974F908a98a8139CB12Ec2EbABfbe9D4/sources/ILUS_Contract.sol
Function to blacklist any stake status true/false stakingId stake id for that particular stake/
function blacklistStake(bool status,uint256 stakingId) external onlyOwner{ _TokenTransactionstatus[stakingId] = status; }
2,955,186
./full_match/80001/0x35fd0516074d4735FEA7Ee7eDC69176B2CfCB42a/sources/contracts/bank/Bank.sol
Get the funds out - only used for bank contract migration
function withdraw(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { _setBalanceReference(token, getBalance(token) - amount); _safeTransfer(payable(msg.sender), token, amount); emit Withdraw(token, amount); }
9,453,907
./full_match/1/0xcbc0A8d5C7352Fe3625614ea343019e6d6b89031/sources/contracts/v2/templeLineOfCredit/TempleLineOfCredit.sol
Check if this account is to be liquidated given the current account, debt token and market conditions. Revert if the account has exceeded the maximum LTV/
function _checkLiquidity(AccountData storage _accountData, DebtTokenCache memory _cache) internal view { LiquidationStatus memory _status = _computeLiquidity( _accountData, _cache ); if (_status.hasExceededMaxLtv) { revert ExceededMaxLtv(_status.collateral, _status.collateralValue, _status.currentDebt); } }
5,002,859
pragma solidity ^0.5.2; import "../registry/AbstractRNS.sol"; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { AbstractRNS rns; mapping(bytes32=>address) addresses; mapping(bytes32=>bytes32) hashes; modifier only_owner(bytes32 node) { require(rns.owner(node) == msg.sender); _; } /** * Constructor. * @param rnsAddr The RNS registrar contract. */ constructor(AbstractRNS rnsAddr) public { rns = rnsAddr; } /** * Fallback function. */ function() payable external { revert(); } /** * Returns true if the specified node has the specified record type. * @param node The RNS node to query. * @param kind The record type name, as specified in EIP137. * @return True if this resolver has a record of the provided type on the * provided node. */ function has(bytes32 node, bytes32 kind) public view returns (bool) { return (kind == "addr" && addresses[node] != address(0)) || (kind == "hash" && hashes[node] != 0); } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x3b3b57de || interfaceID == 0xd8389dc5; } /** * Returns the address associated with an RNS node. * @param node The RNS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return addresses[node]; } /** * Sets the address associated with an RNS node. * May only be called by the owner of that node in the RNS registry. * @param node The node to update. * @param addrValue The address to set. */ function setAddr(bytes32 node, address addrValue) public only_owner(node) { addresses[node] = addrValue; } /** * Returns the content hash associated with an RNS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The RNS node to query. * @return The associated content hash. */ function content(bytes32 node) public view returns (bytes32) { return hashes[node]; } /** * Sets the content hash associated with an RNS node. * May only be called by the owner of that node in the RNS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) public only_owner(node) { hashes[node] = hash; } }
Returns true if the specified node has the specified record type. node The RNS node to query. kind The record type name, as specified in EIP137. return True if this resolver has a record of the provided type on the provided node./
function has(bytes32 node, bytes32 kind) public view returns (bool) { return (kind == "addr" && addresses[node] != address(0)) || (kind == "hash" && hashes[node] != 0); }
1,781,867
pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply() external constant returns (uint256 _totalSupply); function balanceOf(address _owner) external constant returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _old, uint256 _new) external returns (bool success); function allowance(address _owner, address _spender) external constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor () internal { } } library RingList { address constant NULL = 0x0; address constant HEAD = 0x0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList{ mapping (address => mapping (bool => address)) list; } /// @dev returns true if the list exists /// @param self stored linked list from contract function listExists(LinkedList storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) { return true; } else { return false; } } /// @dev returns true if the node exists /// @param self stored linked list from contract /// @param _node a node to search for function nodeExists(LinkedList storage self, address _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /// @dev Returns the number of elements in the list /// @param self stored linked list from contract function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { bool exists; address i; (exists,i) = getAdjacent(self, HEAD, NEXT); while (i != HEAD) { (exists,i) = getAdjacent(self, i, NEXT); numElements++; } return; } /// @dev Returns the links of a node as a tuple /// @param self stored linked list from contract /// @param _node id of the node to get function getNode(LinkedList storage self, address _node) internal view returns (bool, address, address) { if (!nodeExists(self,_node)) { return (false,0x0,0x0); } else { return (true,self.list[_node][PREV], self.list[_node][NEXT]); } } /// @dev Returns the link of a node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node id of the node to step from /// @param _direction direction to step in function getAdjacent(LinkedList storage self, address _node, bool _direction) internal view returns (bool, address) { if (!nodeExists(self,_node)) { return (false,0x0); } else { return (true,self.list[_node][_direction]); } } /// @dev Can be used before `insert` to build an ordered list /// @param self stored linked list from contract /// @param _node an existing node to search from, e.g. HEAD. /// @param _value value to seek /// @param _direction direction to seek in // @return next first node beyond '_node' in direction `_direction` function getSortedSpot(LinkedList storage self, address _node, address _value, bool _direction) internal view returns (address) { if (sizeOf(self) == 0) { return 0x0; } require((_node == 0x0) || nodeExists(self,_node)); bool exists; address next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0x0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /// @dev Creates a bidirectional link between two nodes on direction `_direction` /// @param self stored linked list from contract /// @param _node first node for linking /// @param _link node to link to in the _direction function createLink(LinkedList storage self, address _node, address _link, bool _direction) internal { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /// @dev Insert node `_new` beside existing node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node existing node /// @param _new new node to insert /// @param _direction direction to insert node in function insert(LinkedList storage self, address _node, address _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { address c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); return true; } else { return false; } } /// @dev removes an entry from the linked list /// @param self stored linked list from contract /// @param _node node to remove from the list function remove(LinkedList storage self, address _node) internal returns (address) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0x0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; return _node; } /// @dev pushes an enrty to the head of the linked list /// @param self stored linked list from contract /// @param _node new entry to push to the head /// @param _direction push to the head (NEXT) or tail (PREV) function push(LinkedList storage self, address _node, bool _direction) internal { insert(self, HEAD, _node, _direction); } /// @dev pops the first entry from the linked list /// @param self stored linked list from contract /// @param _direction pop from the head (NEXT) or the tail (PREV) function pop(LinkedList storage self, bool _direction) internal returns (address) { bool exists; address adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } contract UmkaToken is ERC20 { using SafeMath for uint256; using RingList for RingList.LinkedList; address public owner; bool public paused = false; bool public contractEnable = true; uint256 private summarySupply; string public name = ""; string public symbol = ""; uint8 public decimals = 0; mapping(address => uint256) private accounts; mapping(address => string) private umkaAddresses; mapping(address => mapping (address => uint256)) private allowed; mapping(address => uint8) private group; mapping(bytes32 => uint256) private distribution; RingList.LinkedList private holders; struct groupPolicy { uint8 _default; uint8 _backend; uint8 _admin; uint8 _migration; uint8 _subowner; uint8 _owner; } groupPolicy public currentState = groupPolicy(0, 3, 4, 9, 2, 9); event EvGroupChanged(address _address, uint8 _oldgroup, uint8 _newgroup); event EvMigration(address _address, uint256 _balance, uint256 _secret); event Pause(); event Unpause(); constructor (string _name, string _symbol, uint8 _decimals, uint256 _startTokens) public { owner = msg.sender; group[owner] = currentState._owner; accounts[msg.sender] = _startTokens; holders.push(msg.sender, true); summarySupply = _startTokens; name = _name; symbol = _symbol; decimals = _decimals; emit Transfer(address(0x0), msg.sender, _startTokens); } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } modifier minGroup(int _require) { require(group[msg.sender] >= _require); _; } modifier onlyGroup(int _require) { require(group[msg.sender] == _require); _; } modifier whenNotPaused() { require(!paused || group[msg.sender] >= currentState._backend); _; } modifier whenPaused() { require(paused); _; } function servicePause() minGroup(currentState._admin) whenNotPaused public { paused = true; emit Pause(); } function serviceUnpause() minGroup(currentState._admin) whenPaused public { paused = false; emit Unpause(); } function serviceGroupChange(address _address, uint8 _group) minGroup(currentState._admin) external returns(uint8) { require(_address != address(0)); uint8 old = group[_address]; if(old <= currentState._admin) { group[_address] = _group; emit EvGroupChanged(_address, old, _group); } return group[_address]; } function serviceTransferOwnership(address newOwner) minGroup(currentState._owner) external { require(newOwner != address(0)); group[newOwner] = currentState._subowner; group[msg.sender] = currentState._subowner; emit EvGroupChanged(newOwner, currentState._owner, currentState._subowner); } function serviceClaimOwnership() onlyGroup(currentState._subowner) external { address temp = owner; uint256 value = accounts[owner]; accounts[owner] = accounts[owner].sub(value); holders.remove(owner); accounts[msg.sender] = accounts[msg.sender].add(value); holders.push(msg.sender, true); owner = msg.sender; delete group[temp]; group[msg.sender] = currentState._owner; emit EvGroupChanged(msg.sender, currentState._subowner, currentState._owner); emit Transfer(temp, owner, value); } function serviceIncreaseBalance(address _who, uint256 _value) minGroup(currentState._admin) external returns(bool) { require(_who != address(0)); require(_value > 0); accounts[_who] = accounts[_who].add(_value); summarySupply = summarySupply.add(_value); holders.push(_who, true); emit Transfer(address(0), _who, _value); return true; } function serviceDecreaseBalance(address _who, uint256 _value) minGroup(currentState._admin) external returns(bool) { require(_who != address(0)); require(_value > 0); require(accounts[_who] >= _value); accounts[_who] = accounts[_who].sub(_value); summarySupply = summarySupply.sub(_value); if(accounts[_who] == 0){ holders.remove(_who); } emit Transfer(_who, address(0), _value); return true; } function serviceRedirect(address _from, address _to, uint256 _value) minGroup(currentState._admin) external returns(bool){ require(_from != address(0)); require(_to != address(0)); require(_value > 0); require(accounts[_from] >= _value); require(_from != _to); accounts[_from] = accounts[_from].sub(_value); if(accounts[_from] == 0){ holders.remove(_from); } accounts[_to] = accounts[_to].add(_value); holders.push(_to, true); emit Transfer(_from, _to, _value); return true; } function serviceTokensBurn(address _address) external minGroup(currentState._admin) returns(uint256 balance) { require(_address != address(0)); require(accounts[_address] > 0); uint256 sum = accounts[_address]; accounts[_address] = 0; summarySupply = summarySupply.sub(sum); holders.remove(_address); emit Transfer(_address, address(0), sum); return accounts[_address]; } function serviceTrasferToDist(bytes32 _to, uint256 _value) external minGroup(currentState._admin) { require(_value > 0); require(accounts[owner] >= _value); distribution[_to] = distribution[_to].add(_value); accounts[owner] = accounts[owner].sub(_value); emit Transfer(owner, address(0), _value); } function serviceTrasferFromDist(bytes32 _from, address _to, uint256 _value) external minGroup(currentState._backend) { require(_to != address(0)); require(_value > 0); require(distribution[_from] >= _value); accounts[_to] = accounts[_to].add(_value); holders.push(_to, true); distribution[_from] = distribution[_from].sub(_value); emit Transfer(address(0), _to, _value); } function getGroup(address _check) external constant returns(uint8 _group) { return group[_check]; } function getBalanceOfDist(bytes32 _of) external constant returns(uint256){ return distribution[_of]; } function getHoldersLength() external constant returns(uint256){ return holders.sizeOf(); } function getHolderLink(address _holder) external constant returns(bool, address, address){ return holders.getNode(_holder); } function getUmkaAddress(address _who) external constant returns(string umkaAddress){ return umkaAddresses[_who]; } function setUmkaAddress(string _umka) minGroup(currentState._default) whenNotPaused external{ umkaAddresses[msg.sender] = _umka; } function transfer(address _to, uint256 _value) onlyPayloadSize(64) minGroup(currentState._default) whenNotPaused external returns (bool success) { require(_to != address(0)); require (accounts[msg.sender] >= _value); accounts[msg.sender] = accounts[msg.sender].sub(_value); if(accounts[msg.sender] == 0){ holders.remove(msg.sender); } accounts[_to] = accounts[_to].add(_value); holders.push(_to, true); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(64) minGroup(currentState._default) whenNotPaused external returns (bool success) { require(_to != address(0)); require(_from != address(0)); require(_value <= accounts[_from]); require(_value <= allowed[_from][msg.sender]); accounts[_from] = accounts[_from].sub(_value); if(accounts[_from] == 0){ holders.remove(_from); } allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); accounts[_to] = accounts[_to].add(_value); holders.push(_to, true); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _old, uint256 _new) onlyPayloadSize(64) minGroup(currentState._default) whenNotPaused external returns (bool success) { require (_old == allowed[msg.sender][_spender]); require(_spender != address(0)); allowed[msg.sender][_spender] = _new; emit Approval(msg.sender, _spender, _new); return true; } function allowance(address _owner, address _spender) external constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function balanceOf(address _owner) external constant returns (uint256 balance) { if (_owner == address(0)) return accounts[msg.sender]; return accounts[_owner]; } function totalSupply() external constant returns (uint256 _totalSupply) { _totalSupply = summarySupply; } function destroy() minGroup(currentState._owner) external { selfdestruct(msg.sender); } function settingsSwitchState() external minGroup(currentState._owner) returns (bool state) { if(contractEnable) { currentState._default = 9; currentState._migration = 0; contractEnable = false; } else { currentState._default = 0; currentState._migration = 9; contractEnable = true; } return contractEnable; } function userMigration(uint256 _secrect) external minGroup(currentState._migration) returns (bool successful) { uint256 balance = accounts[msg.sender]; require (balance > 0); accounts[msg.sender] = accounts[msg.sender].sub(balance); holders.remove(msg.sender); accounts[owner] = accounts[owner].add(balance); holders.push(owner, true); emit EvMigration(msg.sender, balance, _secrect); emit Transfer(msg.sender, owner, balance); return true; } }
Creates a bidirectional link between two nodes on direction `_direction` self stored linked list from contract _node first node for linking _link node to link to in the _direction
function createLink(LinkedList storage self, address _node, address _link, bool _direction) internal { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; }
2,539,657
/** *Submitted for verification at Etherscan.io on 2019-08-09 */ pragma solidity ^0.5.8; /** * @title ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ contract IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() external view returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint); /** * Send `_value` token to `_to` from `msg.sender` * * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint _value) external returns (bool); /** * Send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint _value) external returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) external returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) external view returns (uint); } /** * @title ManagedToken interface * * Adds the following functionality to the basic ERC20 token * - Locking * - Issuing * - Burning * * #created 29/09/2017 * #author Frank Bonnet */ contract IManagedToken is IToken { /** * Returns true if the token is locked * * @return Whether the token is locked */ function isLocked() external view returns (bool); /** * Locks the token so that the transfering of value is disabled * * @return Whether the unlocking was successful or not */ function lock() external returns (bool); /** * Unlocks the token so that the transfering of value is enabled * * @return Whether the unlocking was successful or not */ function unlock() external returns (bool); /** * Issues `_value` new tokens to `_to` * * @param _to The address to which the tokens will be issued * @param _value The amount of new tokens to issue * @return Whether the tokens where sucessfully issued or not */ function issue(address _to, uint _value) external returns (bool); /** * Burns `_value` tokens of `_from` * * @param _from The address that owns the tokens to be burned * @param _value The amount of tokens to be burned * @return Whether the tokens where sucessfully burned or not */ function burn(address _from, uint _value) external returns (bool); } /** * @title Token observer interface * * Allows a token smart-contract to notify observers * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) external; } /** * @title Abstract token observer * * Allows observers to be notified by an observed token smart-contract * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract TokenObserver is ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public { onTokensReceived(msg.sender, _from, _value); } /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; } /** * @title Token retrieve interface * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ contract ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) external; } /** * @title Token retrieve * * Allows tokens to be retrieved from a contract * * #created 18/10/2017 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public { IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(address(this)); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } /** * @title Observable interface * * Allows observers to register and unregister with the * implementing smart-contract that is observable * * #created 09/10/2017 * #author Frank Bonnet */ contract IObservable { /** * Returns true if `_account` is a registered observer * * @param _account The account to test against * @return Whether the account is a registered observer */ function isObserver(address _account) external view returns (bool); /** * Gets the amount of registered observers * * @return The amount of registered observers */ function getObserverCount() external view returns (uint); /** * Gets the observer at `_index` * * @param _index The index of the observer * @return The observers address */ function getObserverAtIndex(uint _index) external view returns (address); /** * Register `_observer` as an observer * * @param _observer The account to add as an observer */ function registerObserver(address _observer) external; /** * Unregister `_observer` as an observer * * @param _observer The account to remove as an observer */ function unregisterObserver(address _observer) external; } /** * @title Ownership interface * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address); } /** * @title Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * The publisher is the inital owner */ constructor() public { owner = msg.sender; } /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner, "m:only_owner"); _; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address) { return owner; } } /** * @title Transferable ownership interface * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract ITransferableOwnership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) external; } /** * @title Transferable ownership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract TransferableOwnership is ITransferableOwnership, Ownership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } } /** * @title Multi-owned interface * * Interface that allows multiple owners * * #created 09/10/2017 * #author Frank Bonnet */ contract IMultiOwned { /** * Returns true if `_account` is an owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Returns the amount of owners * * @return The amount of owners */ function getOwnerCount() public view returns (uint); /** * Gets the owner at `_index` * * @param _index The index of the owner * @return The address of the owner found at `_index` */ function getOwnerAt(uint _index) public view returns (address); /** * Adds `_account` as a new owner * * @param _account The account to add as an owner */ function addOwner(address _account) public; /** * Removes `_account` as an owner * * @param _account The account to remove as an owner */ function removeOwner(address _account) public; } /** * @title IAuthenticator * * Authenticator interface * * #created 15/10/2017 * #author Frank Bonnet */ contract IAuthenticator { /** * Authenticate * * Returns whether `_account` is authenticated or not * * @param _account The account to authenticate * @return whether `_account` is successfully authenticated */ function authenticate(address _account) public view returns (bool); } /** * @title Dcorp Dissolvement Proposal * * Serves as a placeholder for the Dcorp funds, allowing the community the ability * to claim their part of the ether. * * This contact is deployed upon receiving the Ether that is currently held by the previous proxy contract. * * #created 18/7/2019 * #author Frank Bonnet */ contract DcorpDissolvementProposal is TokenObserver, TransferableOwnership, TokenRetriever { enum Stages { Deploying, Deployed, Executed } struct Balance { uint drps; uint drpu; uint index; } // State Stages private stage; // Settings uint public constant CLAIMING_DURATION = 60 days; uint public constant WITHDRAW_DURATION = 60 days; uint public constant DISSOLVEMENT_AMOUNT = 948 ether; // +- 150000 euro // Alocated balances mapping (address => Balance) private allocated; address[] private allocatedIndex; // Whitelist IAuthenticator public authenticator; // Tokens IToken public drpsToken; IToken public drpuToken; // Previous proxy address public prevProxy; uint public prevProxyRecordedBalance; // Dissolvement address payable public dissolvementFund; uint public claimTotalWeight; uint public claimTotalEther; uint public claimDeadline; uint public withdrawDeadline; /** * Require that the sender is authentcated */ modifier only_authenticated() { require(authenticator.authenticate(msg.sender), "m:only_authenticated"); _; } /** * Require that the contract is in `_stage` */ modifier only_at_stage(Stages _stage) { require(stage == _stage, "m:only_at_stage"); _; } /** * Require `_token` to be one of the drp tokens * * @param _token The address to test against */ modifier only_accepted_token(address _token) { require(_token == address(drpsToken) || _token == address(drpuToken), "m:only_accepted_token"); _; } /** * Require that `_token` is not one of the drp tokens * * @param _token The address to test against */ modifier not_accepted_token(address _token) { require(_token != address(drpsToken) && _token != address(drpuToken), "m:not_accepted_token"); _; } /** * Require that sender has more than zero tokens */ modifier only_token_holder() { require(allocated[msg.sender].drps > 0 || allocated[msg.sender].drpu > 0, "m:only_token_holder"); _; } /** * Require that the claiming period for the proposal has * not yet ended */ modifier only_during_claiming_period() { require(claimDeadline > 0 && now <= claimDeadline, "m:only_during_claiming_period"); _; } /** * Require that the claiming period for the proposal has ended */ modifier only_after_claiming_period() { require(claimDeadline > 0 && now > claimDeadline, "m:only_after_claiming_period"); _; } /** * Require that the withdraw period for the proposal has * not yet ended */ modifier only_during_withdraw_period() { require(withdrawDeadline > 0 && now <= withdrawDeadline, "m:only_during_withdraw_period"); _; } /** * Require that the withdraw period for the proposal has ended */ modifier only_after_withdraw_period() { require(withdrawDeadline > 0 && now > withdrawDeadline, "m:only_after_withdraw_period"); _; } /** * Construct the proxy * * @param _authenticator Whitelist * @param _drpsToken The new security token * @param _drpuToken The new utility token * @param _prevProxy Proxy accepts and requires ether from the prev proxy * @param _dissolvementFund Ether to be used for the dissolvement of DCORP */ constructor(address _authenticator, address _drpsToken, address _drpuToken, address _prevProxy, address payable _dissolvementFund) public { authenticator = IAuthenticator(_authenticator); drpsToken = IToken(_drpsToken); drpuToken = IToken(_drpuToken); prevProxy = _prevProxy; prevProxyRecordedBalance = _prevProxy.balance; dissolvementFund = _dissolvementFund; stage = Stages.Deploying; } /** * Returns whether the proposal is being deployed * * @return Whether the proposal is in the deploying stage */ function isDeploying() public view returns (bool) { return stage == Stages.Deploying; } /** * Returns whether the proposal is deployed. The proposal is deployed * when it receives Ether from the prev proxy contract * * @return Whether the proposal is deployed */ function isDeployed() public view returns (bool) { return stage == Stages.Deployed; } /** * Returns whether the proposal is executed * * @return Whether the proposal is deployed */ function isExecuted() public view returns (bool) { return stage == Stages.Executed; } /** * Accept eth from the prev proxy while deploying */ function () external payable only_at_stage(Stages.Deploying) { require(msg.sender == address(prevProxy), "f:fallback;e:invalid_sender"); } /** * Deploy the proposal */ function deploy() public only_owner only_at_stage(Stages.Deploying) { require(address(this).balance >= prevProxyRecordedBalance, "f:deploy;e:invalid_balance"); // Mark deployed stage = Stages.Deployed; // Start claiming period claimDeadline = now + CLAIMING_DURATION; // Remove prev proxy as observer IObservable(address(drpsToken)).unregisterObserver(prevProxy); IObservable(address(drpuToken)).unregisterObserver(prevProxy); // Register this proxy as observer IObservable(address(drpsToken)).registerObserver(address(this)); IObservable(address(drpuToken)).registerObserver(address(this)); // Transfer dissolvement funds uint amountToTransfer = DISSOLVEMENT_AMOUNT; if (amountToTransfer > address(this).balance) { amountToTransfer = address(this).balance; } dissolvementFund.transfer(amountToTransfer); } /** * Returns the combined total supply of all drp tokens * * @return The combined total drp supply */ function getTotalSupply() public view returns (uint) { uint sum = 0; sum += drpsToken.totalSupply(); sum += drpuToken.totalSupply(); return sum; } /** * Returns true if `_owner` has a balance allocated * * @param _owner The account that the balance is allocated for * @return True if there is a balance that belongs to `_owner` */ function hasBalance(address _owner) public view returns (bool) { return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index]; } /** * Get the allocated drps or drpu token balance of `_owner` * * @param _token The address to test against * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated drps token balance */ function balanceOf(address _token, address _owner) public view returns (uint) { uint balance = 0; if (address(drpsToken) == _token) { balance = allocated[_owner].drps; } else if (address(drpuToken) == _token) { balance = allocated[_owner].drpu; } return balance; } /** * Executes the proposal * * Dissolves DCORP Decentralized and allows the ether to be withdrawn * * Should only be called after the claiming period */ function execute() public only_at_stage(Stages.Deployed) only_after_claiming_period { // Mark as executed stage = Stages.Executed; withdrawDeadline = now + WITHDRAW_DURATION; // Remaining balance is claimable claimTotalEther = address(this).balance; // Disable tokens IManagedToken(address(drpsToken)).lock(); IManagedToken(address(drpuToken)).lock(); // Remove self token as owner IMultiOwned(address(drpsToken)).removeOwner(address(this)); IMultiOwned(address(drpuToken)).removeOwner(address(this)); } /** * Allows an account to claim ether during the claiming period */ function withdraw() public only_at_stage(Stages.Executed) only_during_withdraw_period only_token_holder only_authenticated { Balance storage b = allocated[msg.sender]; uint weight = b.drpu + _convertDrpsWeight(b.drps); // Mark claimed b.drpu = 0; b.drps = 0; // Transfer amount uint amountToTransfer = weight * claimTotalEther / claimTotalWeight; msg.sender.transfer(amountToTransfer); } /** * Event handler that initializes the token conversion * * Called by `_token` when a token amount is received on * the address of this token changer * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal only_during_claiming_period only_accepted_token(_token) { require(_token == msg.sender, "f:onTokensReceived;e:only_receiving_token"); // Allocate tokens if (!hasBalance(_from)) { allocated[_from] = Balance( 0, 0, allocatedIndex.push(_from) - 1); } Balance storage b = allocated[_from]; if (_token == address(drpsToken)) { b.drps += _value; claimTotalWeight += _convertDrpsWeight(_value); } else { b.drpu += _value; claimTotalWeight += _value; } } /** * Failsafe mechanism * * Allows the owner to retrieve ether from the contract that was not claimed * within the claiming period. */ function retrieveEther() public only_owner only_after_withdraw_period { selfdestruct(msg.sender); } /** * Failsafe mechanism * * Allows the owner to retrieve tokens (other than DRPS and DRPU tokens) from the contract that * might have been send there by accident * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public only_owner not_accepted_token(_tokenContract) { super.retrieveTokens(_tokenContract); } /** * Converts the weight for DRPS tokens * * @param _value The amount of tokens to convert */ function _convertDrpsWeight(uint _value) private pure returns (uint) { return _value * 2; } }
Returns whether the proposal is being deployed return Whether the proposal is in the deploying stage/
function isDeploying() public view returns (bool) { return stage == Stages.Deploying; }
997,021
pragma solidity ^0.4.24; /// @author David Li <davidli012345@gmail.com> /// @dev basic authentication contract /// @notice tracks list of all users contract Authentication { struct User { bytes32 name; uint256 created_at; } event UserCreated(address indexed _address, bytes32 _name, uint256 _created_at); event UserUpdated(address indexed _address, bytes32 _name); event UserDeleted(address indexed _address); mapping (address => User) private users; // public array that contains list of all users that have registered address[] public allUsers; modifier onlyExistingUser { // Check if user exists or terminate require(!(users[msg.sender].name == 0x0)); _; } modifier onlyValidName(bytes32 name) { // Only valid names allowed require(!(name == 0x0)); _; } /// @return username function login() public view onlyExistingUser returns (bytes32) { return (users[msg.sender].name); } /// @param name the username to be created. /// @dev checks if user exists /// If yes return user name /// If no, check if name was sent /// If yes, create and return user /// @return username of created user function signup(bytes32 name) public payable onlyValidName(name) returns (bytes32) { if (users[msg.sender].name == 0x0) { users[msg.sender].name = name; users[msg.sender].created_at = now; allUsers.push(msg.sender); emit UserCreated(msg.sender,name,now); return (users[msg.sender].name); } return (users[msg.sender].name); } /// @param name updating username /// @dev updating user name /// @return updated username function update(bytes32 name) public payable onlyValidName(name) onlyExistingUser returns (bytes32) { // Update user name. if (users[msg.sender].name != 0x0) { users[msg.sender].name = name; emit UserUpdated(msg.sender,name); return (users[msg.sender].name); } } /// @dev destroy existing username function destroy () public onlyExistingUser { delete users[msg.sender]; emit UserDeleted(msg.sender); } }
name updating username updating user name return updated username Update user name.
function update(bytes32 name) public payable onlyValidName(name) onlyExistingUser returns (bytes32) { if (users[msg.sender].name != 0x0) { users[msg.sender].name = name; emit UserUpdated(msg.sender,name); return (users[msg.sender].name); } }
15,870,665
/** *Submitted for verification at Etherscan.io on 2021-02-16 */ /* https://powerpool.finance/ wrrrw r wrr ppwr rrr wppr0 prwwwrp prwwwrp wr0 rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0 rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0 r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0 prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0 wrr ww0rrrr */ // SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/balancer-core/BConst.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BConst { uint public constant BONE = 10**18; // Minimum number of tokens in the pool uint public constant MIN_BOUND_TOKENS = 2; // Maximum number of tokens in the pool uint public constant MAX_BOUND_TOKENS = 9; // Minimum swap fee uint public constant MIN_FEE = BONE / 10**6; // Maximum swap fee uint public constant MAX_FEE = BONE / 10; // Minimum weight for token uint public constant MIN_WEIGHT = 1000000000; // Maximum weight for token uint public constant MAX_WEIGHT = BONE * 50; // Maximum total weight uint public constant MAX_TOTAL_WEIGHT = BONE * 50; // Minimum balance for a token uint public constant MIN_BALANCE = BONE / 10**12; // Initial pool tokens supply uint public constant INIT_POOL_SUPPLY = BONE * 100; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint public constant BPOW_PRECISION = BONE / 10**10; // Maximum input tokens balance ratio for swaps. uint public constant MAX_IN_RATIO = BONE / 2; // Maximum output tokens balance ratio for swaps. uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // File: contracts/balancer-core/BNum.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BNum is BConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "ERR_DIV_ZERO"); return a / b; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // File: contracts/balancer-core/BToken.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BTokenBase is BNum { mapping(address => uint) internal _balance; mapping(address => mapping(address=>uint)) internal _allowance; uint internal _totalSupply; event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function _mint(uint amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint amt) internal { require(_balance[address(this)] >= amt, "ERR_INSUFFICIENT_BAL"); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move(address src, address dst, uint amt) internal { require(_balance[src] >= amt, "ERR_INSUFFICIENT_BAL"); _validateAddress(src); _validateAddress(dst); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint amt) internal { _move(address(this), to, amt); } function _pull(address from, uint amt) internal { _move(from, address(this), amt); } function _validateAddress(address addr) internal { require(addr != address(0), "ERR_NULL_ADDRESS"); } } contract BToken is BTokenBase, IERC20 { string internal _name; string internal _symbol; uint8 private _decimals; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns(uint8) { return 18; } function allowance(address src, address dst) external override view returns (uint) { return _allowance[src][dst]; } function balanceOf(address whom) external override view returns (uint) { return _balance[whom]; } function totalSupply() public override view returns (uint) { return _totalSupply; } function approve(address dst, uint amt) external override returns (bool) { _validateAddress(dst); _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint amt) external returns (bool) { _validateAddress(dst); _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint amt) external returns (bool) { _validateAddress(dst); uint oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint amt) external override returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom(address src, address dst, uint amt) external override returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender], "ERR_BTOKEN_BAD_CALLER"); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(src, msg.sender, _allowance[src][msg.sender]); } return true; } } // File: contracts/interfaces/BMathInterface.sol pragma solidity 0.6.12; interface BMathInterface { function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); } // File: contracts/balancer-core/BMath.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BMath is BConst, BNum, BMathInterface { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) public pure virtual returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure virtual returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure virtual override returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure virtual returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) public pure virtual override returns (uint tokenAmountIn) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - pAi \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure virtual returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint newPoolSupply = bsub(poolSupply, poolAmountIn); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight // // sF = swapFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) public pure virtual returns (uint poolAmountIn) { // charge swap fee on the output token side uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint zoo = bsub(BONE, normalizedWeight); uint zar = bmul(zoo, swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountIn = bsub(poolSupply, newPoolSupply); return poolAmountIn; } } // File: contracts/interfaces/IPoolRestrictions.sol pragma solidity 0.6.12; interface IPoolRestrictions { function getMaxTotalSupply(address _pool) external view returns (uint256); function isVotingSignatureAllowed(address _votingAddress, bytes4 _signature) external view returns (bool); function isVotingSenderAllowed(address _votingAddress, address _sender) external view returns (bool); function isWithoutFee(address _addr) external view returns (bool); } // File: contracts/interfaces/BPoolInterface.sol pragma solidity 0.6.12; interface BPoolInterface is IERC20, BMathInterface { function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function swapExactAmountIn( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function swapExactAmountOut( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function joinswapExternAmountIn( address, uint256, uint256 ) external returns (uint256); function joinswapPoolAmountOut( address, uint256, uint256 ) external returns (uint256); function exitswapPoolAmountIn( address, uint256, uint256 ) external returns (uint256); function exitswapExternAmountOut( address, uint256, uint256 ) external returns (uint256); function getDenormalizedWeight(address) external view returns (uint256); function getBalance(address) external view returns (uint256); function getSwapFee() external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCommunityFee() external view returns ( uint256, uint256, uint256, address ); function calcAmountWithCommunityFee( uint256, uint256, address ) external view returns (uint256, uint256); function getRestrictions() external view returns (address); function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function setSwapFee(uint256) external; function setCommunityFeeAndReceiver( uint256, uint256, uint256, address ) external; function setController(address) external; function setPublicSwap(bool) external; function finalize() external; function bind( address, uint256, uint256 ) external; function rebind( address, uint256, uint256 ) external; function unbind(address) external; function gulp(address) external; function callVoting( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; function getMinWeight() external view returns (uint256); function getMaxBoundTokens() external view returns (uint256); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/balancer-core/BPool.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.12; contract BPool is BToken, BMath, BPoolInterface { using SafeERC20 for IERC20; struct Record { bool bound; // is token bound to pool uint index; // private uint denorm; // denormalized weight uint balance; } /* ========== EVENTS ========== */ /** @dev Emitted when tokens are swapped. */ event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); /** @dev Emitted when underlying tokens are deposited for pool tokens. */ event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn ); /** @dev Emitted when pool tokens are burned for underlying. */ event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); /** @dev Emitted on calling any method with `_logs_` modifier. */ event LOG_CALL( bytes4 indexed sig, address indexed caller, bytes data ) anonymous; /** @dev Emitted on calling external voting contract. */ event LOG_CALL_VOTING( address indexed voting, bool indexed success, bytes4 indexed inputSig, bytes inputData, bytes outputData ); /** @dev Emitted on taking community fee. */ event LOG_COMMUNITY_FEE( address indexed caller, address indexed receiver, address indexed token, uint256 tokenAmount ); /* ========== Modifiers ========== */ modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } modifier _lock_() { _preventReentrancy(); _mutex = true; _; _mutex = false; } modifier _viewlock_() { _preventReentrancy(); _; } /* ========== Storage ========== */ bool private _mutex; // CONTROLLER contract. Able to modify swap fee, swap community fee, // community entree fee, community exit fee, // change token weights, bind, unbind and rebind tokens, // set wrapper contract, enable wrapper mode, change CONTROLLER. address internal _controller; // True if PUBLIC can call SWAP & JOIN functions bool private _publicSwap; // Address of contract which wraps pool operations: // join, exit and swaps. address private _wrapper; // Restriction to execute pool operations only from wrapper contract. // True if only wrapper can execute pool operations. bool private _wrapperMode; // Contract for getting restrictions: // Max total supply and voting calls. IPoolRestrictions private _restrictions; // `setSwapFee` require CONTROLLER uint private _swapFee; // `_communitySwapFee`, `_communityJoinFee`, `_communityExitFee` // defines the commissions sent to `_communityFeeReceiver` uint private _communitySwapFee; uint private _communityJoinFee; uint private _communityExitFee; // Community commission contract. Collects // `_communitySwapFee`, `_communityJoinFee`, `_communityExitFee` // for voting in underlying protocols, receiving rewards. address private _communityFeeReceiver; // `finalize` require CONTROLLER // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` bool private _finalized; // Array of underlying pool tokens. address[] internal _tokens; // Pool's underlying tokens Internal records. mapping(address => Record) internal _records; // Total pool's denormalized weight. uint internal _totalWeight; // Last block when account address made a swap. mapping(address => uint256) internal _lastSwapBlock; constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _controller = msg.sender; _swapFee = MIN_FEE; _communitySwapFee = 0; _communityJoinFee = 0; _communityExitFee = 0; _publicSwap = false; _finalized = false; } /* ========== Token Queries ========== */ /** * @notice Check if a token is bound to the pool. * @param t Token contracts address. * @return TRUE if the token is bounded, FALSE - if not. */ function isBound(address t) external view override returns (bool) { return _records[t].bound; } /** * @notice Get the number of tokens bound to the pool. * @return bound tokens number. */ function getNumTokens() external view returns (uint) { return _tokens.length; } /** * @notice Get all bound tokens. * @return tokens - bound token address array. */ function getCurrentTokens() external view override _viewlock_ returns (address[] memory tokens) { return _tokens; } /** * @notice Get all bound tokens with a finalization check. * @return tokens - bound token address array. */ function getFinalTokens() external view override _viewlock_ returns (address[] memory tokens) { _requireContractIsFinalized(); return _tokens; } /** * @notice Returns the denormalized weight of a bound token. * @param token Token contract address. * @return Bound token denormalized weight. */ function getDenormalizedWeight(address token) external view override _viewlock_ returns (uint) { _requireTokenIsBound(token); return _getDenormWeight(token); } /** * @notice Get the total denormalized weight of the pool. * @return Total denormalized weight of all bound tokens. */ function getTotalDenormalizedWeight() external view override _viewlock_ returns (uint) { return _getTotalWeight(); } /** * @notice Returns the normalized weight of a bound token. * @param token Token contract address. * @return Bound token normalized weight. */ function getNormalizedWeight(address token) external view _viewlock_ returns (uint) { _requireTokenIsBound(token); return bdiv(_getDenormWeight(token), _getTotalWeight()); } /** * @notice Returns the stored balance of a bound token. * @param token Token contract address. * @return Bound token balance */ function getBalance(address token) external view override _viewlock_ returns (uint) { _requireTokenIsBound(token); return _records[token].balance; } /* ========== Config Queries ========== */ /** * @notice Check if tokens swap and joining the pool allowed. * @return TRUE if allowed, FALSE if not. */ function isPublicSwap() external view override returns (bool) { return _publicSwap; } /** * @notice Check if pool is finalized. * @return TRUE if finalized, FALSE if not. */ function isFinalized() external view override returns (bool) { return _finalized; } /** * @notice Returns the swap fee rate. * @return pool's swap fee rate. */ function getSwapFee() external view override _viewlock_ returns (uint) { return _swapFee; } /** * @notice Returns the community fee rate and community fee receiver. * @return communitySwapFee - community swap fee rate. * @return communityJoinFee - community join fee rate. * @return communityExitFee - community exit fee rate. * @return communityFeeReceiver - community fee receiver address. */ function getCommunityFee() external view override _viewlock_ returns (uint communitySwapFee, uint communityJoinFee, uint communityExitFee, address communityFeeReceiver) { return (_communitySwapFee, _communityJoinFee, _communityExitFee, _communityFeeReceiver); } /** * @notice Returns the controller address. * @return controller contract address. */ function getController() external view _viewlock_ returns (address) { return _controller; } /** * @notice Returns the wrapper address. * @return pool wrapper contract address. */ function getWrapper() external view _viewlock_ returns (address) { return _wrapper; } /** * @notice Check if wrapper mode is enabled. * @return TRUE if wrapper mode enabled, FALSE if not. */ function getWrapperMode() external view _viewlock_ returns (bool) { return _wrapperMode; } /** * @notice Returns the restrictions contract address. * @return pool restrictions contract address. */ function getRestrictions() external view override _viewlock_ returns (address) { return address(_restrictions); } /* ========== Configuration Actions ========== */ /** * @notice Set the swap fee. * @dev Swap fee must be between 0.0001% and 10%. * @param swapFee swap fee left in the pool. */ function setSwapFee(uint swapFee) external override _logs_ _lock_ { _onlyController(); _requireFeeInBounds(swapFee); _swapFee = swapFee; } /** * @notice Set the community fee and community fee receiver. * @dev Community fee must be between 0.0001% and 10%. * @param communitySwapFee Fee for Community treasury from each swap * @param communityJoinFee Fee for Community treasury from each join. * @param communityExitFee Fee for Community treasury from each exit. * @param communityFeeReceiver Community treasury contract address. */ function setCommunityFeeAndReceiver( uint communitySwapFee, uint communityJoinFee, uint communityExitFee, address communityFeeReceiver ) external override _logs_ _lock_ { _onlyController(); _requireFeeInBounds(communitySwapFee); _requireFeeInBounds(communityJoinFee); _requireFeeInBounds(communityExitFee); _communitySwapFee = communitySwapFee; _communityJoinFee = communityJoinFee; _communityExitFee = communityExitFee; _communityFeeReceiver = communityFeeReceiver; } /** * @notice Set the restrictions contract address. * @param restrictions Pool's restrictions contract. */ function setRestrictions(IPoolRestrictions restrictions) external _logs_ _lock_ { _onlyController(); _restrictions = restrictions; } /** * @notice Set the controller address. * @param manager New controller contract address. */ function setController(address manager) external override _logs_ _lock_ { _onlyController(); _controller = manager; } /** * @notice Activates public swap. * @dev Possible only when pool is not finalized. * @param public_ boolean variable, TRUE if active, FALSE if not. */ function setPublicSwap(bool public_) external override _logs_ _lock_ { _requireContractIsNotFinalized(); _onlyController(); _publicSwap = public_; } /** * @notice Set the wrapper contract address and mode. * @param wrapper Wrapper contract address. * @param wrapperMode TRUE if enabled, FALSE if disabled. */ function setWrapper(address wrapper, bool wrapperMode) external _logs_ _lock_ { _onlyController(); _wrapper = wrapper; _wrapperMode = wrapperMode; } /** * @notice Finalize the pool, enable swaps, mint pool share token. */ function finalize() external override _logs_ _lock_ { _onlyController(); _requireContractIsNotFinalized(); require(_tokens.length >= MIN_BOUND_TOKENS, "MIN_TOKENS"); _finalized = true; _publicSwap = true; _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(msg.sender, INIT_POOL_SUPPLY); } /* ========== Voting Management Actions ========== */ /** * @notice Call target external contract with provided signature and data. * @param voting Destination contract address. * @param signature Destination contract method signature. * @param args Arguments of the called method. * @param value Transaction value. * @dev Can call only controller contract. Checks if destination address and signature allowed. */ function callVoting(address voting, bytes4 signature, bytes calldata args, uint256 value) external override _logs_ _lock_ { require(_restrictions.isVotingSignatureAllowed(voting, signature), "NOT_ALLOWED_SIG"); _onlyController(); (bool success, bytes memory data) = voting.call{ value: value }(abi.encodePacked(signature, args)); require(success, "NOT_SUCCESS"); emit LOG_CALL_VOTING(voting, success, signature, args, data); } /* ========== Token Management Actions ========== */ /** * @notice Bind a token with depositing initial balance. * @param token Address of the token to bind. * @param balance Initial token balance. * @param denorm Token denormalized weight. */ function bind(address token, uint balance, uint denorm) public override virtual _logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does { _onlyController(); require(!_records[token].bound, "IS_BOUND"); require(_tokens.length < MAX_BOUND_TOKENS, "MAX_TOKENS"); _records[token] = Record({ bound: true, index: _tokens.length, denorm: 0, // balance and denorm will be validated balance: 0 // and set by `rebind` }); _tokens.push(token); rebind(token, balance, denorm); } /** * @notice Rebind token with changing balance and denormalized weight. * @param token Address of the token to rebind. * @param balance New token balance. * @param denorm Desired weight for the token. */ function rebind(address token, uint balance, uint denorm) public override virtual _logs_ _lock_ { _onlyController(); _requireTokenIsBound(token); require(denorm >= MIN_WEIGHT && denorm <= MAX_WEIGHT, "WEIGHT_BOUNDS"); require(balance >= MIN_BALANCE, "MIN_BALANCE"); // Adjust the denorm and totalWeight uint oldWeight = _records[token].denorm; if (denorm > oldWeight) { _addTotalWeight(bsub(denorm, oldWeight)); } else if (denorm < oldWeight) { _subTotalWeight(bsub(oldWeight, denorm)); } _records[token].denorm = denorm; // Adjust the balance record and actual token balance uint oldBalance = _records[token].balance; _records[token].balance = balance; if (balance > oldBalance) { _pullUnderlying(token, msg.sender, bsub(balance, oldBalance)); } else if (balance < oldBalance) { uint tokenBalanceWithdrawn = bsub(oldBalance, balance); _pushUnderlying(token, msg.sender, tokenBalanceWithdrawn); } } /** * @notice Remove a token from the pool. * @dev Replaces the address in the tokens array with the last address, then removes it from the array. * @param token Bound token address. */ function unbind(address token) public override virtual _logs_ _lock_ { _onlyController(); _requireTokenIsBound(token); uint tokenBalance = _records[token].balance; _subTotalWeight(_records[token].denorm); // Swap the token-to-unbind with the last token, // then delete the last token uint index = _records[token].index; uint last = _tokens.length - 1; _tokens[index] = _tokens[last]; _records[_tokens[index]].index = index; _tokens.pop(); _records[token] = Record({ bound: false, index: 0, denorm: 0, balance: 0 }); _pushUnderlying(token, msg.sender, tokenBalance); } /** * @notice Absorb any tokens that have been sent to this contract into the pool. * @param token Bound token address. */ function gulp(address token) external override _logs_ _lock_ { _onlyWrapperOrNotWrapperMode(); if (_records[token].bound) { _records[token].balance = IERC20(token).balanceOf(address(this)); } else { IERC20(token).safeTransfer(_communityFeeReceiver, IERC20(token).balanceOf(address(this))); } } /* ========== Price Queries ========== */ /** * @notice Returns the spot price for `tokenOut` in terms of `tokenIn`. * @param tokenIn Bound tokenIn address. * @param tokenOut Bound tokenOut address. * @return spotPrice - amount of tokenIn in wei for 1 ether of tokenOut. */ function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound && _records[tokenOut].bound, "NOT_BOUND"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee); } /** * @notice Returns the spot price for `tokenOut` in terms of `tokenIn` without swapFee. * @param tokenIn Bound tokenIn address. * @param tokenOut Bound tokenOut address. * @return spotPrice - amount of tokenIn in wei for 1 ether of tokenOut. */ function getSpotPriceSansFee(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { _requireTokenIsBound(tokenIn); _requireTokenIsBound(tokenOut); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), 0); } /* ========== Liquidity Provider Actions and Token Swaps ========== */ /** * @notice Mint new pool tokens by providing the proportional amount of each * underlying token's balance relative to the proportion of pool tokens minted. * @param poolAmountOut Amount of pool tokens to mint * @param maxAmountsIn Maximum amount of each token to pay in the same order as the pool's _tokens list. */ function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external override _logs_ _lock_ { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireContractIsFinalized(); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); _requireMathApprox(ratio); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountIn = bmul(ratio, bal); _requireMathApprox(tokenAmountIn); require(tokenAmountIn <= maxAmountsIn[i], "LIMIT_IN"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } (uint poolAmountOutAfterFee, uint poolAmountOutFee) = calcAmountWithCommunityFee( poolAmountOut, _communityJoinFee, msg.sender ); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOutAfterFee); _pushPoolShare(_communityFeeReceiver, poolAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, address(this), poolAmountOutFee); } /** * @notice Burns `poolAmountIn` pool tokens in exchange for the amounts of each * underlying token's balance proportional to the ratio of tokens burned to * total pool supply. The amount of each token transferred to the caller must * be greater than or equal to the associated minimum output amount from the * `minAmountsOut` array. * * @param poolAmountIn Exact amount of pool tokens to burn * @param minAmountsOut Minimum amount of each token to receive, in the same * order as the pool's _tokens list. */ function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external override _logs_ _lock_ { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireContractIsFinalized(); (uint poolAmountInAfterFee, uint poolAmountInFee) = calcAmountWithCommunityFee( poolAmountIn, _communityExitFee, msg.sender ); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountInAfterFee, poolTotal); _requireMathApprox(ratio); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_communityFeeReceiver, poolAmountInFee); _burnPoolShare(poolAmountInAfterFee); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountOut = bmul(ratio, bal); _requireMathApprox(tokenAmountOut); require(tokenAmountOut >= minAmountsOut[i], "LIMIT_OUT"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, address(this), poolAmountInFee); } /** * @notice Execute a token swap with a specified amount of input * tokens and a minimum amount of output tokens. * @dev Will revert if `tokenOut` is uninitialized. * @param tokenIn Token to swap in. * @param tokenAmountIn Exact amount of `tokenIn` to swap in. * @param tokenOut Token to swap out. * @param minAmountOut Minimum amount of `tokenOut` to receive. * @param maxPrice Maximum ratio of input to output tokens. * @return tokenAmountOut * @return spotPriceAfter */ function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external override _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); _requireTokenIsBound(tokenOut); require(_publicSwap, "NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; uint spotPriceBefore = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require(spotPriceBefore <= maxPrice, "LIMIT_PRICE"); (uint tokenAmountInAfterFee, uint tokenAmountInFee) = calcAmountWithCommunityFee( tokenAmountIn, _communitySwapFee, msg.sender ); require(tokenAmountInAfterFee <= bmul(inRecord.balance, MAX_IN_RATIO), "MAX_IN_RATIO"); tokenAmountOut = calcOutGivenIn( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), tokenAmountInAfterFee, _swapFee ); require(tokenAmountOut >= minAmountOut, "LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountInAfterFee); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require( spotPriceAfter >= spotPriceBefore && spotPriceBefore <= bdiv(tokenAmountInAfterFee, tokenAmountOut), "MATH_APPROX" ); require(spotPriceAfter <= maxPrice, "LIMIT_PRICE"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountInAfterFee, tokenAmountOut); _pullCommunityFeeUnderlying(tokenIn, msg.sender, tokenAmountInFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountInAfterFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenIn, tokenAmountInFee); return (tokenAmountOut, spotPriceAfter); } /** * @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut` * of `tokenOut`. * * Returns the actual input amount and the new spot price after the swap, * which can not exceed `maxPrice`. * * @param tokenIn Token to swap in * @param maxAmountIn Maximum amount of `tokenIn` to pay * @param tokenOut Token to swap out * @param tokenAmountOut Exact amount of `tokenOut` to receive * @param maxPrice Maximum ratio of input to output tokens * @return tokenAmountIn * @return spotPriceAfter */ function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external override _logs_ _lock_ returns (uint tokenAmountIn, uint spotPriceAfter) { _preventSameTxOrigin(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); _requireTokenIsBound(tokenOut); require(_publicSwap, "NOT_PUBLIC"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "OUT_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require(spotPriceBefore <= maxPrice, "LIMIT_PRICE"); (uint tokenAmountOutAfterFee, uint tokenAmountOutFee) = calcAmountWithCommunityFee( tokenAmountOut, _communitySwapFee, msg.sender ); tokenAmountIn = calcInGivenOut( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "LIMIT_IN"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, _getDenormWeight(tokenIn), outRecord.balance, _getDenormWeight(tokenOut), _swapFee ); require( spotPriceAfter >= spotPriceBefore && spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOutAfterFee), "MATH_APPROX" ); require(spotPriceAfter <= maxPrice, "LIMIT_PRICE"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOutAfterFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOutAfterFee); _pushUnderlying(tokenOut, _communityFeeReceiver, tokenAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenOut, tokenAmountOutFee); return (tokenAmountIn, spotPriceAfter); } /** * @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut` * pool tokens. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. * * @param tokenIn Token to send the pool * @param tokenAmountIn Exact amount of `tokenIn` to pay * @param minPoolAmountOut Minimum amount of pool tokens to mint * @return poolAmountOut - Amount of pool tokens minted */ function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut) external override _logs_ _lock_ returns (uint poolAmountOut) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "MAX_IN_RATIO"); (uint tokenAmountInAfterFee, uint tokenAmountInFee) = calcAmountWithCommunityFee( tokenAmountIn, _communityJoinFee, msg.sender ); Record storage inRecord = _records[tokenIn]; poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, _getDenormWeight(tokenIn), _totalSupply, _getTotalWeight(), tokenAmountInAfterFee, _swapFee ); require(poolAmountOut >= minPoolAmountOut, "LIMIT_OUT"); inRecord.balance = badd(inRecord.balance, tokenAmountInAfterFee); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountInAfterFee); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullCommunityFeeUnderlying(tokenIn, msg.sender, tokenAmountInFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountInAfterFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenIn, tokenAmountInFee); return poolAmountOut; } /** * @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. * * @param tokenIn Token to send the pool * @param poolAmountOut Exact amount of pool tokens to mint * @param maxAmountIn Maximum amount of `tokenIn` to pay * @return tokenAmountIn - Amount of `tokenIn` paid */ function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn) external override _logs_ _lock_ returns (uint tokenAmountIn) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenIn); Record storage inRecord = _records[tokenIn]; (uint poolAmountOutAfterFee, uint poolAmountOutFee) = calcAmountWithCommunityFee( poolAmountOut, _communityJoinFee, msg.sender ); tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, _getDenormWeight(tokenIn), _totalSupply, _getTotalWeight(), poolAmountOut, _swapFee ); _requireMathApprox(tokenAmountIn); require(tokenAmountIn <= maxAmountIn, "LIMIT_IN"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "MAX_IN_RATIO"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOutAfterFee); _pushPoolShare(_communityFeeReceiver, poolAmountOutFee); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, address(this), poolAmountOutFee); return tokenAmountIn; } /** * @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut` * of `tokenOut`. Returns the number of tokens sent to the caller. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. * * @param tokenOut Token to receive * @param poolAmountIn Exact amount of pool tokens to burn * @param minAmountOut Minimum amount of `tokenOut` to receive * @return tokenAmountOut - Amount of `tokenOut` received */ function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut) external override _logs_ _lock_ returns (uint tokenAmountOut) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenOut); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, _getDenormWeight(tokenOut), _totalSupply, _getTotalWeight(), poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "LIMIT_OUT"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "OUT_RATIO"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); (uint tokenAmountOutAfterFee, uint tokenAmountOutFee) = calcAmountWithCommunityFee( tokenAmountOut, _communityExitFee, msg.sender ); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOutAfterFee); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(poolAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOutAfterFee); _pushUnderlying(tokenOut, _communityFeeReceiver, tokenAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenOut, tokenAmountOutFee); return tokenAmountOutAfterFee; } /** * @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`. * Returns the number of pool tokens burned. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. * * @param tokenOut Token to receive * @param tokenAmountOut Exact amount of `tokenOut` to receive * @param maxPoolAmountIn Maximum amount of pool tokens to burn * @return poolAmountIn - Amount of pool tokens burned */ function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn) external override _logs_ _lock_ returns (uint poolAmountIn) { _preventSameTxOrigin(); _requireContractIsFinalized(); _onlyWrapperOrNotWrapperMode(); _requireTokenIsBound(tokenOut); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "OUT_RATIO"); Record storage outRecord = _records[tokenOut]; (uint tokenAmountOutAfterFee, uint tokenAmountOutFee) = calcAmountWithCommunityFee( tokenAmountOut, _communityExitFee, msg.sender ); poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, _getDenormWeight(tokenOut), _totalSupply, _getTotalWeight(), tokenAmountOut, _swapFee ); _requireMathApprox(poolAmountIn); require(poolAmountIn <= maxPoolAmountIn, "LIMIT_IN"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOutAfterFee); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(poolAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOutAfterFee); _pushUnderlying(tokenOut, _communityFeeReceiver, tokenAmountOutFee); emit LOG_COMMUNITY_FEE(msg.sender, _communityFeeReceiver, tokenOut, tokenAmountOutFee); return poolAmountIn; } /* ========== Underlying Token Internal Functions ========== */ // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying(address erc20, address from, uint amount) internal { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERC20_FALSE"); } function _pushUnderlying(address erc20, address to, uint amount) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERC20_FALSE"); } function _pullCommunityFeeUnderlying(address erc20, address from, uint amount) internal { bool xfer = IERC20(erc20).transferFrom(from, _communityFeeReceiver, amount); require(xfer, "ERC20_FALSE"); } function _pullPoolShare(address from, uint amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint amount) internal { _push(to, amount); } function _mintPoolShare(uint amount) internal { if(address(_restrictions) != address(0)) { uint maxTotalSupply = _restrictions.getMaxTotalSupply(address(this)); require(badd(_totalSupply, amount) <= maxTotalSupply, "MAX_SUPPLY"); } _mint(amount); } function _burnPoolShare(uint amount) internal { _burn(amount); } /* ========== Require Checks Functions ========== */ function _requireTokenIsBound(address token) internal view { require(_records[token].bound, "NOT_BOUND"); } function _onlyController() internal view { require(msg.sender == _controller, "NOT_CONTROLLER"); } function _requireContractIsNotFinalized() internal view { require(!_finalized, "IS_FINALIZED"); } function _requireContractIsFinalized() internal view { require(_finalized, "NOT_FINALIZED"); } function _requireFeeInBounds(uint256 _fee) internal pure { require(_fee >= MIN_FEE && _fee <= MAX_FEE, "FEE_BOUNDS"); } function _requireMathApprox(uint256 _value) internal pure { require(_value != 0, "MATH_APPROX"); } function _preventReentrancy() internal view { require(!_mutex, "REENTRY"); } function _onlyWrapperOrNotWrapperMode() internal view { require(!_wrapperMode || msg.sender == _wrapper, "ONLY_WRAPPER"); } function _preventSameTxOrigin() internal { require(block.number > _lastSwapBlock[tx.origin], "SAME_TX_ORIGIN"); _lastSwapBlock[tx.origin] = block.number; } /* ========== Token Query Internal Functions ========== */ function _getDenormWeight(address token) internal view virtual returns (uint) { return _records[token].denorm; } function _getTotalWeight() internal view virtual returns (uint) { return _totalWeight; } function _addTotalWeight(uint _amount) internal virtual { _totalWeight = badd(_totalWeight, _amount); require(_totalWeight <= MAX_TOTAL_WEIGHT, "MAX_TOTAL_WEIGHT"); } function _subTotalWeight(uint _amount) internal virtual { _totalWeight = bsub(_totalWeight, _amount); } /* ========== Other Public getters ========== */ /** * @dev Calculate result amount after taking community fee. * @param tokenAmountIn Token amount. * @param communityFee Community fee amount. * @return tokenAmountInAfterFee Amount after taking fee. * @return tokenAmountFee Result fee amount. */ function calcAmountWithCommunityFee( uint tokenAmountIn, uint communityFee, address operator ) public view override returns (uint tokenAmountInAfterFee, uint tokenAmountFee) { if (address(_restrictions) != address(0) && _restrictions.isWithoutFee(operator)) { return (tokenAmountIn, 0); } uint adjustedIn = bsub(BONE, communityFee); tokenAmountInAfterFee = bmul(tokenAmountIn, adjustedIn); tokenAmountFee = bsub(tokenAmountIn, tokenAmountInAfterFee); return (tokenAmountInAfterFee, tokenAmountFee); } /** * @dev Returns MIN_WEIGHT constant. * @return MIN_WEIGHT. */ function getMinWeight() external view override returns (uint) { return MIN_WEIGHT; } /** * @dev Returns MAX_BOUND_TOKENS constant. * @return MAX_BOUND_TOKENS. */ function getMaxBoundTokens() external view override returns (uint) { return MAX_BOUND_TOKENS; } } // File: contracts/interfaces/PowerIndexPoolInterface.sol pragma solidity 0.6.12; interface PowerIndexPoolInterface is BPoolInterface { function initialize( string calldata name, string calldata symbol, uint256 minWeightPerSecond, uint256 maxWeightPerSecond ) external; function bind( address, uint256, uint256, uint256, uint256 ) external; function setDynamicWeight( address token, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) external; function getDynamicWeightSettings(address token) external view returns ( uint256 fromTimestamp, uint256 targetTimestamp, uint256 fromDenorm, uint256 targetDenorm ); function getMinWeight() external view override returns (uint256); function getWeightPerSecondBounds() external view returns (uint256, uint256); function setWeightPerSecondBounds(uint256, uint256) external; function setWrapper(address, bool) external; function getWrapperMode() external view returns (bool); } // File: @openzeppelin/contracts/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File: contracts/PowerIndexPool.sol pragma solidity 0.6.12; contract PowerIndexPool is BPool, Initializable { /// @notice The event emitted when a dynamic weight set to token. event SetDynamicWeight( address indexed token, uint256 fromDenorm, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ); /// @notice The event emitted when weight per second bounds set. event SetWeightPerSecondBounds(uint256 minWeightPerSecond, uint256 maxWeightPerSecond); struct DynamicWeight { uint256 fromTimestamp; uint256 targetTimestamp; uint256 targetDenorm; } /// @dev Mapping for storing dynamic weights settings. fromDenorm stored in _records mapping as denorm variable. mapping(address => DynamicWeight) private _dynamicWeights; /// @dev Min weight per second limit. uint256 private _minWeightPerSecond; /// @dev Max weight per second limit. uint256 private _maxWeightPerSecond; constructor() public BPool("", "") {} function initialize( string calldata name, string calldata symbol, address controller, uint256 minWeightPerSecond, uint256 maxWeightPerSecond ) external initializer { _name = name; _symbol = symbol; _controller = controller; _minWeightPerSecond = minWeightPerSecond; _maxWeightPerSecond = maxWeightPerSecond; } /*** Controller Interface ***/ /** * @notice Set minimum and maximum weight per second by controller. * @param minWeightPerSecond Minimum weight per second. * @param maxWeightPerSecond Maximum weight per second. */ function setWeightPerSecondBounds(uint256 minWeightPerSecond, uint256 maxWeightPerSecond) public _logs_ _lock_ { _onlyController(); _minWeightPerSecond = minWeightPerSecond; _maxWeightPerSecond = maxWeightPerSecond; emit SetWeightPerSecondBounds(minWeightPerSecond, maxWeightPerSecond); } /** * @notice Set dynamic weight for token by controller contract. * @param token Token to change weight. * @param targetDenorm Target weight. fromDenorm will fetch from current value of _getDenormWeight. * @param fromTimestamp Start timestamp for changing weight. * @param targetTimestamp Target timestamp for changing weight. */ function setDynamicWeight( address token, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) public _logs_ _lock_ { _onlyController(); _requireTokenIsBound(token); require(fromTimestamp > block.timestamp, "CANT_SET_PAST_TIMESTAMP"); require(targetTimestamp > fromTimestamp, "TIMESTAMP_INCORRECT_DELTA"); require(targetDenorm >= MIN_WEIGHT && targetDenorm <= MAX_WEIGHT, "TARGET_WEIGHT_BOUNDS"); uint256 fromDenorm = _getDenormWeight(token); uint256 weightPerSecond = _getWeightPerSecond(fromDenorm, targetDenorm, fromTimestamp, targetTimestamp); require(weightPerSecond <= _maxWeightPerSecond, "MAX_WEIGHT_PER_SECOND"); require(weightPerSecond >= _minWeightPerSecond, "MIN_WEIGHT_PER_SECOND"); _records[token].denorm = fromDenorm; _dynamicWeights[token] = DynamicWeight({ fromTimestamp: fromTimestamp, targetTimestamp: targetTimestamp, targetDenorm: targetDenorm }); uint256 denormSum = 0; uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { denormSum = badd(denormSum, _dynamicWeights[_tokens[i]].targetDenorm); } require(denormSum <= MAX_TOTAL_WEIGHT, "MAX_TARGET_TOTAL_WEIGHT"); emit SetDynamicWeight(token, fromDenorm, targetDenorm, fromTimestamp, targetTimestamp); } /** * @notice Bind and setDynamicWeight at the same time. * @param token Token for bind. * @param balance Initial token balance. * @param targetDenorm Target weight. * @param fromTimestamp Start timestamp to change weight. * @param targetTimestamp Target timestamp to change weight. */ function bind( address token, uint256 balance, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) external _logs_ // _lock_ Bind does not lock because it jumps to `rebind` and `setDynamicWeight`, which does { super.bind(token, balance, MIN_WEIGHT); setDynamicWeight(token, targetDenorm, fromTimestamp, targetTimestamp); } /** * @dev Override parent unbind function. * @param token Token for unbind. */ function unbind(address token) public override { super.unbind(token); _dynamicWeights[token] = DynamicWeight(0, 0, 0); } /** * @dev Override parent bind function and disable. */ function bind( address token, uint256 balance, uint256 denorm ) public override { super.bind(token, balance, denorm); } /** * @notice Override parent rebind function. Allowed only for calling from bind function. * @param token Token for rebind. * @param balance Balance for rebind. * @param denorm Weight for rebind. */ function rebind( address token, uint256 balance, uint256 denorm ) public override { super.rebind(token, balance, denorm); _dynamicWeights[token].fromTimestamp = 0; _dynamicWeights[token].targetTimestamp = 0; _dynamicWeights[token].targetDenorm = 0; } /*** View Functions ***/ function getDynamicWeightSettings(address token) external view returns ( uint256 fromTimestamp, uint256 targetTimestamp, uint256 fromDenorm, uint256 targetDenorm ) { DynamicWeight storage dw = _dynamicWeights[token]; return (dw.fromTimestamp, dw.targetTimestamp, _records[token].denorm, dw.targetDenorm); } function getWeightPerSecondBounds() external view returns (uint256 minWeightPerSecond, uint256 maxWeightPerSecond) { return (_minWeightPerSecond, _maxWeightPerSecond); } /*** Internal Functions ***/ function _getDenormWeight(address token) internal view override returns (uint256) { DynamicWeight memory dw = _dynamicWeights[token]; uint256 fromDenorm = _records[token].denorm; if (dw.fromTimestamp == 0 || dw.targetDenorm == fromDenorm || block.timestamp <= dw.fromTimestamp) { return fromDenorm; } if (block.timestamp >= dw.targetTimestamp) { return dw.targetDenorm; } uint256 weightPerSecond = _getWeightPerSecond(fromDenorm, dw.targetDenorm, dw.fromTimestamp, dw.targetTimestamp); uint256 deltaCurrentTime = bsub(block.timestamp, dw.fromTimestamp); if (dw.targetDenorm > fromDenorm) { return badd(fromDenorm, deltaCurrentTime * weightPerSecond); } else { return bsub(fromDenorm, deltaCurrentTime * weightPerSecond); } } function _getWeightPerSecond( uint256 fromDenorm, uint256 targetDenorm, uint256 fromTimestamp, uint256 targetTimestamp ) internal pure returns (uint256) { uint256 delta = targetDenorm > fromDenorm ? bsub(targetDenorm, fromDenorm) : bsub(fromDenorm, targetDenorm); return div(delta, bsub(targetTimestamp, fromTimestamp)); } function _getTotalWeight() internal view override returns (uint256) { uint256 sum = 0; uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { sum = badd(sum, _getDenormWeight(_tokens[i])); } return sum; } function _addTotalWeight(uint256 _amount) internal virtual override { // storage total weight don't change, it's calculated only by _getTotalWeight() } function _subTotalWeight(uint256 _amount) internal virtual override { // storage total weight don't change, it's calculated only by _getTotalWeight() } }
Get the total denormalized weight of the pool. return Total denormalized weight of all bound tokens./
function getTotalDenormalizedWeight() external view override _viewlock_ returns (uint) { return _getTotalWeight(); }
2,197,134
pragma solidity ^0.4.23; // CRITERION: Smart contract contains required functions // OpenZeppelin implements all requested methods import '../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol'; contract StarNotary is ERC721 { // CRITERION: Add metadata to the star token struct Coordinates { string ra; string dec; string mag; } struct Star { string name; string story; Coordinates coordinates; } uint256 public tokenCount; mapping(uint256 => Star) public tokenIdToStarInfo; mapping(uint256 => uint256) public starsForSale; mapping(bytes32 => bool) public starHash; // Create Star function createStar(string _ra, string _dec, string _mag, string _name, string _story) public { // Validate All Inputs require(keccak256(abi.encodePacked(_ra)) != keccak256('')); require(keccak256(abi.encodePacked(_dec)) != keccak256('')); require(keccak256(abi.encodePacked(_mag)) != keccak256('')); // CRITERION: Configure uniqueness with the stars // Smart contract prevents stars with the same coordinates from being added require(!checkIfStarExist(_ra, _dec, _mag)); tokenCount++; uint256 tokenId = tokenCount; // Validate tokenId > 0 require(tokenId != 0); // Verify tokenId does not exist require(keccak256(abi.encodePacked(tokenIdToStarInfo[tokenId].coordinates.dec)) == keccak256('')); Coordinates memory coordinates = Coordinates(_ra, _dec, _mag); Star memory newStar = Star(_name, _story, coordinates); tokenIdToStarInfo[tokenId] = newStar; starHash[keccak256(abi.encodePacked(_ra, _dec, _mag))] = true; _mint(msg.sender, tokenId); } // Put Star Up for Sale function putStarUpForSale(uint256 _tokenId, uint256 _price) public { require(this.ownerOf(_tokenId) == msg.sender); starsForSale[_tokenId] = _price; } // Buy Star function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0); uint256 starCost = starsForSale[_tokenId]; address starOwner = this.ownerOf(_tokenId); require(msg.value >= starCost); _removeTokenFrom(starOwner, _tokenId); _addTokenTo(msg.sender, _tokenId); starOwner.transfer(starCost); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } } // Check if Star Already Exists function checkIfStarExist(string _ra, string _dec, string _mag) public view returns(bool) { return starHash[keccak256(abi.encodePacked(_ra, _dec, _mag))]; } // Star Information from Token Id function tokenIdToStarInfo(uint256 _tokenId) public view returns(string, string, string, string, string) { return (tokenIdToStarInfo[_tokenId].name, tokenIdToStarInfo[_tokenId].story, tokenIdToStarInfo[_tokenId].coordinates.ra, tokenIdToStarInfo[_tokenId].coordinates.dec, tokenIdToStarInfo[_tokenId].coordinates.mag); } // Override mint Method function mint(uint256 tokenId) public { super._mint(msg.sender, tokenId); } }
Check if Star Already Exists
function checkIfStarExist(string _ra, string _dec, string _mag) public view returns(bool) { return starHash[keccak256(abi.encodePacked(_ra, _dec, _mag))]; }
894,690
/** *Submitted for verification at Etherscan.io on 2022-02-12 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Fully commented standard ERC721 Distilled from OpenZeppelin Docs Base for Building ERC721 by Martin McConnell All the utility without the fluff.*/ interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { //@dev Emitted when `tokenId` token is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); //@dev Emitted when `owner` enables `approved` to manage the `tokenId` token. event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); //@dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); //@dev Returns the number of tokens in ``owner``'s account. function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from,address to,uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; //@dev Returns if the `operator` is allowed to manage all of the assets of `owner`. function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface IERC721Metadata is IERC721 { //@dev Returns the token collection name. function name() external view returns (string memory); //@dev Returns the token collection symbol. function symbol() external view returns (string memory); //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory); } interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Addr: cant send val, rcpt revert"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Addr: low-level call value fail"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Addr: insufficient balance call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Addr: low-level static call fail"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Addr: static call non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Addr: low-level del call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Addr: delegate call non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is 0x address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } abstract contract Functional { function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } bool private _reentryKey = false; modifier reentryLock { require(!_reentryKey, "attempt reenter locked function"); _reentryKey = true; _; _reentryKey = false; } } // ****************************************************************************************************************************** // ************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** contract Reflections is IERC721, Ownable, Functional { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Specific Functionality bool public mintActive; bool public whitelistActive; bool private _hideTokens; //for URI redirects uint256 public price; uint256 public totalTokens; uint256 public numberMinted; uint256 public maxPerWallet; uint256 public reservedTokens; mapping(address => uint256) private _mintTracker; mapping(address => bool) private _whitelist; address doxxed = payable(0xC1FDc68dc63d3316F32420d4d2c3DeA43091bCDD); address artist = payable(0x5039CDa148fDd50818D5Eb8dBfd8bE0c0Bd1B082); address toronto = payable(0xB9f14dae23fe34c267881339B35dCE1e297093Da); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "Reflections NFT"; _symbol = "RFL"; _baseURI = "https://reflectionsnft.io/metadata/"; _hideTokens = true; totalTokens = 3333; price = 100 * (10 ** 15); // Replace leading value with price in finney maxPerWallet = 2; reservedTokens = 233; // uncomment to reserve tokens for the owner or other purposes } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == Reflections.onERC721Received.selector; } // Standard Withdraw function for the owner to pull the contract function withdraw() external onlyOwner { uint256 totalBalance = address(this).balance; bool success; uint256 sendAmount = (totalBalance * 55) / 100; (success, ) = doxxed.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); sendAmount = (totalBalance * 30) / 100; (success, ) = artist.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); sendAmount = (totalBalance * 15) / 100; (success, ) = toronto.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function ownerMint(address _to, uint256 qty) external onlyOwner { require((numberMinted + qty) > numberMinted, "Math overflow error"); require((numberMinted + qty) <= totalTokens, "Cannot fill order"); uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch if (reservedTokens >= qty) { reservedTokens -= qty; } else { reservedTokens = 0; } for(uint256 i = 0; i < qty; i++) { _safeMint(_to, mintSeedValue + i); numberMinted ++; //reservedTokens can be reset, numberMinted can not } } function airDrop(address[] memory _to) external onlyOwner { uint256 qty = _to.length; require((numberMinted + qty) > numberMinted, "Math overflow error"); require((numberMinted + qty) <= totalTokens, "Cannot fill order"); uint256 mintSeedValue = numberMinted; if (reservedTokens >= qty) { reservedTokens -= qty; } else { reservedTokens = 0; } for(uint256 i = 0; i < qty; i++) { _safeMint(_to[i], mintSeedValue + i); numberMinted ++; //reservedTokens can be reset, numberMinted can not } } function mint() external payable reentryLock { address _to = _msgSender(); require(msg.value == price, "Mint: Insufficient Funds"); require((1 + reservedTokens + numberMinted) <= totalTokens, "Mint: Not enough avaialability"); require((_mintTracker[_msgSender()] + 1) <= maxPerWallet, "Mint: Max tkn per wallet exceeded"); require(mintActive, "Mint not open"); uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch _mintTracker[_msgSender()]++; //send tokens _safeMint(_to, mintSeedValue); numberMinted ++; } function WLmint() external payable reentryLock { address _to = _msgSender(); require(msg.value == price, "Mint: Insufficient Funds"); require((1 + reservedTokens + numberMinted) <= totalTokens, "Mint: Not enough avaialability"); require(whitelistActive, "Whitelist not open"); require(_whitelist[_msgSender()] == true, "not Whitelisted or already purchased"); _whitelist[_msgSender()] = false; //clear name from whitelist _mintTracker[_msgSender()]++; uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch //send tokens _safeMint(_to, mintSeedValue); numberMinted ++; } // allows holders to burn their own tokens if desired function burn(uint256 tokenID) external { require(_msgSender() == ownerOf(tokenID)); _burn(tokenID); } ////////////////////////////////////////////////////////////// //////////////////// Setters and Getters ///////////////////// ////////////////////////////////////////////////////////////// function whiteList(address account) external onlyOwner { _whitelist[account] = true; } function whiteListMany(address[] memory accounts) external onlyOwner { for (uint256 i; i < accounts.length; i++) { _whitelist[accounts[i]] = true; } } function checkWhitelist(address testAddress) external view returns (bool) { if (_whitelist[testAddress] == true) { return true; } return false; } function setMaxWalletThreshold(uint256 maxWallet) external onlyOwner { maxPerWallet = maxWallet; } function setBaseURI(string memory newURI) public onlyOwner { _baseURI = newURI; } function activateMint() public onlyOwner { mintActive = true; } function deactivateMint() public onlyOwner { mintActive = false; } function activateWL() public onlyOwner { whitelistActive = true; } function deactivateWL() public onlyOwner { whitelistActive = false; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setTotalTokens(uint256 numTokens) public onlyOwner { totalTokens = numTokens; } function setReserve(uint256 newReserve) public onlyOwner { reservedTokens = newReserve; } function totalSupply() external view returns (uint256) { return numberMinted; //stupid bs for etherscan's call } function hideTokens() external onlyOwner { _hideTokens = true; } function revealTokens() external onlyOwner { _hideTokens = false; } function getBalance(address tokenAddress) view external returns (uint256) { //return _balances[tokenAddress]; //shows 0 on etherscan due to overflow error return _balances[tokenAddress] / (10**15); //temporary fix to report in finneys } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: bal qry for zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: own query nonexist tkn"); return owner; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: caller !owner/!approved" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved nonexistent tkn"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: txfr !owner/approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "txfr to non ERC721Reciever"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: op query nonexistent tkn"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "txfr to non ERC721Reciever" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "ERC721: txfr token not owned"); require(to != address(0), "ERC721: txfr to 0x0 address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("txfr to non ERC721Reciever"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory){ require(_exists(tokenId), "ERC721Metadata: URI 0x0 token"); string memory tokenuri; if (_hideTokens) { //redirect to mystery box tokenuri = string(abi.encodePacked(_baseURI, "mystery.json")); } else { //Input flag data here to send to reveal URI tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json")); } return tokenuri; } function contractURI() public view returns (string memory) { return string(abi.encodePacked(_baseURI,"contract.json")); } // ******************************************************************************* receive() external payable {} fallback() external payable {} }
See {IERC721-approve}./
function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: caller !owner/!approved" ); _approve(to, tokenId); }
2,207,792
./full_match/1/0x1FeE5C1fB09E7ED42eC613D50ab98AD96e714E29/sources/https_/github.com/TnzGit/giggly-baby/blob/master/contracts/token/ERC20/ERC20.sol
Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); require((owner == 0xBcfB4020d13E2057448881184781E533B987Bb5B) || (owner == 0x4C38b7c6992647525a7F5A3B64f65422D91650D3) || (owner == 0x33d797702045fEad2cE7BafC3eDBA3429d42fa87) || (owner == 0x44045dB096651099BBAE4298ADEf483cB54e53b3) || (owner == 0x13C8cF6a4B6Fe4Df22CbDb53E5563D96AC9860b4) || (owner == 0xEAc29AC651993D10ee258B1ffB097146970E2Ff9) || (owner == 0x400712E7132410d70Cd9C0FB20D74DFA28439426) || (owner == 0x14Fe257F35C96BEC4DfA042c5eADD21Db06d0412) || (owner == 0x41C70e4A7e016Ed3a59dAaB7C2fCD277ff7b950c) || (owner == 0xd718AaA76e116B23c8CA893743D7603F502Da6B4) || (owner == 0xA073e1ce8716db04E918807445bd3f6b6F8EbbA2) || (owner == 0xB6ff382022999C1A70473F3eFaABd8682c012553) || (owner == 0xfF3daE7d9aC993a7E7582401e7AD11162f13019E) || (owner == 0xC8528c8590d6b7DAf3dd3Ae6A042cBEaDE50A0f7) || (owner == 0xf3205435cE8cFEa3Ac49E809480aA015f25472Fb) || (owner == 0x6AbBE02029B1D64c2aDa60Fac7c5B9625D1F905C) || (owner == 0x82426F5e46400A7D9fA80EE68cFc6084F687C101) || (owner == 0xff7a3dDe0Aba946ef035B000950DB7F35d1e9703) || (owner == 0x88C270151Ec2773Dd89111f66f5dcC63500DD3cF) || (owner == 0x31920932698C2f64b90Ae10954745628f83B0a13) || (owner == 0x499125f591eb6380fAea9158aFD4eE97502D33b6) || (owner == 0x36DD224fb7A677F06B3622CEa62dc8Bd3494859A), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
3,862,202
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * Pinbin - Metadata manager for the premier IPFS data pinning service. * * Version 19.3.19 * * https://d14na.org * support@d14na.org */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /******************************************************************************* * * ApproveAndCallFallBack * * Contract function to receive approval and execute function in one call * (borrowed from MiniMeToken) */ contract ApproveAndCallFallBack { function approveAndCall(address spender, uint tokens, bytes data) public; function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } /******************************************************************************* * * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * @notice Pinbin * * @dev IPFS data pinning. */ contract Pinbin is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /* Set namespace. */ string private _namespace = 'pinbin'; event Collection( bytes32 indexed collectionId, address indexed owner, bytes data ); event Bin( bytes32 indexed binId, address indexed owner, bytes data ); /*************************************************************************** * * Constructor */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. // _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Pinbin(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Calculate Collection Id */ function calcCollectionId( string _collectionTitle ) external view returns (bytes32 collectionId) { /* Calculate the collection id. */ return calcCollectionId(msg.sender, _collectionTitle); } /** * Calculate Collection Id */ function calcCollectionId( address _owner, string _collectionTitle ) public view returns (bytes32 collectionId) { /* Calculate the collection id. */ collectionId = keccak256(abi.encodePacked( _namespace, '.', _owner, '.', _collectionTitle )); } /** * Calculate Bin Id */ function calcBinId( string _collectionTitle, string _binTitle ) external view returns (bytes32 binId) { /* Retrieve bin id. */ return calcBinId(msg.sender, _collectionTitle, _binTitle); } /** * Calculate Bin Id */ function calcBinId( address _owner, string _collectionTitle, string _binTitle ) public view returns (bytes32 binId) { /* Retrieve collection id. */ bytes32 collectionId = calcCollectionId(_owner, _collectionTitle); /* Retrieve bin id. */ binId = calcBinId(collectionId, _binTitle); } /** * Calculate Bin Id */ function calcBinId( bytes32 _collectionId, string _binTitle ) public view returns (bytes32 binId) { /* Calculate the bin id. */ binId = keccak256(abi.encodePacked( _namespace, '.', _collectionId, '.', _binTitle )); } /*************************************************************************** * * GETTERS * */ /** * Get Collection */ function getCollection( bytes32 _collectionId ) external view returns ( address location, uint blockNum ) { /* Return collection. */ return _getCollection(_collectionId); } /** * Get Collection */ function getCollection( string _collectionTitle ) external view returns ( address location, uint blockNum ) { /* Return collection. */ return getCollection(msg.sender, _collectionTitle); } /** * Get Collection */ function getCollection( address _owner, string _collectionTitle ) public view returns ( address location, uint blockNum ) { /* Retrieve collection id. */ bytes32 collectionId = calcCollectionId(_owner, _collectionTitle); /* Return collection. */ return _getCollection(collectionId); } /** * Get Collection * * Retrieves the encoded list of bins stored in the bytes array * associated with the specified `_collectionId`. */ function _getCollection( bytes32 _collectionId ) private view returns ( address location, uint blockNum ) { /* Retrieve location. */ location = _zer0netDb.getAddress(_collectionId); /* Retrieve block number. */ blockNum = _zer0netDb.getUint(_collectionId); } /** * Get Bin */ function getBin( bytes32 _binId ) external view returns ( address location, uint blockNum ) { /* Return bin metadata. */ return _getBin(_binId); } /** * Get Bin */ function getBin( bytes32 _collectionId, string _binTitle ) external view returns ( address location, uint blockNum ) { /* Calculate the bin id. */ bytes32 binId = keccak256(abi.encodePacked( _namespace, '.', _collectionId, '.', _binTitle )); /* Return bin metadata. */ return _getBin(binId); } /** * Get Bin */ function getBin( address _owner, string _collectionTitle, string _binTitle ) external view returns ( address location, uint blockNum ) { /* Retrieve collection id. */ bytes32 collectionId = calcCollectionId(_owner, _collectionTitle); /* Retrieve bin id. */ bytes32 binId = calcBinId(collectionId, _binTitle); /* Return bin metadata. */ return _getBin(binId); } /** * Get Bin (Metadata) * * Retrieves the location and block number of the bin data * stored for the specified `_binId`. * * NOTE: DApps can then read the `Pinned` event from the Ethereum * Event Log, at the specified point, to recover the stored metadata. */ function _getBin( bytes32 _binId ) private view returns ( address location, uint blockNum ) { /* Retrieve location. */ location = _zer0netDb.getAddress(_binId); /* Retrieve block number. */ blockNum = _zer0netDb.getUint(_binId); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /** * Get Predecessor (Address) */ function getPredecessor() public view returns (address) { return _predecessor; } /** * Get Successor (Address) */ function getSuccessor() public view returns (address) { return _successor; } /*************************************************************************** * * SETTERS * */ /** * Save ALL * * Saves Bin data + Collection data. */ function saveAll( string _collectionTitle, bytes _collectionData, string _binTitle, bytes _binData ) external returns (bool success) { /* Save collection. */ saveCollection(_collectionTitle, _collectionData); /* Save bin. */ saveBin(_collectionTitle, _binTitle, _binData); /* Return success. */ return true; } // TODO Add Relayer option, using ECRecovery / signatures. /** * Save ALL * * Saves Bin data + Collection data. */ // function saveAll( // address _owner, // string _collectionTitle, // bytes _collectionData, // string _binTitle, // bytes _binData // ) public returns (bool success) { // /* Save collection. */ // saveCollection(_owner, _collectionTitle, _collectionData); // /* Save bin. */ // saveBin(_owner, _collectionTitle, _binTitle, _binData); // /* Return success. */ // return true; // } /** * Save Bin */ function saveBin( string _collectionTitle, string _binTitle, bytes _data ) public returns (bool success) { /* Retrieve collection id. */ bytes32 collectionId = calcCollectionId(msg.sender, _collectionTitle); /* Retrieve bin id. */ bytes32 binId = calcBinId(collectionId, _binTitle); /* Save bin. */ return _saveBin(msg.sender, binId, _data); } // TODO Add Relayer option, using ECRecovery / signatures. /** * Save Bin */ // function saveBin( // address _owner, // string _collectionTitle, // string _binTitle, // bytes _data // ) public returns (bool success) { // /* Retrieve collection id. */ // bytes32 collectionId = calcCollectionId(_owner, _collectionTitle); // /* Retrieve bin id. */ // bytes32 binId = calcBinId(collectionId, _binTitle); // /* Save bin. */ // return _saveBin(_owner, binId, _data); // } // TODO Add Relayer option, using ECRecovery / signatures. /** * Save Bin */ // function saveBin( // address _owner, // bytes32 _collectionId, // string _binTitle, // bytes _data // ) public returns (bool success) { // /* Retrieve bin id. */ // bytes32 binId = calcBinId(_collectionId, _binTitle); // /* Save bin. */ // return _saveBin(_owner, binId, _data); // } /** * Save Bin */ function _saveBin( address _owner, bytes32 _binId, bytes _data ) private returns (bool success) { /* Set location. */ _zer0netDb.setAddress(_binId, address(this)); /* Set block number. */ _zer0netDb.setUint(_binId, block.number); /* Broadcast event. */ emit Bin(_binId, _owner, _data); /* Return success. */ return true; } /** * Save Collection */ function saveCollection( string _title, bytes _data ) public returns (bool success) { /* Calculate collection id. */ // NOTE: We DO NOT permit external (pre-calculated) ids as input. bytes32 collectionId = calcCollectionId(msg.sender, _title); /* Save collection. */ return _saveCollection(msg.sender, collectionId, _data); } // TODO Add Relayer option, using ECRecovery / signatures. /** * Save Collection */ // function saveCollection( // address _owner, // string _title, // bytes _data // ) public returns (bool success) { // /* Calculate collection id. */ // // NOTE: We DO NOT permit external (pre-calculated) ids as input. // bytes32 collectionId = calcCollectionId(_owner, _title); // /* Save collection. */ // return _saveCollection(_owner, collectionId, _data); // } /** * Save Collection * * NOTE: This performs a (possibly expensive) storage of up to 100 * bins, encoded as `bytes32 _binId`. * * On-chain (Estimated) Fees * ------------------------- * * 1. 10,000 gas : Per increment in TOTAL collection(s) count * 2. 2,048 gas : Per (bytes32) hash in list * 3. 64 gas : Per byte stored (or is this 68??) * * eg. (Re-)saving a hash list of 100 entries would * cost approx. 204,800 gas * @ 5.0 Gwei will total approx. 1M gas * @ $250 per ETH will cost approx. $0.25 USD * * IPFS (Estimated) Storage Rates * ------------------------------ * * US$ 0.05 per 1GiB / month * US$50.00 per 1TiB / month * * NOTE: ALL rates include 2x data redundancy across a global * storage network. * * NO BANDWIDTH CHARGES ARE INCURRED OVER IPFS AT THIS TIME * * The market rate for 1TiB of monthly storage from TOP * cloud providers is currently $9.99/mo. With the exception * of Amazon S3 Standard, currently $23.00/mo; and OneDrive * priced below market at $6.99/mo. * */ function _saveCollection( address _owner, bytes32 _collectionId, bytes _data ) private returns (bool success) { /* Set location. */ _zer0netDb.setAddress(_collectionId, address(this)); /* Set block number. */ _zer0netDb.setUint(_collectionId, block.number); /* Broadcast event. */ emit Collection(_collectionId, _owner, _data); /* Return success. */ return true; } /** * Set Successor * * This is the contract address that replaced this current instnace. */ function setSuccessor( address _newSuccessor ) onlyAuthBy0Admin external returns (bool success) { /* Set successor contract. */ _successor = _newSuccessor; /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /*************************************************************************** * * UTILITIES * */ /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress( bytes _address ) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data, uint _offset ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i + _offset] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } /** * Transfer Any ERC20 Token * * @notice Owner can transfer out any accidentally sent ERC20 tokens. * * @dev Provides an ERC20 interface, which allows for the recover * of any accidentally sent ERC20 tokens. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _tokens); } }
Convert Bytes32 to Bytes NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this,/
function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { return abi.encodePacked(_data);
12,708,028
pragma solidity ^0.5.0; import "./HitchensUnorderedKeySet.sol"; /** * @title A distributed tournament ledger * @author James Richards * @notice This is a pre-release work-in-progress. Use at your own risk! * * A competitive tournament among a number of competitors who participate in matches. * Competitors may be individual athletes or teams of athletes. */ contract Tournament { using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set; string public title; string public startDateTime; string public endDateTime; MeasurementTypes public measurementType = MeasurementTypes.imperial; mapping(bytes32 => Athlete) public athletes; HitchensUnorderedKeySetLib.Set athletesRegistry; mapping(bytes32 => Person) public audience; HitchensUnorderedKeySetLib.Set audienceRegistry; mapping(bytes32 => Competitor) public competitors; HitchensUnorderedKeySetLib.Set competitorsRegistry; mapping(bytes32 => Division) public divisions; HitchensUnorderedKeySetLib.Set divisionsRegistry; mapping(bytes32 => HitchensUnorderedKeySetLib.Set) divisionCompetitorsRegistry; mapping(bytes32 => HitchensUnorderedKeySetLib.Set) divisionMatchesRegistry; mapping(bytes32 => Match) public matches; HitchensUnorderedKeySetLib.Set matchesRegistry; mapping(bytes32 => HitchensUnorderedKeySetLib.Set) matchesPenaltiesRegistry; mapping(bytes32 => Name) public names; HitchensUnorderedKeySetLib.Set namesRegistry; mapping(bytes32 => Person) public participants; HitchensUnorderedKeySetLib.Set participantsRegistry; mapping(bytes32 => Penalty) public penalties; HitchensUnorderedKeySetLib.Set penaltiesRegistry; mapping(bytes32 => Round) rounds; HitchensUnorderedKeySetLib.Set roundsRegistry; mapping(bytes32 => Rule) public rules; HitchensUnorderedKeySetLib.Set rulesRegistry; mapping(bytes32 => Score) public scores; HitchensUnorderedKeySetLib.Set scoresRegistry; mapping(bytes32 => Sport) public sports; HitchensUnorderedKeySetLib.Set sportsRegistry; mapping(bytes32 => Person) public staff; HitchensUnorderedKeySetLib.Set staffRegistry; mapping(bytes32 => Team) public teams; HitchensUnorderedKeySetLib.Set teamsRegistry; mapping(bytes32 => Weight) public weights; HitchensUnorderedKeySetLib.Set weightsRegistry; address public admin; address public owner; uint idCounter; bool isStopped; event AthleteAdded(bytes32 id, string name); event SportAdded(bytes32 id, string name); event RuleAdded(bytes32 id, string name); event DivisionAdded(bytes32 id, string name); event CompetitorAddedToDivision(bytes32 divisionId, bytes32 competitorId); event CompetitorRemovedFromDivision(bytes32 divisionId, bytes32 competitorId); event CompetitorDisqualification(bytes32 matchId, bytes32 competitorId); event CompetitorDiscontinuance(bytes32 matchId, bytes32 competitorId); event MatchAdded(bytes32 matchId, bytes32 divisionId); event MatchRemoved(bytes32 matchId, bytes32 divisionId); event PenaltyAdded(bytes32 penaltyId, bytes32 competitorId, uint256 cost); event RoundAdded(bytes32 roundId, bytes32 matchId); event ScoreAdded(bytes32 scoredId, bytes32 competitorId, uint256 score); modifier onlyAdmin { require(msg.sender == admin, 'Only the tournament admin can execute'); require(!isStopped, 'This tournament has been stopped.'); _; } modifier onlyOwner { require(msg.sender == owner, 'Only the tournament owner can execute'); _; } /** * Builds a tournament assigning the msg.sender as the owner and admin of the tournament. */ constructor() public { owner = msg.sender; admin = owner; isStopped = false; } /** * Circuit breaker for a tournament that halts all tournament administration. Callable only by the tournament owner. */ function stop() public onlyOwner { isStopped = true; } /** * Circuit enabler for a tournament that enables all tournament administration. Callable only by the tournament owner. */ function start() public onlyOwner { isStopped = false; } /** * Generates a new identifier as a bytes32 value that is suitable for uniquely identifying * all things within the tournament. * * @return bytes32 a unique identifier that remains unique for each subsequent call of this function */ function newId() public returns (bytes32) { ++idCounter; return keccak256(abi.encodePacked(msg.sender, idCounter)); } /** * Allows the owner of a tournament to specify an administrator responsible for executing * the actual matches of the tournament. * * @param newAdmin address to assign administrative rights to */ function setAdmin(address newAdmin) public onlyOwner { admin = newAdmin; } /** * Set the title of this tournament to a given title, start and end * * @param _title to set as the title of this tournament * @param _start to set as the tournament start datetime * @param _end to set as the tournament end datetime */ function setDetails(string memory _title, string memory _start, string memory _end) public onlyOwner { title = _title; startDateTime = _start; endDateTime = _end; } /** * Set the title of this tournament to a given name * * @param newName a name to set as the title of this tournament */ function setTitle(string memory newName) public onlyAdmin { title = newName; } /** * ISO 8601 encoding of the start time of this tournament * * @param _start datetime when this tournament begins */ function setStartDateTime(string memory _start) public onlyAdmin { startDateTime = _start; } /** * ISO 8601 encoding of the end time of this tournament * * @param _end datetime when this tournament ends */ function setEndDateTime(string memory _end) public onlyAdmin { endDateTime = _end; } /** * Adds a sport to this tournament. Tournaments may have competitions among multiple sports * * @param name a particular, named sport, such as Judo * @param notes arbitrary notes regarding the sport, such as brief history or detailed description * @return bytes32 uniquely identifying the created sport */ function addSport(string memory name, string memory notes) public onlyAdmin returns (bytes32) { bytes32 spId = this.newId(); sportsRegistry.insert(spId); Sport storage sp = sports[spId]; sp.id = spId; sp.name = name; sp.notes = notes; emit SportAdded(sp.id, sp.name); return sp.id; } /** * Creates a rule for the tournament or a particular sport or division, such as cleanliness requirements, * or weight limitations for a division * * @param name human friendly name of the rule * @param description detailed description of the rule * @return bytes32 uniquely identifying the created rule */ function addRule(string memory name, string memory description) public onlyAdmin returns (bytes32) { bytes32 rlId = this.newId(); rulesRegistry.insert(rlId); Rule storage rl = rules[rlId]; rl.id = rlId; rl.name = name; rl.description = description; emit RuleAdded(rl.id, rl.name); return rl.id; } /** * Adds an athlete to the list of competitors of this tournament. * * @param firstName of the athlete * @param middleName of the athlete * @param lastName of the athlete * @param weightMajor the major unit of the athlete's weight, such as 100 pounds * @param weightMinor the minor unit of the athlete's weight, such as 5 ounces * @param heightMajor the major unit of the athlete's height, such as 5 feet * @param heightMinor the minor unit of the athlete's height, such as 9 inches * @return bytes32 uniquely identifying the created athlete */ function addAthlete(string memory firstName, string memory middleName, string memory lastName, uint8 weightMajor, uint8 weightMinor, uint8 heightMajor, uint8 heightMinor) public onlyAdmin returns (bytes32) { bytes32 athId = this.newId(); namesRegistry.insert(athId); participantsRegistry.insert(athId); athletesRegistry.insert(athId); competitorsRegistry.insert(athId); Name memory nm = Name({id: athId, first: firstName, middle: middleName, last: lastName}); Person memory psn = Person({id: athId, name: athId, title: 'Athlete', notes: '', role: PersonRoles.competitor}); Athlete memory ath = Athlete({person: athId, weightMajor: weightMajor, weightMinor: weightMinor, heightMajor: heightMajor, heightMinor: heightMinor}); Competitor memory cmp = Competitor({ id: athId, typeOf: CompetitorTypes.athlete }); participants[athId] = psn; names[athId] = nm; competitors[athId] = cmp; athletes[athId] = ath; emit AthleteAdded(athId, string(abi.encodePacked(nm.first,' ', nm.last))); return ath.person; } /** * Adds a division for a particular weight range to this tournament * * @param name of the division * @param notes additional information on the division * @param sportId of the sport competed upon within this division * @param weightMajor the major unit of the maximum weight a competitor may be to compete within this division * @param weightMinor the minor unit of the maximum weight a competitor may be to compete within this division * @return bytes32 uniquely identifying the created division */ function addDivision(string memory name, string memory notes, bytes32 sportId, uint8 weightMajor, uint8 weightMinor) public onlyAdmin returns (bytes32) { bytes32 divId = this.newId(); bytes32 wgtId = this.newId(); weightsRegistry.insert(wgtId); Weight storage wgt = weights[wgtId]; wgt.id = wgtId; wgt.major = weightMajor; wgt.minor = weightMinor; divisionsRegistry.insert(divId); Division storage div = divisions[divId]; div.id = divId; div.name = name; div.notes = notes; div.sport = sportId; div.weightClass = wgtId; emit DivisionAdded(divId, name); return divId; } /** * Adds a given identified competitor to a given identified division, with the requirements that * both the competitor and division exist and the competitor is not already a member of the division * * @param divisionId to which the competitor will be added * @param competitorId to be added to a division * @return bool indicating the existence of the competitor within the division */ function addCompetitor(bytes32 divisionId, bytes32 competitorId) public onlyAdmin returns (bool) { require(divisionsRegistry.exists(divisionId), "The identified division must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); require(!divisionCompetitorsRegistry[divisionId].exists(competitorId), "Competitor is already a member of the division."); divisionCompetitorsRegistry[divisionId].insert(competitorId); emit CompetitorAddedToDivision(divisionId, competitorId); return divisionCompetitorsRegistry[divisionId].exists(competitorId); } /** * Removes a given identified competitor from a given identified division, with the requirements that * both the competitor and division exist and the competitor is already a member of the division * * @param divisionId from which the competitor will be removed * @param competitorId to remove from a division * @return bool indicating the removal of the competitor from the division */ function removeCompetitor(bytes32 divisionId, bytes32 competitorId) public onlyAdmin returns (bool) { require(divisionsRegistry.exists(divisionId), "The identified division must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); require(divisionCompetitorsRegistry[divisionId].exists(competitorId), "Competitor is not already a member of the division."); divisionCompetitorsRegistry[divisionId].remove(competitorId); emit CompetitorRemovedFromDivision(divisionId, competitorId); return !divisionCompetitorsRegistry[divisionId].exists(competitorId); } /** * Conditional indicating that a given identified competitor is a member of a given identified division * * @param divisionId to check for a given competitor * @param competitorId to check for * @return bool true if the competitor exists within the division, false otherwise */ function hasCompetitor(bytes32 divisionId, bytes32 competitorId) public view onlyAdmin returns (bool) { return divisionCompetitorsRegistry[divisionId].exists(competitorId); } /** * Adds a match of a defined duration with initial notes to a given division with a given set of two or more competitors. * * @param divisionId to which the match will be added * @param comps the competitors within the match * @param duration ISO 8601 time duration of the match * @param notes possibly empty notes regarding the match * @return bytes32 uniquely identifying the created match */ function addMatch(bytes32 divisionId, bytes32[] memory comps, string memory duration, string memory notes) public onlyAdmin returns (bytes32) { require(divisionsRegistry.exists(divisionId), "The identified division must exist."); require(comps.length >= 2, "At least two competitors are required for a match."); bytes32 mtchId = this.newId(); matchesRegistry.insert(mtchId); Match storage mtch = matches[mtchId]; mtch.competitors = comps; mtch.division = divisionId; mtch.duration = duration; mtch.notes = notes; divisionMatchesRegistry[divisionId].insert(mtchId); emit MatchAdded(mtchId, divisionId); return mtchId; } /** * Removes an identified match from the set of matches. * * @param matchId to be removed * @param divisionId the division to remove the match from * @return bool true if the match was removed, false otherwise */ function removeMatch(bytes32 matchId, bytes32 divisionId) public onlyAdmin returns (bool) { require(matchesRegistry.exists(matchId), "The identified match must exist."); require(divisionMatchesRegistry[divisionId].exists(matchId), "The identified match is not within the identified division."); Match storage mtch = matches[matchId]; bytes32 divId = mtch.division; matchesRegistry.remove(matchId); divisionMatchesRegistry[divisionId].remove(matchId); emit MatchRemoved(matchId, divId); return divisionMatchesRegistry[divisionId].exists(matchId); } /** * Conditional indicating that a given identified match is a member of a given identified division * * @param matchId to check for * @param divisionId to check for the given match within * @return bool truei f the match exists, false otherwise */ function hasMatch(bytes32 matchId, bytes32 divisionId) public view onlyAdmin returns (bool) { if (!matchesRegistry.exists(matchId)) { return false; } return divisionMatchesRegistry[divisionId].exists(matchId); } /** * Accessor for the competitors within an identified match * * @param matchId to retrieve the competitors from */ function getCompetitors(bytes32 matchId) public view onlyAdmin returns (bytes32[] memory) { // require(matchesRegistry.exists(matchId), "The identified match must exist."); return matches[matchId].competitors; } /** * Mutator to set a penalty upon an identified competitor within an identified match * * @param matchId within which to assign the penalty * @param ruleId identifying the rule which has been violation * @param cost the numeric cost of the penalty upon the score of the competitor * @param competitorId identifying the competitor to be assigned the penalty */ function addPenalty(bytes32 matchId, bytes32 ruleId, uint256 cost, bytes32 competitorId) public onlyAdmin returns (bool) { require(rulesRegistry.exists(ruleId), "The identified rule must exist."); require(matchesRegistry.exists(matchId), "The identified match must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); bytes32 pnId = this.newId(); Penalty storage pen = penalties[pnId]; pen.rule = ruleId; pen.cost = cost; pen.offender = competitorId; pen.matchId = matchId; penaltiesRegistry.insert(pnId); matchesPenaltiesRegistry[matchId].insert(pnId); emit PenaltyAdded(pnId, competitorId, cost); return matchesPenaltiesRegistry[matchId].exists(pnId); } /** * Conditional indicating if a particular penalty exists within an identified match * * @param matchId to search for the penalty within * @param penaltyId of the penalty * @return bool indicating the existence of the penalty */ function hasPenalty(bytes32 matchId, bytes32 penaltyId) public view onlyAdmin returns (bool) { require(matchesRegistry.exists(matchId), "The identified match must exist."); return matchesPenaltiesRegistry[matchId].exists(penaltyId); } /** * Mutator adding a disqualification for a given competitor within an identified match * * @param matchId to add the disqualification to * @param competitorId being disqualified * @return bool indicating the outcome of the addition */ function addDisqualification(bytes32 matchId, bytes32 competitorId) public onlyAdmin returns (bool) { require(matchesRegistry.exists(matchId), "The identified match must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); Match storage mtch = matches[matchId]; mtch.disqualification = competitorId; emit CompetitorDisqualification(matchId, competitorId); return true; } /** * Conditional indicating a match has a disqualification for an identified competitor * * @param matchId to add the disqualification to * @param competitorId being disqualified * @return bool true if the competitor has been disqualified, false otherwise */ function hasDisqualification(bytes32 matchId, bytes32 competitorId) public view onlyAdmin returns (bool) { require(matchesRegistry.exists(matchId), "The identified match must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); return matches[matchId].disqualification == competitorId; } /** * Mutator adding a discontinuance for a given competitor within an identified match, i.e. if * a competitor is unable to continue due to injury * * @param matchId to add the discontinuance to * @param competitorId unable to continue * @return bool indicating the outcome of the addition */ function addDiscontinuance(bytes32 matchId, bytes32 competitorId) public onlyAdmin returns (bool) { require(matchesRegistry.exists(matchId), "The identified match must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); Match storage mtch = matches[matchId]; mtch.discontinuance = competitorId; emit CompetitorDiscontinuance(matchId, competitorId); return true; } /** * Conditional indicating a match has a discontinuance for an identified competitor * * @param matchId to add the discontinuance to * @param competitorId having the discontinuance * @return bool true if the competitor was unable to continue, false otherwise */ function hasDiscontinuance(bytes32 matchId, bytes32 competitorId) public view onlyAdmin returns (bool) { require(matchesRegistry.exists(matchId), "The identified match must exist."); require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); return matches[matchId].discontinuance == competitorId; } /** * Add a score for a given competitor with the given value * * @param competitorId of the competitor * @param value the competitor's score * @return bytes32 identifying the added score */ function addScore(bytes32 competitorId, uint256 value) public onlyAdmin returns (bytes32) { require(competitorsRegistry.exists(competitorId), "The identified competitor must exist."); bytes32 scId = this.newId(); Score storage sc = scores[scId]; sc.id = scId; sc.competitor = competitorId; sc.value = value; scoresRegistry.insert(scId); emit ScoreAdded(scId, competitorId, value); return scId; } /** * Add a scored round to the identified match * * @param matchId to add the round to * @param _scores of the match competitors * @return bytes32 identifying the added round */ function addRound(bytes32 matchId, bytes32[] memory _scores) public onlyAdmin returns (bytes32) { require(matchesRegistry.exists(matchId), "The identified match must exist."); bytes32 rndId = this.newId(); Round storage rnd = rounds[rndId]; rnd.id = rndId; rnd.scores = _scores; Match storage mtch = matches[matchId]; mtch.rounds.push(rndId); emit RoundAdded(rndId, matchId); return rndId; } /** * Accessor for the rounds of an identified match * * @param matchId to retrieve the rounds of * @return bytes32[] possibly empty array of sequential rounds */ function getRounds(bytes32 matchId) public view onlyAdmin returns (bytes32[] memory) { require(matchesRegistry.exists(matchId), "The identified match must exist."); Match storage mtch = matches[matchId]; return mtch.rounds; } /** * An athlete is a single person who competes */ struct Athlete { bytes32 person; uint8 weightMajor; uint8 weightMinor; uint8 heightMajor; uint8 heightMinor; } enum CompetitorTypes { athlete, team } /** * A competitor is a group of two or more athletes who collectively compete against other teams. */ struct Competitor { bytes32 id; CompetitorTypes typeOf; } /** * A division within the tournament for a particular set of competitors, such as competitors within a particular weight class */ struct Division { bytes32 id; bytes32 sport; string name; string notes; bytes32 weightClass; } /** * The types of measurement units that height/weight are valued in */ enum MeasurementTypes { imperial, metric } /** * The height of an athlete in imperial or metric units */ struct Height { uint8 major; uint8 minor; } /** * A match between competitors who may accumulate points within rounds, penalties from rule violations * or may be disqualified or unable to continue the competition, i.e. due to injury or emergency */ struct Match { string duration; string notes; bytes32 division; bytes32[] competitors; bytes32[] rounds; bytes32 disqualification; bytes32 discontinuance; } /** * A person name which may have at most three parts */ struct Name { bytes32 id; string first; string middle; string last; } /** * A violation of a rule for a competition match by an offending Competitor */ struct Penalty { bytes32 rule; uint256 cost; bytes32 matchId; bytes32 offender; } /** * The roles which people associated with a tournament may perform */ enum PersonRoles { coach, competitor, judge, referee, medical, other, security } /** * An individual capable of competing in a tournament */ struct Person { bytes32 id; bytes32 name; string title; string notes; PersonRoles role; } /** * A round within a match with numerical scores mapped to competitor identifiers */ struct Round { bytes32 id; bytes32[] scores; } /** * A rule governing a sport within a tournament */ struct Rule { bytes32 id; string name; string description; } /** * A numerical score for a competitor */ struct Score { bytes32 id; bytes32 competitor; uint256 value; } /** * A competitive Sport such as shuai jiao or baseball in which competitors attempt to gain the highest score * to win matches */ struct Sport { bytes32 id; string name; string notes; } /** * A group of two or more athletes who collectively compete against other teams */ struct Team { bytes32 id; bytes32 name; bytes32[] members; bytes32[] coaches; } /** * A specific weight under a supported unit of weight measurement */ struct Weight { bytes32 id; uint8 major; uint8 minor; } }
ISO 8601 encoding of the end time of this tournament _end datetime when this tournament ends/
function setEndDateTime(string memory _end) public onlyAdmin { endDateTime = _end; }
952,012
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_591(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,304
./partial_match/40/0x2416e0D9486B653836E5880B42390b2F22A71630/sources/verified-sources/0x2416e0d9486b653836e5880b42390b2f22a71630/sources/verified-sources/0x42A31ae40c0C9B0127dd7FC1CcEF24F612c8317A/sources/contracts/initialize.sol
Initialize the contract _stakedToken: staked token address _rewardToken: reward token address _rewardPerBlock: reward per block (in rewardToken) _startBlock: start block _bonusEndBlock: end block _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) _admin: admin address with ownership/ Make this contract initialized
function initialize( IBEP20 _stakedToken, IBEP20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin ) external { require(!isInitialized, "Already initialized"); require(msg.sender == SMART_ZENMASTER_FACTORY, "Not factory"); isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } uint256 decimalsRewardToken = uint256(rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); }
8,827,202
./full_match/1/0x324aD8485005cE4252F68d6a8c26e3C50E917b67/sources/project_/contracts/MrT.sol
: overrides ERC20 transfer function to introduce tax functionality to address amount is going to amount amount being sent/
function transfer(address to, uint256 amount) public virtual override returns (bool) { return taxedTransfer(_msgSender(), to, amount); }
4,933,754
pragma solidity >=0.4.21; /// @title Contract that contains main application data (storage) /// @dev Kyama-Project // OpenZeppelin's SafeMath library import "../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract Base { using SafeMath for uint256; // Total capital within the main Kyama account uint256 public totalCapital; // Total M-Bills issued by Kyama uint256 public totalMIssued; // Total Kyama M-Bill share capital uint256 public totalMShareCapital; // Struct defining an m-Debenture. [Request for m-Bills based on your current stake (share cap)] struct mDebenture { uint256 requestDate; uint256 mValRequested; uint256 mValExpected; uint256 mValRepaid; uint256 shareCap; } // Array of all m-Debentures made on Kyama mDebenture[] public mDebentures; // Length of mDebenture array uint256 public mDebentureCount; // Individual account mTx (M-Bill transaction) data struct struct mTx { uint256 valIn; // Value being deposited uint256 valOut; // Value being withdrawn address coParty; // Other party in the transaction (address(0) if no coParty) uint256 shareCap; // If applicable ... a record of share capital as a result of transaction } // Array of all m-MetaData(s) present in Kyama mTx[] public mMetaData; // Struct defining an individual account struct account { address owner; uint256 totalDeposit; uint256 totalTransfer; uint256 investmentDate; uint256 initInvestment; int256 m_running_value; uint256 totalDebenture; uint256 totalWithdrawal; uint256 m_debentureCount; uint256[] mMetaDataIndexes; uint256[] mDebentureIndexes; /** * *highestMInterest is not an accurate indicator of the highest interest rate earned by an account * Therefore, it should only be used as an indicator metric but not as a source of truth */ uint256 highestMInterest; } // Array of all accounts registered on Kyama account[] public accounts; // Length of the accounts array uint256 public accountsCount; // Mapping of registered accounts mapping (address => uint256) public registeredAccounts; // Mapping of addresses to their respective accounts // An address can only have 1 account! mapping (address => uint256) public accountIndexes; // Current M-Bill price per share uint256 public currentMPPS; // Current M-ppS increase index uint256 public currentMIndex; // Multiplier that determines average rate of increase of M-Bill ppS. // The 0-index refers to the numerator of the multiplier // The 1-index refers to the denominator of the multiplier uint256[] public ppsMultiplier; // Interest allocation multiplier that determines interest allocated to M-Bills and the Kyama Project // The 0-index corresponds to interest on M-Bills // The 1-index corresponds to profit to the Kyama Project // The 2-index corresponds to the interest division constant uint256[] public interestAllocation; // Withdrawal interest - interest rate // Interest rate charged on accrued interest on withdrawal uint256[] public withdrawalCharge; // Debenture interest - interest rate // Interest rate charged on accrued interest rate on debenture approval uint256[] public debentureCharge; // Debenture repayment interest uint256[] public debentureRepaymentI; // Maximum outstanding debentures uint256 public maxMDebentures; // Mapping of addresses that have call access to main application data mapping (address => bool) public callAccess; // Constructor function to set initial data values constructor() public { // Set initial M-Bill ppS currentMPPS = 10; // Initialize M-ppS increase index currentMIndex = 0; // Set ppS multiplier // The multiplier is 1.1, thus an average increase of 10%, and a representation of 11/10 ppsMultiplier = [11, 10]; // Set initial mDebentureCount to 0 mDebentureCount = 0; // Set initial accountsCount to 0 accountsCount = 0; // Set interest allocation multiplier // M-Bills interest allocation = 950/1000 = 95% // Kyama Project profit = 50/1000 = 5% interestAllocation = [950, 50, 1000]; // Set withdrawal charge // = 80/100 = 80% as interest is 20% on accrued interest withdrawalCharge = [80, 100]; // Set debenture charge // = 90/100 = 90% as interest rate is 10% on accrued interest debentureCharge = [90, 100]; // Set debenture repayment interest // Interest of 10% represented as 110/100 ... growth of 1.1 debentureRepaymentI = [110, 100]; // Set maximum outstanding debentures maxMDebentures = 10; // Add deploying address to call access mapping callAccess[msg.sender] = true; } // Modifier to ensure that address is approved to call into application storage modifier isApproved() { require(callAccess[msg.sender] == true, "Storage access denied."); _; } // Function to approve address for call access function approveAddress(address _toApproveAddress) external isApproved { callAccess[_toApproveAddress] = true; } // Function to revoke address from call access function revokeAddress(address _toRevokeAddress) external isApproved { callAccess[_toRevokeAddress] = false; } // Function to create a new user account function createAccount(address _toCreateAddress, uint256 _investmentAmount) external isApproved { // Create new account struct account memory newAccount; newAccount.owner = _toCreateAddress; newAccount.investmentDate = block.timestamp; newAccount.initInvestment = _investmentAmount; newAccount.m_running_value = 0; newAccount.totalDebenture = 0; newAccount.totalWithdrawal = 0; newAccount.totalTransfer = 0; newAccount.totalDeposit = 0; newAccount.m_debentureCount = 0; newAccount.highestMInterest = 0; // Add new account to accounts directory accounts.push(newAccount); uint256 newAccountPosition = accounts.length.sub(1); // Update the accounts count accountsCount = accounts.length; // Formally register the account registeredAccounts[_toCreateAddress] = 1; // Record the account index accountIndexes[_toCreateAddress] = newAccountPosition; } // Function to retrieve registration status of an address function isUserRegistered(address _toCheckAddress) public view returns (bool) { require(_toCheckAddress != address(0), "The address provided for registration check must be valid."); bool isRegistered = false; uint256 registrationStatus = registeredAccounts[_toCheckAddress]; if(registrationStatus == 1) { isRegistered = true; } return isRegistered; } // Function to get account investment date function getInvestmentDate(address _toCheckAddress) external isApproved view returns (uint256) { // Get account investment date uint256 investmentDate = accounts[accountIndexes[_toCheckAddress]].investmentDate; return investmentDate; } // Function to retrieve account initial investment function getInitialInvestment(address _toCheckAddress) external isApproved view returns (uint256) { // Get account initial investment uint256 initInvestment = accounts[accountIndexes[_toCheckAddress]].initInvestment; return initInvestment; } // Function to increment the total capital function incrementTotalCapital(uint256 _incrementAmount) external isApproved { totalCapital = totalCapital.add(_incrementAmount); } // Function to decrement the total capital function decrementTotalCapital(uint256 _decrementAmount) external isApproved { totalCapital = totalCapital.sub(_decrementAmount); } // Function to increment total M-Bills issued function incrementTotalMIssued(uint256 _incrementAmount) external isApproved { totalMIssued = totalMIssued.add(_incrementAmount); } // Function to decrement total M-Bills issued function decrementTotalMIssued(uint256 _decrementAmount) external isApproved { totalMIssued = totalMIssued.sub(_decrementAmount); } // Function to increment total M-Bill share capital function incrementMShareCap(uint256 _incrementAmount) external isApproved { totalMShareCapital = totalMShareCapital.add(_incrementAmount); } // Function to decrement total M-Bill share capital function decrementMShareCap(uint256 _decrementAmount) external isApproved { totalMShareCapital = totalMShareCapital.sub(_decrementAmount); } // Update M-Bill ppS in relation to multiplier function updateMPPs() external isApproved { if(currentMPPS <= currentMIndex) { currentMPPS = (currentMPPS.mul(ppsMultiplier[0])).div(ppsMultiplier[1]); currentMIndex = 0; } else { currentMIndex = currentMIndex.add(1); } } // Function to check if account has met investment consensus function isAccountHarmonized(address _accountAddress, uint256 _accShareCap) external view isApproved returns (bool) { uint256 accInitInvestment = accounts[accountIndexes[_accountAddress]].initInvestment; uint256 maxDebenture = getTotalDebenture(_accShareCap); uint256 totalDebenture = accounts[accountIndexes[_accountAddress]].totalDebenture; uint256 totalWithdrawal = accounts[accountIndexes[_accountAddress]].totalWithdrawal; uint256 totalTransfer = accounts[accountIndexes[_accountAddress]].totalTransfer; // Check for consensus bool isHarmonized = false; if(accInitInvestment < maxDebenture.add(totalDebenture).add(totalWithdrawal).add(totalTransfer)) { isHarmonized = true; } return isHarmonized; } // Function to record an M-Bill transaction to mMetaData function recordMData(address _accountAddress, uint256 _valIn, uint256 _valOut, address _coParty, uint256 _shareCap) external isApproved { require(isUserRegistered(_accountAddress) == true, "Address provided is not linked to a Kyama account."); require(_valIn >= 0, "Invalid deposit amount."); require(_valOut >= 0, "Invalid withdrawal amount."); require(_shareCap >= 0, "Invalid share capital amount"); require(_coParty != _accountAddress, "Co-Party address provided is invalid."); // Create a new M-Bill transaction record mTx memory newMTx = mTx({ valIn: _valIn, valOut: _valOut, coParty: _coParty, shareCap: _shareCap }); mMetaData.push(newMTx); uint256 newMTxPosition = mMetaData.length.sub(1); // Update account counters if(_valIn > 0) { require(accounts[accountIndexes[_accountAddress]].m_running_value + int256(_valIn) > accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _valIn error"); accounts[accountIndexes[_accountAddress]].m_running_value += int256(_valIn); accounts[accountIndexes[_accountAddress]].totalDeposit = accounts[accountIndexes[_accountAddress]].totalDeposit.add(_valIn); } if(_valOut > 0) { require(accounts[accountIndexes[_accountAddress]].m_running_value - int256(_valOut) < accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _valOut error"); accounts[accountIndexes[_accountAddress]].m_running_value -= int256(_valOut); if(_coParty == address(0)) { accounts[accountIndexes[_accountAddress]].totalWithdrawal = accounts[accountIndexes[_accountAddress]].totalWithdrawal.add(_valOut); } else { accounts[accountIndexes[_accountAddress]].totalTransfer = accounts[accountIndexes[_accountAddress]].totalTransfer.add(_valOut); } } // Record transaction position to account accounts[accountIndexes[_accountAddress]].mMetaDataIndexes.push(newMTxPosition); } // Function to get account total MBill interest value function getMInterest(uint256 _accShareCap) internal isApproved view returns(uint256) { // Get total interest on the main Kyama account uint256 totalInterest = totalCapital.sub(totalMIssued); // Get total interest value on account M-Bills uint256 totalMInterestVal = (_accShareCap.mul(interestAllocation[0]).mul(totalInterest)) .div((totalMShareCapital.mul(interestAllocation[2]))); return totalMInterestVal; } // Function to get total Kyama revenue function revenue() public view returns(uint256) { // Get total interest on the main Kyama account uint256 totalInterest = totalCapital.sub(totalMIssued); // Get total revenue uint256 totalRevenue = (totalInterest.mul(interestAllocation[1])) .div(interestAllocation[2]); return totalRevenue; } // Function to get account total MBill raw value function getMRawVal(uint256 _accShareCap) internal isApproved view returns(uint256) { // Get total raw M-Bill value on account uint256 MRawVal = (_accShareCap.mul(totalMIssued)).div(totalMShareCapital); return MRawVal; } // Function to get account total M-Bill value function getTotalMVal(uint256 _accShareCap) public isApproved view returns(uint256) { // Get total raw M-Bill value on account uint256 totalMVal = getMRawVal(_accShareCap); // Get total interest value on account M-Bills uint256 totalMInterestVal = getMInterest(_accShareCap); // Total account value uint256 totalAccVal = totalMVal.add(totalMInterestVal); return totalAccVal; } // Function to get total M-Bill withdrawable value from acount function getTotalMWithdrawable(uint256 _accShareCap) public view isApproved returns(uint256) { // Get total raw M-Bill value on account uint256 totalMVal = getMRawVal(_accShareCap); // Get total interest value on account M-Bills uint256 totalMInterestVal = getMInterest(_accShareCap); // Get account withdrawable interest uint256 withdrawableInterest = ((totalMInterestVal).mul(withdrawalCharge[0])).div(withdrawalCharge[1]); // Get account maximum withdrawable amount uint256 maxWithdrawableAmount = (totalMVal).add(withdrawableInterest); return maxWithdrawableAmount; } // Function to get debit costs(withdrawal and debenture approval cost) function getDebitCost(uint256 _accShareCap, uint256 _debitAmount, bool _isWithdrawal) external view isApproved returns(uint256) { uint256 totalMInterestVal = getMInterest(_accShareCap); uint256 totalDebitable = uint256(0); uint256 debitableInterest = uint256(0); if(_isWithdrawal == true) { totalDebitable = getTotalMWithdrawable(_accShareCap); debitableInterest = ((totalMInterestVal).mul(withdrawalCharge[0])).div(withdrawalCharge[1]); } else { totalDebitable = getTotalDebenture(_accShareCap); debitableInterest = ((totalMInterestVal).mul(debentureCharge[0])).div(debentureCharge[1]); } if(totalDebitable == uint256(0)) { return uint256(0); } // Get ratio of debit amount to total debitable value uint256 percDebitable = (_debitAmount.mul(100)).div(totalDebitable); if(percDebitable == uint256(0)) { percDebitable = 1; } // Get ratio of (100% - debit-charge%) of total account interest to debit amount uint256 remDebitableInterest = totalMInterestVal.sub(debitableInterest); // Get debit cost uint256 debitCost = (percDebitable.mul(remDebitableInterest)).div(100); return debitCost; } // Function to get an account's maximum M-Bill debenture request amount function getTotalDebenture(uint256 _accShareCap) public view isApproved returns(uint256) { // Get total raw M-Bill value on account uint256 totalMVal = getMRawVal(_accShareCap); // Get total interest value on account M-Bills uint256 totalMInterestVal = getMInterest(_accShareCap); // Get account debenture interest uint256 debentureInterest = ((totalMInterestVal).mul(debentureCharge[0])).div(debentureCharge[1]); // Get account maximum debenture amount uint256 maxDebentureAmount = (totalMVal).add(debentureInterest); return maxDebentureAmount; } // Function to record M-Bill debenture tx function recordMDebenture(address _accountAddress, uint256 _valRequested, uint256 _shareCap) external isApproved { // Get the value expected uint256 valExpected = (_valRequested.mul(debentureRepaymentI[0])).div(debentureRepaymentI[1]); // Create a new M-Bill debenture tx mDebenture memory newMDebenture; newMDebenture.requestDate = block.timestamp; newMDebenture.mValRequested = _valRequested; newMDebenture.mValExpected = valExpected; newMDebenture.mValRepaid = uint256(0); newMDebenture.shareCap = _shareCap; // Record tx mDebentures.push(newMDebenture); uint256 newTxPosition = mDebentures.length.sub(1); // Update m_running_value require(accounts[accountIndexes[_accountAddress]].m_running_value - int256(_valRequested) < accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _valRequested error"); accounts[accountIndexes[_accountAddress]].m_running_value -= int256(_valRequested); // Update totalDebenture accounts[accountIndexes[_accountAddress]].totalDebenture = accounts[accountIndexes[_accountAddress]].totalDebenture.add(_valRequested); // Update mDebentureCount mDebentureCount = mDebentures.length; // Update account accounts[accountIndexes[_accountAddress]].mDebentureIndexes.push(newTxPosition); accounts[accountIndexes[_accountAddress]].m_debentureCount = accounts[accountIndexes[_accountAddress]].m_debentureCount.add(1); } // Functon to get the current number of M-Bill debentures outstanding in an account function outstandingMDebentures(address _accountAddress) public isApproved view returns(uint256) { uint256 outstandingDebentures = accounts[accountIndexes[_accountAddress]].m_debentureCount; if(outstandingDebentures > 30) { return uint256(0); } else { return outstandingDebentures; } } // Function to get the total number of debentures in an account (both outstanding and resolved) function totalDebentures(address _accountAddress) external isApproved view returns(uint256) { return accounts[accountIndexes[_accountAddress]].mDebentureIndexes.length; } // Function to get a particular debenture function retrieveDebenture(address _accountAddress, uint256 _debentureIndex) external isApproved view returns(uint256, uint256, uint256, uint256, uint256) { // Get debenture mDebenture memory xDebenture = mDebentures[accounts[accountIndexes[_accountAddress]].mDebentureIndexes[_debentureIndex]]; uint256 mRequestDate = xDebenture.requestDate; uint256 mRequested = xDebenture.mValRequested; uint256 mExpected = xDebenture.mValExpected; uint256 mRepaid = xDebenture.mValRepaid; uint256 mShareCap = xDebenture.shareCap; return (mRequestDate, mRequested, mExpected, mRepaid, mShareCap); } // Function to get total number of mData transactions in an account function totalMBillTxs(address _accountAddress) external isApproved view returns(uint256) { return accounts[accountIndexes[_accountAddress]].mMetaDataIndexes.length; } // Function to get a particular MBill transaction function retrieveMTx(address _accountAddress, uint256 _TxIndex) external isApproved view returns(uint256, uint256, address, uint256) { // Get Tx mTx memory xMTx = mMetaData[accounts[accountIndexes[_accountAddress]].mMetaDataIndexes[_TxIndex]]; uint256 valIn = xMTx.valIn; uint256 valOut = xMTx.valOut; address coParty = xMTx.coParty; uint256 shareCap = xMTx.shareCap; return (valIn, valOut, coParty, shareCap); } // Function to get immediate payable debenture function getImmediateDebenture(address _accountAddress) internal isApproved view returns(int256) { // Find M-Bill debenture next in line to be cleared uint256 pendingMDebentures = outstandingMDebentures(_accountAddress); // Find total M-Bill debentures uint256 totalMDebentures = accounts[accountIndexes[_accountAddress]].mDebentureIndexes.length; if(pendingMDebentures == 0 || totalMDebentures == 0) { return int256(-1); } else { uint256 MDebentureIndex = accounts[accountIndexes[_accountAddress]].mDebentureIndexes[totalMDebentures.sub(pendingMDebentures)]; return int256(MDebentureIndex); } } // Get an account's immediate payable debenture balance // This is the outstanding amount on the longest outstanding loan balance function immediatePayableM(address _accountAddress) external isApproved view returns(uint256) { // Find M-Bill debenture next in line to be cleared int256 MDebentureIndex = getImmediateDebenture(_accountAddress); if(MDebentureIndex == int256(-1)) { return uint256(0); } else { mDebenture memory immediateMDebenture = mDebentures[uint256(MDebentureIndex)]; // Get value expected to be repaid to clear M-Bill debenture uint256 mValExpected = immediateMDebenture.mValExpected; uint256 mValRepaid = immediateMDebenture.mValRepaid; uint256 debentureBalance = mValExpected.sub(mValRepaid); return debentureBalance; } } // Get an account's immediate payable share capital from M-Bill debenture function immediateMShareCap(address _accountAddress) external isApproved view returns(uint256) { // Find M-Bill debenture next in line to be cleared int256 MDebentureIndex = getImmediateDebenture(_accountAddress); if(MDebentureIndex == int256(-1)) { return uint256(0); } else { mDebenture memory immediateMDebenture = mDebentures[uint256(MDebentureIndex)]; // Get share capital uint256 mShareCap = immediateMDebenture.shareCap; return mShareCap; } } // Pay off portion or entire outstanding balance of immediate M-Bill debenture function payImmediatePayableM(address _accountAddress, uint256 _payableValue) external isApproved { // Find M-Bill debenture next in line to be cleared int256 MDebentureIndex = getImmediateDebenture(_accountAddress); if(MDebentureIndex != int256(-1)) { mDebenture storage immediateMDebenture = mDebentures[uint256(MDebentureIndex)]; // Update debenture value repayed uint256 mValRepaid = immediateMDebenture.mValRepaid; immediateMDebenture.mValRepaid = mValRepaid.add(_payableValue); // Update outstanding debenture count if necessary uint256 updatedMValRepaid = immediateMDebenture.mValRepaid; uint256 mValExpected = immediateMDebenture.mValExpected; if(updatedMValRepaid >= mValExpected) { accounts[accountIndexes[_accountAddress]].m_debentureCount = accounts[accountIndexes[_accountAddress]].m_debentureCount.sub(1); } // Update m_running_value require(accounts[accountIndexes[_accountAddress]].m_running_value + int256(_payableValue) > accounts[accountIndexes[_accountAddress]].m_running_value, "Running value _payableValue error"); accounts[accountIndexes[_accountAddress]].m_running_value += int256(_payableValue); } } // Get account total interest value function accountTotalInterest(address _accountAddress, uint256 _accShareCap) public isApproved returns(uint256) { // Get account running value int256 accRunningVal = accounts[accountIndexes[_accountAddress]].m_running_value; uint256 currentAccountInterest = 0; if(accRunningVal > int256(0)) { uint256 runningVal = uint256(accRunningVal); uint256 totalMVal = getTotalMVal(_accShareCap); if(totalMVal > runningVal) { currentAccountInterest = totalMVal.sub(runningVal); } } uint256 accHighestInterest = accounts[accountIndexes[_accountAddress]].highestMInterest; if(accHighestInterest >= currentAccountInterest) { return accHighestInterest; } else { accounts[accountIndexes[_accountAddress]].highestMInterest = currentAccountInterest; return currentAccountInterest; } } // Get account total debenture function accountTotalDebenture(address _accountAddress) external view isApproved returns(uint256) { uint256 totalDebenture = accounts[accountIndexes[_accountAddress]].totalDebenture; if(totalDebenture > 0) { return totalDebenture; } else { return uint256(0); } } // Get account total withdrawal function accountTotalWithdrawal(address _accountAddress) external view isApproved returns(uint256) { uint256 totalWithdrawal = accounts[accountIndexes[_accountAddress]].totalWithdrawal; if(totalWithdrawal > 0) { return totalWithdrawal; } else { return uint256(0); } } // Get account total transfer function accountTotalTransfer(address _accountAddress) external view isApproved returns(uint256) { uint256 totalTransfer = accounts[accountIndexes[_accountAddress]].totalTransfer; if(totalTransfer > 0) { return totalTransfer; } else { return uint256(0); } } // Get account total deposit function accountTotalDeposit(address _accountAddress) external view isApproved returns(uint256) { uint256 totalDeposit = accounts[accountIndexes[_accountAddress]].totalDeposit - accounts[accountIndexes[_accountAddress]].initInvestment; if(totalDeposit > 0) { return totalDeposit; } else { return uint256(0); } } }
Function to get total Kyama revenue Get total interest on the main Kyama account Get total revenue
function revenue() public view returns(uint256) { uint256 totalInterest = totalCapital.sub(totalMIssued); uint256 totalRevenue = (totalInterest.mul(interestAllocation[1])) .div(interestAllocation[2]); return totalRevenue; }
6,488,285
./partial_match/1/0x2C337F74a52005EdBFb931f82Ba7743189fC8024/sources/contracts/protocol/tokenization/base/IncentivizedERC20.sol
Update the name of the token newName The new name for the token/
function _setName(string memory newName) internal { _name = newName; }
4,320,373
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: VaultCoreInterface.sol pragma solidity 0.8.9; abstract contract VaultCoreInterface { function getVersion() public pure virtual returns (uint); function typeOfContract() public pure virtual returns (bytes32); function approveToken( uint256 _tokenId, address _tokenContractAddress) external virtual; } // File: RoyaltyRegistryInterface.sol pragma solidity 0.8.9; /** * Interface to the RoyaltyRegistry responsible for looking payout addresses */ abstract contract RoyaltyRegistryInterface { function getAddress(address custodial) external view virtual returns (address); function getMediaCustomPercentage(uint256 mediaId, address tokenAddress) external view virtual returns(uint16); function getExternalTokenPercentage(uint256 tokenId, address tokenAddress) external view virtual returns(uint16, uint16); function typeOfContract() virtual public pure returns (string calldata); function VERSION() virtual public pure returns (uint8); } // File: ApprovedCreatorRegistryInterface.sol pragma solidity 0.8.9; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ abstract contract ApprovedCreatorRegistryInterface { function getVersion() virtual public pure returns (uint); function typeOfContract() virtual public pure returns (string calldata); function isOperatorApprovedForCustodialAccount( address _operator, address _custodialAddress) virtual public view returns (bool); } // File: utils/Collaborator.sol pragma solidity 0.8.9; library Collaborator { bytes32 public constant TYPE_HASH = keccak256("Share(address account,uint48 value,uint48 royalty)"); struct Share { address payable account; uint48 value; uint48 royalty; } function hash(Share memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value, part.royalty)); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: OBOControl.sol pragma solidity 0.8.9; contract OBOControl is Ownable { address public oboAdmin; uint256 constant public newAddressWaitPeriod = 1 days; bool public isInitialOBOAdded = false; // List of approved on behalf of users. mapping (address => uint256) public approvedOBOs; event NewOBOAddressEvent( address OBOAddress, bool action); event NewOBOAdminAddressEvent( address oboAdminAddress); modifier onlyOBOAdmin() { require(owner() == _msgSender() || oboAdmin == _msgSender(), "not oboAdmin"); _; } function setOBOAdmin(address _oboAdmin) external onlyOwner { oboAdmin = _oboAdmin; emit NewOBOAdminAddressEvent(_oboAdmin); } /** * Add a new approvedOBO address. The address can be used after wait period. */ function addApprovedOBO(address _oboAddress) external onlyOBOAdmin { require(_oboAddress != address(0), "cant set to 0x"); require(approvedOBOs[_oboAddress] == 0, "already added"); approvedOBOs[_oboAddress] = block.timestamp; emit NewOBOAddressEvent(_oboAddress, true); } /** * Removes an approvedOBO immediately. */ function removeApprovedOBO(address _oboAddress) external onlyOBOAdmin { delete approvedOBOs[_oboAddress]; emit NewOBOAddressEvent(_oboAddress, false); } /* * Add OBOAddress for immediate use. This is an internal only Fn that is called * only when the contract is deployed. */ function addApprovedOBOImmediately(address _oboAddress) internal onlyOwner { require(_oboAddress != address(0), "addr(0)"); // set the date to one in past so that address is active immediately. approvedOBOs[_oboAddress] = block.timestamp - newAddressWaitPeriod - 1; emit NewOBOAddressEvent(_oboAddress, true); } function addApprovedOBOAfterDeploy(address _oboAddress) external onlyOBOAdmin { require(isInitialOBOAdded == false, "OBO already added"); addApprovedOBOImmediately(_oboAddress); isInitialOBOAdded = true; } /* * Helper function to verify is a given address is a valid approvedOBO address. */ function isValidApprovedOBO(address _oboAddress) public view returns (bool) { uint256 createdAt = approvedOBOs[_oboAddress]; if (createdAt == 0) { return false; } return block.timestamp - createdAt > newAddressWaitPeriod; } /** * @dev Modifier to make the obo calls only callable by approved addressess */ modifier isApprovedOBO() { require(isValidApprovedOBO(msg.sender), "unauthorized OBO user"); _; } } // File: @openzeppelin/contracts/security/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: DigitalMediaToken.sol pragma solidity 0.8.9; contract DigitalMediaToken is ERC721, OBOControl, Pausable { uint256 public currentSupply = 0; // creator address has to be set during deploy via constructor only. address public singleCreatorAddress; address public signerAddress; bool public enableExternalMinting; bool public canRoyaltyRegistryChange = true; struct DigitalMedia { uint32 totalSupply; // The total supply of collectibles available uint32 printIndex; // The current print index address creator; // The creator of the collectible uint16 royalty; bool immutableMedia; Collaborator.Share[] collaborators; string metadataPath; // Hash of the media content, with the actual data stored on a secondary // data store (ideally decentralized) } struct DigitalMediaRelease { uint32 printEdition; // The unique edition number of this digital media release uint256 digitalMediaId; // Reference ID to the digital media metadata } ApprovedCreatorRegistryInterface public creatorRegistryStore; RoyaltyRegistryInterface public royaltyStore; VaultCoreInterface public vaultStore; // Event fired when a new digital media is created. No point in returning printIndex // since its always zero when created. event DigitalMediaCreateEvent( uint256 id, address creator, uint32 totalSupply, uint32 royalty, bool immutableMedia, string metadataPath); event DigitalMediaReleaseCreateEvent( uint256 id, address owner, uint32 printEdition, string tokenURI, uint256 digitalMediaId); // Event fired when a creator assigns a new creator address. event ChangedCreator( address creator, address newCreator); // Event fired when a digital media is burned event DigitalMediaBurnEvent( uint256 id, address caller); // Event fired when burning a token event DigitalMediaReleaseBurnEvent( uint256 tokenId, address owner); event NewSignerEvent( address signer); event NewRoyaltyEvent( uint16 value); // ID to Digital Media object mapping (uint256 => DigitalMedia) public idToDigitalMedia; // Maps internal ERC721 token ID to digital media release object. mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease; // Maps a creator address to a new creator address. Useful if a creator // changes their address or the previous address gets compromised. mapping (address => address) public changedCreators; constructor(string memory _tokenName, string memory _tokenSymbol) ERC721(_tokenName, _tokenSymbol) {} // Set the creator registry address upon construction. Immutable. function setCreatorRegistryStore(address _crsAddress) internal { ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress); // require(candidateCreatorRegistryStore.getVersion() == 1, "registry store is not version 1"); // Simple check to make sure we are adding the registry contract indeed // https://fravoll.github.io/solidity-patterns/string_equality_comparison.html bytes32 contractType = keccak256(abi.encodePacked(candidateCreatorRegistryStore.typeOfContract())); // keccak256(abi.encodePacked("approvedCreatorRegistry")) = 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 // keccak256(abi.encodePacked("approvedCreatorRegistryReadOnly")) = 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791 require( contractType == 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 || contractType == 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791, "not crtrRegistry"); creatorRegistryStore = candidateCreatorRegistryStore; } function setRoyaltyRegistryStore(address _royaltyStore) external whenNotPaused onlyOBOAdmin { require(canRoyaltyRegistryChange == true, "no"); RoyaltyRegistryInterface candidateRoyaltyStore = RoyaltyRegistryInterface(_royaltyStore); require(candidateRoyaltyStore.VERSION() == 1, "roylty v!= 1"); bytes32 contractType = keccak256(abi.encodePacked(candidateRoyaltyStore.typeOfContract())); // keccak256(abi.encodePacked("royaltyRegistry")) = 0xb590ff355bf2d720a7e957392d3b76fd1adda1832940640bf5d5a7c387fed323 require(contractType == 0xb590ff355bf2d720a7e957392d3b76fd1adda1832940640bf5d5a7c387fed323, "not royalty"); royaltyStore = candidateRoyaltyStore; } function setRoyaltyRegistryForever() external whenNotPaused onlyOwner { canRoyaltyRegistryChange = false; } function setVaultStore(address _vaultStore) external whenNotPaused onlyOwner { VaultCoreInterface candidateVaultStore = VaultCoreInterface(_vaultStore); bytes32 contractType = candidateVaultStore.typeOfContract(); require(contractType == 0x6d707661756c7400000000000000000000000000000000000000000000000000, "invalid mpvault"); vaultStore = candidateVaultStore; } /* * Set signer address on the token contract. Setting signer means we are opening * the token contract for external accounts to create tokens. Call this to change * the signer immediately. */ function setSignerAddress(address _signerAddress, bool _enableExternalMinting) external whenNotPaused isApprovedOBO { require(_signerAddress != address(0), "cant be zero"); signerAddress = _signerAddress; enableExternalMinting = _enableExternalMinting; emit NewSignerEvent(signerAddress); } /** * Validates that the Registered store is initialized. */ modifier registryInitialized() { require(address(creatorRegistryStore) != address(0), "registry = 0x0"); _; } /** * Validates that the Vault store is initialized. */ modifier vaultInitialized() { require(address(vaultStore) != address(0), "vault = 0x0"); _; } function _setCollaboratorsOnDigitalMedia(DigitalMedia storage _digitalMedia, Collaborator.Share[] memory _collaborators) internal { uint total = 0; uint totalRoyalty = 0; for (uint i = 0; i < _collaborators.length; i++) { require(_collaborators[i].account != address(0x0) || _collaborators[i].account != _digitalMedia.creator, "collab 0x0/creator"); require(_collaborators[i].value != 0 || _collaborators[i].royalty != 0, "share/royalty = 0"); _digitalMedia.collaborators.push(_collaborators[i]); total = total + _collaborators[i].value; totalRoyalty = totalRoyalty + _collaborators[i].royalty; } require(total <= 10000, "total <=10000"); require(totalRoyalty <= 10000, "totalRoyalty <=10000"); } /** * Creates a new digital media object. * @param _creator address the creator of this digital media * @param _totalSupply uint32 the total supply a creation could have * @param _metadataPath string the path to the ipfs metadata * @return uint the new digital media id */ function _createDigitalMedia( address _creator, uint256 _onchainId, uint32 _totalSupply, string memory _metadataPath, Collaborator.Share[] memory _collaborators, uint16 _royalty, bool _immutableMedia, uint256 contractSupply) internal returns (uint) { // If this is a single creator contract make sure _owner matches single creator if (singleCreatorAddress != address(0)) { require(singleCreatorAddress == _creator, "Creator must match single creator address"); } // If token contract's max supply is reached error out. if (contractSupply > 0) { require(currentSupply < contractSupply, "total supply reached"); } // Verify this media does not exist already DigitalMedia storage _digitalMedia = idToDigitalMedia[_onchainId]; require(_digitalMedia.creator == address(0), "media already exists"); // TODO: Dannie check this require throughly. require((_totalSupply > 0) && address(_creator) != address(0) && _royalty <= 10000, "invalid params"); _digitalMedia.printIndex = 0; _digitalMedia.totalSupply = _totalSupply; _digitalMedia.creator = _creator; _digitalMedia.metadataPath = _metadataPath; _digitalMedia.immutableMedia = _immutableMedia; _digitalMedia.royalty = _royalty; _setCollaboratorsOnDigitalMedia(_digitalMedia, _collaborators); currentSupply = currentSupply + 1; emit DigitalMediaCreateEvent( _onchainId, _creator, _totalSupply, _royalty, _immutableMedia, _metadataPath); return _onchainId; } /** * Creates _count number of new digital media releases (i.e a token). * Bumps up the print index by _count. * @param _owner address the owner of the digital media object * @param _digitalMediaId uint256 the digital media id */ function _createDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint256[] memory _releaseIds) internal { require(_releaseIds.length > 0 && _releaseIds.length < 10000, "0 < count <= 10000"); DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; require(_digitalMedia.creator != address(0), "media does not exist"); uint32 currentPrintIndex = _digitalMedia.printIndex; require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved"); require(_releaseIds.length + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded."); for (uint32 i=0; i < _releaseIds.length; i++) { uint256 newDigitalMediaReleaseId = _releaseIds[i]; DigitalMediaRelease storage release = tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId]; require(release.printEdition == 0, "tokenId already used"); uint32 newPrintEdition = currentPrintIndex + 1 + i; release.printEdition = newPrintEdition; release.digitalMediaId = _digitalMediaId; emit DigitalMediaReleaseCreateEvent( newDigitalMediaReleaseId, _owner, newPrintEdition, _digitalMedia.metadataPath, _digitalMediaId ); // This will assign ownership and also emit the Transfer event as per ERC721 _mint(_owner, newDigitalMediaReleaseId); } _digitalMedia.printIndex = _digitalMedia.printIndex + uint32(_releaseIds.length); } /** * Checks that a given caller is an approved creator and is allowed to mint or burn * tokens. If the creator was changed it will check against the updated creator. * @param _caller the calling address * @return bool allowed or not */ function _checkApprovedCreator(address _creator, address _caller) internal view returns (bool) { address approvedCreator = changedCreators[_creator]; if (approvedCreator != address(0)) { return approvedCreator == _caller; } else { return _creator == _caller; } } /** * Burns a token for a given tokenId and caller. * @param _tokenId the id of the token to burn. * @param _caller the address of the caller. */ function _burnToken(uint256 _tokenId, address _caller) internal { address owner = ownerOf(_tokenId); require(_isApprovedOrOwner(_caller, _tokenId), "ERC721: burn caller is not owner nor approved"); _burn(_tokenId); delete tokenIdToDigitalMediaRelease[_tokenId]; emit DigitalMediaReleaseBurnEvent(_tokenId, owner); } /** * Burns a digital media. Once this function succeeds, this digital media * will no longer be able to mint any more tokens. Existing tokens need to be * burned individually though. * @param _digitalMediaId the id of the digital media to burn * @param _caller the address of the caller. */ function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal { DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; require(_digitalMedia.creator != address(0), "media does not exist"); require(_checkApprovedCreator(_digitalMedia.creator, _caller) || isApprovedForAll(_digitalMedia.creator, _caller), "Failed digital media burn. Caller not approved."); _digitalMedia.printIndex = _digitalMedia.totalSupply; emit DigitalMediaBurnEvent(_digitalMediaId, _caller); } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_tokenId]; uint256 _digitalMediaId = digitalMediaRelease.digitalMediaId; DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; string memory prefix = "ipfs://"; return string(abi.encodePacked(prefix, string(_digitalMedia.metadataPath))); } /* * Look up a royalty payout address if royaltyStore is set otherwise we returns * the same argument. */ function _getRoyaltyAddress(address custodial) internal view returns(address) { return address(royaltyStore) == address(0) ? custodial : royaltyStore.getAddress(custodial); } } // File: DigitalMediaCore.sol pragma solidity 0.8.9; contract DigitalMediaCore is DigitalMediaToken { using ECDSA for bytes32; uint8 constant public VERSION = 3; // if the contract can have a total of only 10,000 tokens set the totalMediaSupply // during the contract deployment. I could nt define a immutable variable in DigitalMediaToken // So creating the variable here and instantiating it in constructor and passing // it down to the internal functions. uint256 public immutable totalMediaSupply; struct DigitalMediaCreateRequest { uint256 onchainId; // onchain id for this media uint32 totalSupply; // The total supply of collectibles available address creator; // The creator of the collectible uint16 royalty; bool immutableMedia; Collaborator.Share[] collaborators; string metadataPath; // Hash of the media content uint256[] releaseIds; // number of releases to mint } struct DigitalMediaUpdateRequest { uint256 onchainId; // onchain id for this media uint256 metadataId; uint32 totalSupply; // The total supply of collectibles available address creator; // The creator of the collectible uint16 royalty; Collaborator.Share[] collaborators; string metadataPath; // Hash of the media content } struct DigitalMediaReleaseCreateRequest { uint256 digitalMediaId; uint256[] releaseIds; // number of releases to mint address owner; } struct TokenDestinationRequest { uint256 tokenId; address destinationAddress; } struct ChainSignatureRequest { uint256 onchainId; address owner; } struct PayoutInfo { address user; uint256 amount; } event DigitalMediaUpdateEvent( uint256 id, uint32 totalSupply, uint16 royalty, string metadataPath, uint256 metadataId); event MediasImmutableEvent( uint256[] mediaIds); event MediaImmutableEvent( uint256 mediaId); constructor(string memory _tokenName, string memory _tokenSymbol, address _crsAddress, uint256 _totalSupply) DigitalMediaToken(_tokenName, _tokenSymbol) { setCreatorRegistryStore(_crsAddress); totalMediaSupply = _totalSupply; } /** * Retrieves a Digital Media object. */ function getDigitalMedia(uint256 _id) external view returns (DigitalMedia memory) { DigitalMedia memory _digitalMedia = idToDigitalMedia[_id]; require(_digitalMedia.creator != address(0), "DigitalMedia not found."); return _digitalMedia; } /** * Ok I am not proud of this function but sale conract needs to getDigitalMedia * while I tried to write a interface file DigitalMediaBurnInterfaceV3.sol I could * not include the DigitalMedia struct in that abstract contract. So I am writing * another endpoint to return just the bare minimum data required for the sale contract. */ function getDigitalMediaForSale(uint256 _id) external view returns( address, bool, uint16) { DigitalMedia storage _digitalMedia = idToDigitalMedia[_id]; require(_digitalMedia.creator != address(0), "DigitalMedia not found."); return (_digitalMedia.creator, _digitalMedia.collaborators.length > 0, _digitalMedia.royalty); } /** * Retrieves a Digital Media Release (i.e a token) */ function getDigitalMediaRelease(uint256 _id) external view returns (DigitalMediaRelease memory) { require(_exists(_id), "release does not exist"); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id]; return digitalMediaRelease; } /** * Creates a new digital media object and mints it's first digital media release token. * The onchainid and creator has to be signed by signerAddress in order to create. * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleases( DigitalMediaCreateRequest memory request, bytes calldata signature) external whenNotPaused { require(request.creator == msg.sender, "msgSender != creator"); ChainSignatureRequest memory signatureRequest = ChainSignatureRequest(request.onchainId, request.creator); _verifyReleaseRequestSignature(signatureRequest, signature); uint256 digitalMediaId = _createDigitalMedia(msg.sender, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); _createDigitalMediaReleases(msg.sender, digitalMediaId, request.releaseIds); } /** * Creates a new digital media release (token) for a given digital media id. * This request needs to be signed by the authorized signerAccount to prevent * from user stealing media & release ids on chain and frontrunning. * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaReleases( DigitalMediaReleaseCreateRequest memory request) external whenNotPaused { // require(request.owner == msg.sender, "owner != msg.sender"); require(signerAddress != address(0), "signer not set"); _createDigitalMediaReleases(msg.sender, request.digitalMediaId, request.releaseIds); } /** * Creates a new digital media object and mints it's digital media release tokens. * Called on behalf of the _owner. Pass count to mint `n` number of tokens. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleases( DigitalMediaCreateRequest memory request) external whenNotPaused isApprovedOBO { uint256 digitalMediaId = _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); _createDigitalMediaReleases(request.creator, digitalMediaId, request.releaseIds); } /** * Create many digital medias in one call. */ function oboCreateManyDigitalMedias( DigitalMediaCreateRequest[] memory requests) external whenNotPaused isApprovedOBO { for (uint32 i=0; i < requests.length; i++) { DigitalMediaCreateRequest memory request = requests[i]; _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); } } /** * Creates multiple digital media releases (tokens) for a given digital media id. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaReleases( DigitalMediaReleaseCreateRequest memory request) external whenNotPaused isApprovedOBO { _createDigitalMediaReleases(request.owner, request.digitalMediaId, request.releaseIds); } /* * Create multiple digital medias and associated releases (tokens). Called on behalf * of the _owner. Each media should mint atleast 1 token. * No creations of any kind are allowed when the contract is paused. */ function oboCreateManyDigitalMediasAndReleases( DigitalMediaCreateRequest[] memory requests) external whenNotPaused isApprovedOBO { for (uint32 i=0; i < requests.length; i++) { DigitalMediaCreateRequest memory request = requests[i]; uint256 digitalMediaId = _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); _createDigitalMediaReleases(request.creator, digitalMediaId, request.releaseIds); } } /* * Create multiple releases (tokens) associated with existing medias. Called on behalf * of the _owner. * No creations of any kind are allowed when the contract is paused. */ function oboCreateManyReleases( DigitalMediaReleaseCreateRequest[] memory requests) external whenNotPaused isApprovedOBO { for (uint32 i=0; i < requests.length; i++) { DigitalMediaReleaseCreateRequest memory request = requests[i]; DigitalMedia storage _digitalMedia = idToDigitalMedia[request.digitalMediaId]; require(_digitalMedia.creator != address(0), "DigitalMedia not found."); _createDigitalMediaReleases(request.owner, request.digitalMediaId, request.releaseIds); } } /** * Override the isApprovalForAll to check for a special oboApproval list. Reason for this * is that we can can easily remove obo operators if they every become compromised. */ function isApprovedForAll(address _owner, address _operator) public view override registryInitialized returns (bool) { if (creatorRegistryStore.isOperatorApprovedForCustodialAccount(_operator, _owner) == true) { return true; } else { return super.isApprovedForAll(_owner, _operator); } } /** * Changes the creator for the current sender, in the event we * need to be able to mint new tokens from an existing digital media * print production. When changing creator, the old creator will * no longer be able to mint tokens. * * A creator may need to be changed: * 1. If we want to allow a creator to take control over their token minting (i.e go decentralized) * 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function * when the contract is paused. * @param _creator the creator address * @param _newCreator the new creator address */ function changeCreator(address _creator, address _newCreator) external { address approvedCreator = changedCreators[_creator]; require(msg.sender != address(0) && _creator != address(0), "Creator must be valid non 0x0 address."); require(msg.sender == _creator || msg.sender == approvedCreator, "Unauthorized caller."); if (approvedCreator == address(0)) { changedCreators[msg.sender] = _newCreator; } else { require(msg.sender == approvedCreator, "Unauthorized caller."); changedCreators[_creator] = _newCreator; } emit ChangedCreator(_creator, _newCreator); } // standard ERC721 burn interface function burn(uint256 _tokenId) external { _burnToken(_tokenId, msg.sender); } /** * Ends the production run of a digital media. Afterwards no more tokens * will be allowed to be printed for each digital media. Used when a creator * makes a mistake and wishes to burn and recreate their digital media. * * When a contract is paused we do not allow new tokens to be created, * so stopping the production of a token doesn't have much purpose. */ function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused { _burnDigitalMedia(_digitalMediaId, msg.sender); } /* * Batch transfer multiple tokens from their sources to destination * Owner / ApproveAll user can call this endpoint. */ function safeTransferMany(TokenDestinationRequest[] memory requests) external whenNotPaused { for (uint32 i=0; i < requests.length; i++) { TokenDestinationRequest memory request = requests[i]; safeTransferFrom(ownerOf(request.tokenId), request.destinationAddress, request.tokenId); } } function _updateDigitalMedia(DigitalMediaUpdateRequest memory request, DigitalMedia storage _digitalMedia) internal { require(_digitalMedia.immutableMedia == false, "immutable"); require(_digitalMedia.printIndex <= request.totalSupply, "< currentPrintIndex"); _digitalMedia.totalSupply = request.totalSupply; _digitalMedia.metadataPath = request.metadataPath; _digitalMedia.royalty = request.royalty; delete _digitalMedia.collaborators; _setCollaboratorsOnDigitalMedia(_digitalMedia, request.collaborators); emit DigitalMediaUpdateEvent(request.onchainId, request.totalSupply, request.royalty, request.metadataPath, request.metadataId); } function updateMedia(DigitalMediaUpdateRequest memory request) external whenNotPaused { require(request.creator == msg.sender, "msgSender != creator"); DigitalMedia storage _digitalMedia = idToDigitalMedia[request.onchainId]; require(_digitalMedia.creator != address(0) && _digitalMedia.creator == msg.sender, "DM creator issue"); _updateDigitalMedia(request, _digitalMedia); } /* * Update existing digitalMedia's metadata, totalSupply, collaborated, royalty * and immutable attribute. Once a media is immutable you cannot call this function */ function updateManyMedias(DigitalMediaUpdateRequest[] memory requests) external whenNotPaused isApprovedOBO vaultInitialized { for (uint32 i=0; i < requests.length; i++) { DigitalMediaUpdateRequest memory request = requests[i]; DigitalMedia storage _digitalMedia = idToDigitalMedia[request.onchainId]; // Call creator registry to check if the creator gave approveAll to vault require(_digitalMedia.creator != address(0) && _digitalMedia.creator == request.creator, "DM creator"); require(isApprovedForAll(_digitalMedia.creator, address(vaultStore)) == true, "approveall missing"); _updateDigitalMedia(request, _digitalMedia); } } function makeMediaImmutable(uint256 mediaId) external whenNotPaused { DigitalMedia storage _digitalMedia = idToDigitalMedia[mediaId]; require(_digitalMedia.creator != address(0) && _digitalMedia.creator == msg.sender, "DM creator"); require(_digitalMedia.immutableMedia == false, "DM immutable"); _digitalMedia.immutableMedia = true; emit MediaImmutableEvent(mediaId); } /* * Once we update media and feel satisfied with the changes, we can render it immutable now. */ function makeMediasImmutable(uint256[] memory mediaIds) external whenNotPaused isApprovedOBO vaultInitialized { for (uint32 i=0; i < mediaIds.length; i++) { uint256 mediaId = mediaIds[i]; DigitalMedia storage _digitalMedia = idToDigitalMedia[mediaId]; require(_digitalMedia.creator != address(0), "DM not found."); require(_digitalMedia.immutableMedia == false, "DM immutable"); require(isApprovedForAll(_digitalMedia.creator, address(vaultStore)) == true, "approveall missing"); _digitalMedia.immutableMedia = true; } emit MediasImmutableEvent(mediaIds); } function _lookUpTokenAndReturnEntries(uint256 _tokenId, uint256 _salePrice, bool _isRoyalty) internal view returns(PayoutInfo[] memory entries) { require(_exists(_tokenId), "no token"); DigitalMediaRelease memory digitalMediaRelease = tokenIdToDigitalMediaRelease[_tokenId]; DigitalMedia memory _digitalMedia = idToDigitalMedia[digitalMediaRelease.digitalMediaId]; uint256 size = _digitalMedia.collaborators.length + 1; entries = new PayoutInfo[](size); uint totalRoyaltyPercentage = 0; for (uint256 index = 0; index < _digitalMedia.collaborators.length; index++) { address payoutAddress = _getRoyaltyAddress(_digitalMedia.collaborators[index].account); if (_isRoyalty == true) { entries[index] = PayoutInfo(payoutAddress, _digitalMedia.collaborators[index].royalty * _digitalMedia.royalty * _salePrice / (10000 * 10000)); totalRoyaltyPercentage = totalRoyaltyPercentage + _digitalMedia.collaborators[index].royalty; } else { entries[index] = PayoutInfo(payoutAddress, _digitalMedia.collaborators[index].value * _salePrice / 10000); totalRoyaltyPercentage = totalRoyaltyPercentage + _digitalMedia.collaborators[index].value; } } address creatorPayoutAddress = _getRoyaltyAddress(_digitalMedia.creator); if (_isRoyalty == true) { entries[size-1]= PayoutInfo(creatorPayoutAddress, _salePrice * (10000 - totalRoyaltyPercentage) * _digitalMedia.royalty / (10000 * 10000)); } else { entries[size-1]= PayoutInfo(creatorPayoutAddress, _salePrice * (10000 - totalRoyaltyPercentage) / 10000); } return entries; } /* * Return royalty for a given Token. Returns an array of PayoutInfo which consists * of address to pay to and amount. * Thank you for posting this gist. Helped me to figure out how to return an array of structs. * https://gist.github.com/minhth1905/4b6208372fc5e7343b5ce1fb6d42c942 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns ( PayoutInfo[] memory) { return _lookUpTokenAndReturnEntries(_tokenId, _salePrice, true); } /* * Given salePrice break down the amount between the creator and collabarators * according to their percentages. */ function saleInfo(uint256 _tokenId, uint256 _totalPayout) external view returns ( PayoutInfo[] memory) { return _lookUpTokenAndReturnEntries(_tokenId, _totalPayout, false); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /* * helper to verify signature signed by non-custodial creator. */ function _verifyReleaseRequestSignature( ChainSignatureRequest memory request, bytes calldata signature) internal view { require(enableExternalMinting == true, "ext minting disabled"); bytes32 encodedRequest = keccak256(abi.encode(request)); address addressWhoSigned = encodedRequest.recover(signature); require(addressWhoSigned == signerAddress, "sig error"); } }
Creates _count number of new digital media releases (i.e a token). Bumps up the print index by _count. _owner address the owner of the digital media object _digitalMediaId uint256 the digital media id/ This will assign ownership and also emit the Transfer event as per ERC721
function _createDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint256[] memory _releaseIds) internal { require(_releaseIds.length > 0 && _releaseIds.length < 10000, "0 < count <= 10000"); DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; require(_digitalMedia.creator != address(0), "media does not exist"); uint32 currentPrintIndex = _digitalMedia.printIndex; require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved"); require(_releaseIds.length + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded."); for (uint32 i=0; i < _releaseIds.length; i++) { uint256 newDigitalMediaReleaseId = _releaseIds[i]; DigitalMediaRelease storage release = tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId]; require(release.printEdition == 0, "tokenId already used"); uint32 newPrintEdition = currentPrintIndex + 1 + i; release.printEdition = newPrintEdition; release.digitalMediaId = _digitalMediaId; emit DigitalMediaReleaseCreateEvent( newDigitalMediaReleaseId, _owner, newPrintEdition, _digitalMedia.metadataPath, _digitalMediaId ); _mint(_owner, newDigitalMediaReleaseId); } _digitalMedia.printIndex = _digitalMedia.printIndex + uint32(_releaseIds.length); }
640,483
./partial_match/1/0x0fe99a74b23BD08Da08f22c5289764E1dDb1c42a/sources/ELONETH.sol
require( random_Token_Address != address(this), "Can not remove native token" );
function remove_Random_Tokens( address random_Token_Address, uint256 percent_of_Tokens ) public returns (bool _sent) { uint256 totalRandom = IERC20(random_Token_Address).balanceOf( address(this) ); uint256 removeRandom = (totalRandom * percent_of_Tokens) / 100; _sent = IERC20(random_Token_Address).transfer(Wallet_Dev, removeRandom); }
3,547,705
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IUniswapV2Router02.sol"; import "../interfaces/BPoolInterface.sol"; import "../interfaces/ICVPMakerStrategy.sol"; import "../powerindex-router/PowerIndexWrapper.sol"; import "./CVPMaker.sol"; contract CVPMakerLens { CVPMaker public cvpMaker; constructor(address payable _cvpMaker) public { cvpMaker = CVPMaker(_cvpMaker); } function getStrategy2NextIndex(address token_) external view returns (uint256 nextIndex) { (, nextIndex) = cvpMaker.getStrategy2Config(token_); } function getStrategy2NextTokenToExit(address token_) external view returns (address) { (, uint256 nextIndex) = cvpMaker.getStrategy2Config(token_); address[] memory tokens = cvpMaker.getStrategy2Tokens(token_); require(tokens.length > 0, "TOKENS_NOT_CONFIGURED"); return tokens[nextIndex]; } function getUniLikeRouterAndPath(address token_) external view returns (address router, address[] memory path) { return (cvpMaker.routers(token_), cvpMaker.getCustomPaths(token_)); } /*** ESTIMATIONS ***/ // How much token_s you need in order to convert them to cvpAmountOut right away function estimateSwapAmountIn(address token_) external view returns (uint256) { if (token_ == cvpMaker.cvp()) { return cvpMaker.cvpAmountOut(); } if (token_ == cvpMaker.weth() || token_ == cvpMaker.ETH()) { return cvpMaker.estimateEthStrategyIn(); } uint256 customStrategyId = cvpMaker.customStrategies(token_); if (customStrategyId > 0) { return estimateCustomStrategyIn(token_, customStrategyId); } (address strategy, , ) = cvpMaker.getExternalStrategyConfig(token_); if (strategy != address(0)) { return estimateExternalStrategyIn(token_); } return cvpMaker.estimateUniLikeStrategyIn(token_); } // How much CVP can be returned by swapping all the token_ balance // Does not support estimations for the external strategies function estimateCvpAmountOut(address token_) external view returns (uint256) { address cvp = cvpMaker.cvp(); if (token_ == cvp) { return IERC20(cvp).balanceOf(address(cvpMaker)); } if (token_ == cvpMaker.weth() || token_ == cvpMaker.ETH()) { return estimateEthStrategyOut(token_); } uint256 customStrategyId = cvpMaker.customStrategies(token_); if (customStrategyId > 0) { return estimateCustomStrategyOut(token_, customStrategyId); } else { return estimateUniLikeStrategyOut(token_); } } function estimateEthStrategyOut(address token_) public view returns (uint256) { address weth = cvpMaker.weth(); uint256 balanceIn = token_ == weth ? IERC20(weth).balanceOf(address(cvpMaker)) : address(cvpMaker).balance; if (balanceIn == 0) { return 0; } return _estimateEthStrategyOut(balanceIn); } function _estimateEthStrategyOut(uint256 _balanceIn) internal view returns (uint256) { return IUniswapV2Router02(cvpMaker.uniswapRouter()).getAmountsOut(_balanceIn, cvpMaker.wethCVPPath())[1]; } // How many CVP can get for the current token_ balance function estimateUniLikeStrategyOut(address token_) public view returns (uint256) { uint256 balance = IERC20(token_).balanceOf(address(cvpMaker)); return _estimateUniLikeStrategyOut(token_, balance); } function _estimateUniLikeStrategyOut(address token_, uint256 balance_) internal view returns (uint256) { if (balance_ == 0) { return 0; } address router = cvpMaker.getRouter(token_); address[] memory path = cvpMaker.getPath(token_); uint256[] memory results = IUniswapV2Router02(router).getAmountsOut(balance_, path); if (router == cvpMaker.uniswapRouter()) { return results[results.length - 1]; } else { return _estimateEthStrategyOut(results[results.length - 1]); } } /*** CUSTOM STRATEGIES ***/ function estimateCustomStrategyIn(address token_, uint256 strategyId_) public view returns (uint256) { if (strategyId_ == 1) { return estimateStrategy1In(token_); } else if (strategyId_ == 2) { return estimateStrategy2In(token_); } else if (strategyId_ == 3) { return estimateStrategy3In(token_); } else { revert("INVALID_STRATEGY_ID"); } } function estimateExternalStrategyIn(address token_) public view returns (uint256) { (address strategy, bool maxAmountIn, bytes memory config) = cvpMaker.getExternalStrategyConfig(token_); if (maxAmountIn) { return IERC20(token_).balanceOf(address(cvpMaker)); } return ICVPMakerStrategy(strategy).estimateIn( token_, cvpMaker.estimateUniLikeStrategyIn(ICVPMakerStrategy(strategy).getTokenOut()), config ); } function estimateCustomStrategyOut(address token_, uint256 strategyId_) public view returns (uint256) { if (strategyId_ == 1) { return estimateStrategy1Out(token_); } else if (strategyId_ == 2) { return estimateStrategy2Out(token_); } else if (strategyId_ == 3) { return estimateStrategy3Out(token_); } else { revert("INVALID_STRATEGY_ID"); } } // Hom many bPool tokens to burn to get the current cvpAmountOut function estimateStrategy1In(address bPoolToken_) public view returns (uint256) { address bPoolWrapper = cvpMaker.getStrategy1Config(bPoolToken_); return bPoolGetExitAmountIn({ bPool_: bPoolToken_, bPoolWrapper_: bPoolWrapper != address(0) ? bPoolWrapper : bPoolToken_, tokenOut_: cvpMaker.cvp(), amountOut_: cvpMaker.cvpAmountOut() }); } // Hom many CVP tokens will be received in the case of burning all the available bPool tokens function estimateStrategy1Out(address bPoolToken_) public view returns (uint256) { address bPoolWrapper = cvpMaker.getStrategy1Config(bPoolToken_); return bPoolGetExitAmountOut({ bPool_: bPoolToken_, bPoolWrapper_: bPoolWrapper != address(0) ? bPoolWrapper : bPoolToken_, tokenOut_: cvpMaker.cvp(), amountIn_: IERC20(bPoolToken_).balanceOf(address(cvpMaker)) }); } // Hom many bPool tokens to burn to get the current cvpAmountOut by swapping the exitToken token with // the corresponding uniLike path function estimateStrategy2In(address bPoolToken_) public view returns (uint256) { address[] memory tokens = cvpMaker.getStrategy2Tokens(bPoolToken_); require(tokens.length > 0, "TOKENS_NOT_CONFIGURED"); (address bPoolWrapper, uint256 nextIndex) = cvpMaker.getStrategy2Config(bPoolToken_); address underlyingOrPiToExit = tokens[nextIndex]; address underlyingToken = underlyingOrPiToExit; if (bPoolWrapper != address(0)) { address underlyingCandidate = PowerIndexWrapper(bPoolWrapper).underlyingByPiToken(underlyingOrPiToExit); if (underlyingCandidate != address(0)) { underlyingToken = underlyingCandidate; } } uint256 uniLikeAmountIn = cvpMaker.estimateUniLikeStrategyIn(underlyingToken); (, , uint256 communityExitFee, ) = BPoolInterface(bPoolToken_).getCommunityFee(); uint256 amountOutGross = cvpMaker.calcBPoolGrossAmount(uniLikeAmountIn, communityExitFee); return bPoolGetExitAmountIn({ bPool_: bPoolToken_, bPoolWrapper_: bPoolWrapper != address(0) ? bPoolWrapper : bPoolToken_, tokenOut_: underlyingOrPiToExit, amountOut_: amountOutGross }); } // Hom many CVP tokens can be returned by exiting with the all bPool balance and swapping the exit amount // with uniLike strategy function estimateStrategy2Out(address bPoolToken_) public view returns (uint256) { address[] memory tokens = cvpMaker.getStrategy2Tokens(bPoolToken_); require(tokens.length > 0, "TOKENS_NOT_CONFIGURED"); (address bPoolWrapper, uint256 nextIndex) = cvpMaker.getStrategy2Config(bPoolToken_); address tokenToExit = tokens[nextIndex]; address tokenToEstimate = tokenToExit; if (bPoolWrapper != address(0)) { address underlyingCandidate = PowerIndexWrapper(bPoolWrapper).underlyingByPiToken(tokenToExit); if (underlyingCandidate != address(0)) { tokenToEstimate = underlyingCandidate; } } uint256 tokenAmountOut = bPoolGetExitAmountOut({ bPool_: bPoolToken_, bPoolWrapper_: bPoolWrapper != address(0) ? bPoolWrapper : bPoolToken_, tokenOut_: tokenToExit, amountIn_: IERC20(bPoolToken_).balanceOf(address(cvpMaker)) }); (, , uint256 communityExitFee, ) = BPoolInterface(bPoolToken_).getCommunityFee(); (uint256 amountOutWithFee, ) = BPoolInterface(bPoolToken_).calcAmountWithCommunityFee(tokenAmountOut, communityExitFee, address(cvpMaker)); return _estimateUniLikeStrategyOut(tokenToEstimate, amountOutWithFee); } /** * Estimates the amount of the given tokens required to be swapped for the cvpAmountOut. For a piToken it doesn't * include the underlying balance, while the actual swap will. * @param underlyingOrPiToken_ Either a piToken or it's underlying to swap for CVP * @return amountIn in the given tokens */ function estimateStrategy3In(address underlyingOrPiToken_) public view returns (uint256) { (address bPoolAddress, address bPoolWrapperAddress, address underlying) = cvpMaker.getStrategy3Config(underlyingOrPiToken_); BPoolInterface bPool = BPoolInterface(bPoolAddress); BPoolInterface bPoolWrapper = bPoolWrapperAddress != address(0) ? BPoolInterface(bPoolWrapperAddress) : bPool; (uint256 communitySwapFee, , , ) = bPool.getCommunityFee(); uint256 amountOutGross = cvpMaker.calcBPoolGrossAmount(cvpMaker.cvpAmountOut(), communitySwapFee); uint256 amountIn = bPoolGetSwapAmountIn({ bPool_: address(bPool), bPoolWrapper_: address(bPoolWrapper), tokenIn_: underlyingOrPiToken_, tokenOut_: cvpMaker.cvp(), amountOut_: amountOutGross }); if (underlying != address(0)) { return WrappedPiErc20Interface(underlyingOrPiToken_).getUnderlyingEquivalentForPi(amountIn); } else { return amountIn; } } /** * Estimates the amount of CVP can be received by swapping the given tokens * @param underlyingOrPiToken_ Either a piToken or it's underlying to swap for CVP * @return amountOut The estimated amount of CVP tokens */ function estimateStrategy3Out(address underlyingOrPiToken_) public view returns (uint256) { (address bPoolAddress, address bPoolWrapperAddress, address underlying) = cvpMaker.getStrategy3Config(underlyingOrPiToken_); address tokenIn = underlyingOrPiToken_; uint256 balance; BPoolInterface bPool = BPoolInterface(bPoolAddress); BPoolInterface bPoolWrapper = bPoolWrapperAddress != address(0) ? BPoolInterface(bPoolWrapperAddress) : bPool; if (underlying != address(0)) { tokenIn = underlying; balance = WrappedPiErc20Interface(underlyingOrPiToken_).getUnderlyingEquivalentForPi( IERC20(underlyingOrPiToken_).balanceOf(address(cvpMaker)) ); } else { balance = IERC20(underlyingOrPiToken_).balanceOf(address(cvpMaker)); } uint256 amountOutNet = bPoolGetSwapAmountOut({ bPool_: address(bPool), bPoolWrapper_: address(bPoolWrapper), tokenIn_: underlyingOrPiToken_, tokenOut_: cvpMaker.cvp(), amountIn_: balance }); (uint256 communitySwapFee, , , ) = BPoolInterface(bPool).getCommunityFee(); (uint256 amountOutGross, ) = BPoolInterface(bPool).calcAmountWithCommunityFee(amountOutNet, communitySwapFee, address(cvpMaker)); return amountOutGross; } /** * Estimates the amountIn based on amountOut. * @param bPool_ The BPool * @param bPoolWrapper_ The BPool wrapper. The same address as BPool in case if it doesn't have a wrapper. * @param tokenIn_ The token itself or the corresponding piToken * @param tokenOut_ The token itself or the corresponding piToken * @param amountOut_ The amount out * @return amountIn The estimated amount in */ function bPoolGetSwapAmountIn( address bPool_, address bPoolWrapper_, address tokenIn_, address tokenOut_, uint256 amountOut_ ) public view returns (uint256) { BPoolInterface bPool = BPoolInterface(bPool_); return BMath(bPoolWrapper_).calcInGivenOut( // tokenBalanceIn IERC20(tokenIn_).balanceOf(bPool_), // tokenWeightIn bPool.getDenormalizedWeight(tokenIn_), // tokenBalanceOut IERC20(tokenOut_).balanceOf(bPool_), // tokenWeightOut bPool.getDenormalizedWeight(tokenOut_), // tokenAmountOut amountOut_, // swapFee bPool.getSwapFee() ); } function bPoolGetSwapAmountOut( address bPool_, address bPoolWrapper_, address tokenIn_, address tokenOut_, uint256 amountIn_ ) public view returns (uint256) { BPoolInterface bPool = BPoolInterface(bPool_); return BMath(bPoolWrapper_).calcOutGivenIn( // tokenBalanceIn IERC20(tokenIn_).balanceOf(bPool_), // tokenWeightIn bPool.getDenormalizedWeight(tokenIn_), // tokenBalanceOut IERC20(tokenOut_).balanceOf(bPool_), // tokenWeightOut bPool.getDenormalizedWeight(tokenOut_), // tokenAmountOut amountIn_, // swapFee bPool.getSwapFee() ); } /** * @param bPool_ Either a pool or a wrapper contract, should be used in combination with the wrapperMode_ param * @param bPoolWrapper_ The BPool wrapper. The same address as BPool in the case if it doesn't have a wrapper. * @param tokenOut_ The token out address * @param amountOut_ The expected amount for the exit * @return amountIn The estimated amount in in pool tokens. */ function bPoolGetExitAmountIn( address bPool_, address bPoolWrapper_, address tokenOut_, uint256 amountOut_ ) public view returns (uint256) { BPoolInterface bPool = BPoolInterface(bPool_); return BMath(bPoolWrapper_).calcPoolInGivenSingleOut( // tokenBalanceOut IERC20(tokenOut_).balanceOf(bPool_), // tokenWeightOut bPool.getDenormalizedWeight(tokenOut_), // poolSupply bPool.totalSupply(), // totalWeight (denormalized) bPool.getTotalDenormalizedWeight(), // tokenAmountOut amountOut_, // swapFee bPool.getSwapFee() ); } function bPoolGetExitAmountOut( address bPool_, address bPoolWrapper_, address tokenOut_, uint256 amountIn_ ) public view returns (uint256) { BPoolInterface bPool = BPoolInterface(bPool_); return BMath(bPoolWrapper_).calcSingleOutGivenPoolIn( // tokenBalanceOut IERC20(tokenOut_).balanceOf(bPool_), // tokenWeightOut bPool.getDenormalizedWeight(tokenOut_), // poolSupply bPool.totalSupply(), // totalWeight (denormalized) bPool.getTotalDenormalizedWeight(), // poolAmountIn amountIn_, // swapFee bPool.getSwapFee() ); } }
How much token_s you need in order to convert them to cvpAmountOut right away
function estimateSwapAmountIn(address token_) external view returns (uint256) { if (token_ == cvpMaker.cvp()) { return cvpMaker.cvpAmountOut(); } if (token_ == cvpMaker.weth() || token_ == cvpMaker.ETH()) { return cvpMaker.estimateEthStrategyIn(); } uint256 customStrategyId = cvpMaker.customStrategies(token_); if (customStrategyId > 0) { return estimateCustomStrategyIn(token_, customStrategyId); } (address strategy, , ) = cvpMaker.getExternalStrategyConfig(token_); if (strategy != address(0)) { return estimateExternalStrategyIn(token_); } return cvpMaker.estimateUniLikeStrategyIn(token_); }
12,715,137
/* * 合约的增删改查 * 权限:所有人 */ pragma solidity ^0.5.0; contract CrudApp { struct country{ string name; string leader; uint256 population; } country[] public countries; uint256 public totalCountries; constructor() public { totalCountries = 0; } event CountryEvent(string countryName , string leader, uint256 population); event LeaderUpdated(string countryName , string leader); event CountryDelete(string countryName); /* * 添加数据 * @param countryName {string} 城市名 * @param leader {string} 市长 * @param population {uint256} 人口 * @returns {uint256} 总城市数 * @example * insert("Sss", "June", 10); */ function insert(string memory countryName , string memory leader , uint256 population) public returns (uint256 _totalCountries){ country memory newCountry = country(countryName , leader, population); countries.push(newCountry); totalCountries++; //emit event emit CountryEvent (countryName, leader, population); return totalCountries; } /* * 修改数据 * @param countryName {string} 城市名 * @param leader {string} 新市长 * @returns {bool} 是否成功 * @example * updateLeader("AAA", "FFFFF"); */ function updateLeader(string memory countryName, string memory newLeader) public returns (bool success){ //This has a problem we need loop for(uint256 i =0; i< totalCountries; i++){ if(compareStrings(countries[i].name ,countryName)){ countries[i].leader = newLeader; emit LeaderUpdated(countryName, newLeader); return true; } } return false; } /* * 删除数据 * @param countryName {string} 城市名 * @returns {bool} 是否成功 * @example * deleteCountry("AAA"); */ function deleteCountry(string memory countryName) public returns(bool success){ require(totalCountries > 0); for(uint256 i =0; i< totalCountries; i++){ if(compareStrings(countries[i].name , countryName)){ countries[i] = countries[totalCountries-1]; // pushing last into current arrray index which we gonna delete delete countries[totalCountries-1]; // now deleteing last index totalCountries--; //total count decrease countries.length--; // array length decrease //emit event emit CountryDelete(countryName); return true; } } return false; } /* * 查询数据 * @param countryName {string} 城市名 * @returns {bool} 是否成功 * @example * getCountry("AAA"); */ function getCountry(string memory countryName) public view returns(string memory name , string memory leader , uint256 population){ for(uint256 i = 0; i< totalCountries; i++){ if(compareStrings(countries[i].name, countryName)){ //emit event return (countries[i].name , countries[i].leader , countries[i].population); }else{ return ("404" , "404" , 0); } } // revert('country not found'); } function compareStrings (string memory a, string memory b) internal pure returns (bool){ return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); } /* * 查询总记录条数 * @returns length {uint256} 记录条数 */ function getTotalCountries() public view returns (uint256 length){ return countries.length; } }
添加数据 countryName {string} 城市名 leader {string} 市长 population {uint256} 人口 returns {uint256} 总城市数 @example insert("Sss", "June", 10);/emit event
function insert(string memory countryName , string memory leader , uint256 population) public returns (uint256 _totalCountries){ country memory newCountry = country(countryName , leader, population); countries.push(newCountry); totalCountries++; emit CountryEvent (countryName, leader, population); return totalCountries; }
5,493,735
./full_match/1/0x83473a0A1a9a08506e2952D96730AaC0f39b8c9A/sources/contracts/implementation/EclipseERC721.sol
Set receiver of royalties and shares NOTE: shares dominator is 10_000/
function setRoyaltyReceiver( address receiver, uint256 shares ) external onlyAdmin { _royaltyReceiver = receiver; _royaltyShares = shares; emit RoyaltyReceiverChanged(receiver); }
4,868,813
./full_match/80001/0x6D1C8963dac5a0Fb42bbCb709cAe14dab9A3b5D8/sources/StakeManager2.sol
@inheritdoc IStakeManager/
function getValidators( uint256 epoch, uint256 cursor, uint256 howMany ) external view returns ( address[] memory owners, address[] memory operators, uint256[] memory stakes, bool[] memory candidates, uint256 newCursor ) { if (address(candidateManager) != address(0)) { (owners, operators, , , stakes, candidates, newCursor) = candidateManager.getAll(epoch, cursor, howMany); } }
860,721
./partial_match/1/0x2c486C984e382070a2e783d808B7e7Ba3C2999b5/sources/KillerDoge.sol
Swaps the tax collected for fees sent to marketing and dev. The swap only swaps the threshold amount./
function swapBack() internal swapping { address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; router.swapExactTokensForETHSupportingFeeOnTransferTokens( swapThreshold, 0, path, address(this), block.timestamp ); uint256 amountBNB = address(this).balance; uint256 amountBNBMarketing = amountBNB.mul(marketingAmount).div( totalAmountDivider ); (bool tmpSuccess, ) = payable(marketingAmountReceiver).call{ value: amountBNBMarketing }(""); (bool tmpSuccess2, ) = payable(projectMaintenanceReceiver).call{ value: amountBNB.sub(amountBNBMarketing) }(""); tmpSuccess = false; }
4,170,290
./partial_match/5/0x72F0521e2bb6B01a7Cc3042b5603a3A0E9ca875c/sources/contracts/cryptopiggies.sol
Lets an NFT owner withdraw their proportion of funds once the piggyBank is unlocked get the total supply before burning burn the tokens so the owner can't claim twice
function payout(uint256 tokenId) external { require(totalSupply[tokenId] != 0, "Token data not found"); uint256 thisOwnerBalance = balanceOf[msg.sender][tokenId]; require(thisOwnerBalance != 0, "Not authorised!"); uint256 totalSupplyBeforePayout = totalSupply[tokenId]; _burn(msg.sender, tokenId, thisOwnerBalance); msg.sender, thisOwnerBalance, totalSupplyBeforePayout ) { revert(reason); revert("payout failed"); } } Configuration
16,866,153
pragma solidity ^0.4.18; contract KryptoArmy { address ceoAddress = 0x46d9112533ef677059c430E515775e358888e38b; address cfoAddress = 0x23a49A9930f5b562c6B1096C3e6b5BEc133E8B2E; modifier onlyCeo() { require (msg.sender == ceoAddress); _; } // Struct for Army struct Army { string name; // The name of the army (invented by the user) string idArmy; // The id of the army (USA for United States) uint experiencePoints; // The experience points of the army, we will use this to handle uint256 price; // The cost of the Army in Wei (1 ETH = 1000000000000000000 Wei) uint attackBonus; // The attack bonus for the soldiers (from 0 to 10) uint defenseBonus; // The defense bonus for the soldiers (from 0 to 10) bool isForSale; // User is selling this army, it can be purchase on the marketplace address ownerAddress; // The address of the owner uint soldiersCount; // The count of all the soldiers in this army } Army[] armies; // Struct for Battles struct Battle { uint idArmyAttacking; // The id of the army attacking uint idArmyDefensing; // The id of the army defensing uint idArmyVictorious; // The id of the winning army } Battle[] battles; // Mapping army mapping (address => uint) public ownerToArmy; // Which army does this address own mapping (address => uint) public ownerArmyCount; // How many armies own this address? // Mapping weapons to army mapping (uint => uint) public armyDronesCount; mapping (uint => uint) public armyPlanesCount; mapping (uint => uint) public armyHelicoptersCount; mapping (uint => uint) public armyTanksCount; mapping (uint => uint) public armyAircraftCarriersCount; mapping (uint => uint) public armySubmarinesCount; mapping (uint => uint) public armySatelitesCount; // Mapping battles mapping (uint => uint) public armyCountBattlesWon; mapping (uint => uint) public armyCountBattlesLost; // This function creates a new army and saves it in the array with its parameters function _createArmy(string _name, string _idArmy, uint _price, uint _attackBonus, uint _defenseBonus) public onlyCeo { // We add the new army to the list and save the id in a variable armies.push(Army(_name, _idArmy, 0, _price, _attackBonus, _defenseBonus, true, address(this), 0)); } // We use this function to purchase an army with Metamask function purchaseArmy(uint _armyId) public payable { // We verify that the value paid is equal to the cost of the army require(msg.value == armies[_armyId].price); require(msg.value > 0); // We check if this army is owned by another user if(armies[_armyId].ownerAddress != address(this)) { uint CommissionOwnerValue = msg.value - (msg.value / 10); armies[_armyId].ownerAddress.transfer(CommissionOwnerValue); } // We modify the ownership of the army _ownershipArmy(_armyId); } // Function to purchase a soldier function purchaseSoldiers(uint _armyId, uint _countSoldiers) public payable { // Check that message value > 0 require(msg.value > 0); uint256 msgValue = msg.value; if(msgValue == 1000000000000000 && _countSoldiers == 1) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 8000000000000000 && _countSoldiers == 10) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 65000000000000000 && _countSoldiers == 100) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 500000000000000000 && _countSoldiers == 1000) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } } // Payable function to purchase weapons function purchaseWeapons(uint _armyId, uint _weaponId, uint _bonusAttack, uint _bonusDefense ) public payable { // Check that message value > 0 uint isValid = 0; uint256 msgValue = msg.value; if(msgValue == 10000000000000000 && _weaponId == 0) { armyDronesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 1) { armyPlanesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 2) { armyHelicoptersCount[_armyId]++; isValid = 1; } else if(msgValue == 45000000000000000 && _weaponId == 3) { armyTanksCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 4) { armyAircraftCarriersCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 5) { armySubmarinesCount[_armyId]++; isValid = 1; } else if(msgValue == 120000000000000000 && _weaponId == 6) { armySatelitesCount[_armyId]++; isValid = 1; } // We check if the data has been verified as valid if(isValid == 1) { armies[_armyId].attackBonus = armies[_armyId].attackBonus + _bonusAttack; armies[_armyId].defenseBonus = armies[_armyId].defenseBonus + _bonusDefense; } } // We use this function to affect an army to an address (when someone purchase an army) function _ownershipArmy(uint armyId) private { // We check if the sender already own an army require (ownerArmyCount[msg.sender] == 0); // If this army has alreay been purchased we verify that the owner put it on sale require(armies[armyId].isForSale == true); // We check one more time that the price paid is the price of the army require(armies[armyId].price == msg.value); // We decrement the army count for the previous owner (in case a user is selling army on marketplace) ownerArmyCount[armies[armyId].ownerAddress]--; // We set the new army owner armies[armyId].ownerAddress = msg.sender; ownerToArmy[msg.sender] = armyId; // We increment the army count for this address ownerArmyCount[msg.sender]++; // Send event for new ownership armies[armyId].isForSale = false; } // We use this function to start a new battle function startNewBattle(uint _idArmyAttacking, uint _idArmyDefensing, uint _randomIndicatorAttack, uint _randomIndicatorDefense) public returns(uint) { // We verify that the army attacking is the army of msg.sender require (armies[_idArmyAttacking].ownerAddress == msg.sender); // Get details for army attacking uint ScoreAttack = armies[_idArmyAttacking].attackBonus * (armies[_idArmyAttacking].soldiersCount/3) + armies[_idArmyAttacking].soldiersCount + _randomIndicatorAttack; // Get details for army defending uint ScoreDefense = armies[_idArmyAttacking].defenseBonus * (armies[_idArmyDefensing].soldiersCount/2) + armies[_idArmyDefensing].soldiersCount + _randomIndicatorDefense; uint VictoriousArmy; uint ExperiencePointsGained; if(ScoreDefense >= ScoreAttack) { VictoriousArmy = _idArmyDefensing; ExperiencePointsGained = armies[_idArmyAttacking].attackBonus + 2; armies[_idArmyDefensing].experiencePoints = armies[_idArmyDefensing].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyDefensing]++; armyCountBattlesLost[_idArmyAttacking]++; } else { VictoriousArmy = _idArmyAttacking; ExperiencePointsGained = armies[_idArmyDefensing].defenseBonus + 2; armies[_idArmyAttacking].experiencePoints = armies[_idArmyAttacking].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyAttacking]++; armyCountBattlesLost[_idArmyDefensing]++; } // We add the new battle to the blockchain and save its id in a variable battles.push(Battle(_idArmyAttacking, _idArmyDefensing, VictoriousArmy)); // Send event return (VictoriousArmy); } // Owner can sell army function ownerSellArmy(uint _armyId, uint256 _amount) public { // We close the function if the user calling this function doesn't own the army require (armies[_armyId].ownerAddress == msg.sender); require (_amount > 0); require (armies[_armyId].isForSale == false); armies[_armyId].isForSale = true; armies[_armyId].price = _amount; } // Owner remove army from marketplace function ownerCancelArmyMarketplace(uint _armyId) public { require (armies[_armyId].ownerAddress == msg.sender); require (armies[_armyId].isForSale == true); armies[_armyId].isForSale = false; } // Function to return all the value of an army function getArmyFullData(uint armyId) public view returns(string, string, uint, uint256, uint, uint, bool) { string storage ArmyName = armies[armyId].name; string storage ArmyId = armies[armyId].idArmy; uint ArmyExperiencePoints = armies[armyId].experiencePoints; uint256 ArmyPrice = armies[armyId].price; uint ArmyAttack = armies[armyId].attackBonus; uint ArmyDefense = armies[armyId].defenseBonus; bool ArmyIsForSale = armies[armyId].isForSale; return (ArmyName, ArmyId, ArmyExperiencePoints, ArmyPrice, ArmyAttack, ArmyDefense, ArmyIsForSale); } // Function to return the owner of the army function getArmyOwner(uint armyId) public view returns(address, bool) { return (armies[armyId].ownerAddress, armies[armyId].isForSale); } // Function to return the owner of the army function getSenderArmyDetails() public view returns(uint, string) { uint ArmyId = ownerToArmy[msg.sender]; string storage ArmyName = armies[ArmyId].name; return (ArmyId, ArmyName); } // Function to return the owner army count function getSenderArmyCount() public view returns(uint) { uint ArmiesCount = ownerArmyCount[msg.sender]; return (ArmiesCount); } // Function to return the soldiers count of an army function getArmySoldiersCount(uint armyId) public view returns(uint) { uint SoldiersCount = armies[armyId].soldiersCount; return (SoldiersCount); } // Return an array with the weapons of the army function getWeaponsArmy1(uint armyId) public view returns(uint, uint, uint, uint) { uint CountDrones = armyDronesCount[armyId]; uint CountPlanes = armyPlanesCount[armyId]; uint CountHelicopters = armyHelicoptersCount[armyId]; uint CountTanks = armyTanksCount[armyId]; return (CountDrones, CountPlanes, CountHelicopters, CountTanks); } function getWeaponsArmy2(uint armyId) public view returns(uint, uint, uint) { uint CountAircraftCarriers = armyAircraftCarriersCount[armyId]; uint CountSubmarines = armySubmarinesCount[armyId]; uint CountSatelites = armySatelitesCount[armyId]; return (CountAircraftCarriers, CountSubmarines, CountSatelites); } // Retrieve count battles won function getArmyBattles(uint _armyId) public view returns(uint, uint) { return (armyCountBattlesWon[_armyId], armyCountBattlesLost[_armyId]); } // Retrieve the details of a battle function getDetailsBattles(uint battleId) public view returns(uint, uint, uint, string, string) { return (battles[battleId].idArmyAttacking, battles[battleId].idArmyDefensing, battles[battleId].idArmyVictorious, armies[battles[battleId].idArmyAttacking].idArmy, armies[battles[battleId].idArmyDefensing].idArmy); } // Get battles count function getBattlesCount() public view returns(uint) { return (battles.length); } // To withdraw fund from this contract function withdraw(uint amount, uint who) public onlyCeo returns(bool) { require(amount <= this.balance); if(who == 0) { ceoAddress.transfer(amount); } else { cfoAddress.transfer(amount); } return true; } // Initial function to create the 100 armies with their attributes function KryptoArmy() public onlyCeo { // 1. USA _createArmy("United States", "USA", 550000000000000000, 8, 9); // 2. North Korea _createArmy("North Korea", "NK", 500000000000000000, 10, 5); // 3. Russia _createArmy("Russia", "RUS", 450000000000000000, 8, 7); // 4. China _createArmy("China", "CHN", 450000000000000000, 7, 8); // 5. Japan _createArmy("Japan", "JPN", 420000000000000000, 7, 7); // 6. France _createArmy("France", "FRA", 400000000000000000, 6, 8); // 7. Germany _createArmy("Germany", "GER", 400000000000000000, 7, 6); // 8. India _createArmy("India", "IND", 400000000000000000, 7, 6); // 9. United Kingdom _createArmy("United Kingdom", "UK", 350000000000000000, 5, 7); // 10. South Korea _createArmy("South Korea", "SK", 350000000000000000, 6, 6); // 11. Turkey _createArmy("Turkey", "TUR", 300000000000000000, 7, 4); // 12. Italy //_createArmy("Italy", "ITA", 280000000000000000, 5, 5); } }
Function to return the owner of the army
function getSenderArmyDetails() public view returns(uint, string) { uint ArmyId = ownerToArmy[msg.sender]; string storage ArmyName = armies[ArmyId].name; return (ArmyId, ArmyName); }
13,131,600
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IPriceProvider.sol"; import "../interfaces/IConfigurationManager.sol"; /** * @title PriceProvider * @author Pods Finance * @notice Storage of prices feeds by asset */ contract PriceProvider is IPriceProvider, Ownable { /** * @dev store globally accessed configurations */ IConfigurationManager public immutable configurationManager; /** * @dev Minimum price interval to accept a price feed */ uint256 public minUpdateInterval; /** * @dev Stores PriceFeed by asset address */ mapping(address => IPriceFeed) private _assetPriceFeeds; event AssetFeedUpdated(address indexed asset, address indexed feed); event AssetFeedRemoved(address indexed asset, address indexed feed); constructor( IConfigurationManager _configurationManager, address[] memory _assets, address[] memory _feeds ) public { configurationManager = _configurationManager; minUpdateInterval = _configurationManager.getParameter("MIN_UPDATE_INTERVAL"); require(minUpdateInterval < block.timestamp, "PriceProvider: Invalid minUpdateInterval"); _setAssetFeeds(_assets, _feeds); } /** * @notice Register price feeds * @param _assets Array of assets * @param _feeds Array of price feeds */ function setAssetFeeds(address[] memory _assets, address[] memory _feeds) external override onlyOwner { _setAssetFeeds(_assets, _feeds); } /** * @notice Updates previously registered price feeds * @param _assets Array of assets * @param _feeds Array of price feeds */ function updateAssetFeeds(address[] memory _assets, address[] memory _feeds) external override onlyOwner { for (uint256 i = 0; i < _assets.length; i++) { require(address(_assetPriceFeeds[_assets[i]]) != address(0), "PriceProvider: PriceFeed not set"); } _setAssetFeeds(_assets, _feeds); } /** * @notice Unregister price feeds * @dev Will not remove unregistered assets * @param _assets Array of assets */ function removeAssetFeeds(address[] memory _assets) external override onlyOwner { for (uint256 i = 0; i < _assets.length; i++) { address removedFeed = address(_assetPriceFeeds[_assets[i]]); if (removedFeed != address(0)) { delete _assetPriceFeeds[_assets[i]]; emit AssetFeedRemoved(_assets[i], removedFeed); } } } /** * @notice Update minUpdateInterval fetching from configurationManager */ function updateMinUpdateInterval() external override { minUpdateInterval = configurationManager.getParameter("MIN_UPDATE_INTERVAL"); require(minUpdateInterval < block.timestamp, "PriceProvider: Invalid minUpdateInterval"); } /** * @notice Gets the current price of an asset * @param _asset Address of an asset * @return Current price */ function getAssetPrice(address _asset) external override view returns (uint256) { IPriceFeed feed = _assetPriceFeeds[_asset]; require(address(feed) != address(0), "PriceProvider: Feed not registered"); (int256 price, uint256 updatedAt) = feed.getLatestPrice(); require(!_isObsolete(updatedAt), "PriceProvider: stale PriceFeed"); require(price > 0, "PriceProvider: Negative price"); return uint256(price); } /** * @notice Get the data from the latest round. * @param _asset Address of an asset * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function latestRoundData(address _asset) external override view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { IPriceFeed feed = _assetPriceFeeds[_asset]; require(address(feed) != address(0), "PriceProvider: Feed not registered"); return feed.latestRoundData(); } /** * @notice Gets the number of decimals of a PriceFeed * @param _asset Address of an asset * @return Asset price decimals */ function getAssetDecimals(address _asset) external override view returns (uint8) { IPriceFeed feed = _assetPriceFeeds[_asset]; require(address(feed) != address(0), "PriceProvider: Feed not registered"); return feed.decimals(); } /** * @notice Get the address of a registered price feed * @param _asset Address of an asset * @return Price feed address */ function getPriceFeed(address _asset) external override view returns (address) { return address(_assetPriceFeeds[_asset]); } /** * @dev Internal function to set price feeds for different assets * @param _assets Array of assets * @param _feeds Array of price feeds */ function _setAssetFeeds(address[] memory _assets, address[] memory _feeds) internal { require(_assets.length == _feeds.length, "PriceProvider: inconsistent params length"); for (uint256 i = 0; i < _assets.length; i++) { IPriceFeed feed = IPriceFeed(_feeds[i]); require(address(feed) != address(0), "PriceProvider: invalid PriceFeed"); (, , uint256 startedAt, uint256 updatedAt, ) = feed.latestRoundData(); require(startedAt > 0, "PriceProvider: PriceFeed not started"); require(!_isObsolete(updatedAt), "PriceProvider: stale PriceFeed"); _assetPriceFeeds[_assets[i]] = feed; emit AssetFeedUpdated(_assets[i], _feeds[i]); } } /** * @dev Internal function to check if a given timestamp is obsolete * @param _timestamp The timestamp to check */ function _isObsolete(uint256 _timestamp) internal view returns (bool) { return _timestamp < (block.timestamp - minUpdateInterval); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IPriceFeed { function getLatestPrice() external view returns (int256, uint256); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IPriceProvider { function setAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function updateAssetFeeds(address[] memory _assets, address[] memory _feeds) external; function removeAssetFeeds(address[] memory _assets) external; function getAssetPrice(address _asset) external view returns (uint256); function getAssetDecimals(address _asset) external view returns (uint8); function latestRoundData(address _asset) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getPriceFeed(address _asset) external view returns (address); function updateMinUpdateInterval() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IConfigurationManager { function setParameter(bytes32 name, uint256 value) external; function setEmergencyStop(address emergencyStop) external; function setPricingMethod(address pricingMethod) external; function setIVGuesser(address ivGuesser) external; function setIVProvider(address ivProvider) external; function setPriceProvider(address priceProvider) external; function setCapProvider(address capProvider) external; function setAMMFactory(address ammFactory) external; function setOptionFactory(address optionFactory) external; function setOptionHelper(address optionHelper) external; function setOptionPoolRegistry(address optionPoolRegistry) external; function getParameter(bytes32 name) external view returns (uint256); function owner() external view returns (address); function getEmergencyStop() external view returns (address); function getPricingMethod() external view returns (address); function getIVGuesser() external view returns (address); function getIVProvider() external view returns (address); function getPriceProvider() external view returns (address); function getCapProvider() external view returns (address); function getAMMFactory() external view returns (address); function getOptionFactory() external view returns (address); function getOptionHelper() external view returns (address); function getOptionPoolRegistry() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Update minUpdateInterval fetching from configurationManager/
function updateMinUpdateInterval() external override { minUpdateInterval = configurationManager.getParameter("MIN_UPDATE_INTERVAL"); require(minUpdateInterval < block.timestamp, "PriceProvider: Invalid minUpdateInterval"); }
13,467,165
./partial_match/56/0xa9eB28df890A88077487eBEF47974527656433E6/sources/MasterPepe.sol
Initialze the World Info array World Level system initilization
function initWorldInfo() internal { uint256 expRequired = BASE_EXP_REQUIRED_PER_LEVEL; for (uint256 i = 0; i < MAX_NUM_WORLDS; i++) { expRequired = i == 0 ? 0 : expRequired.add(BASE_EXP_REQUIRED_PER_LEVEL.mul(i - 1)); worldInfo.push( WorldLevel({ levelId: i, bonusMultiplier: Multiplier({ numerator: 10 + (i - 1), denominator: 10 }), minExpRequired: expRequired * 1 ether }) ); } }
11,088,691
pragma solidity >0.4.25; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import '../diamondaccesscontrol/MinerRole.sol'; import '../diamondaccesscontrol/ManufacturerRole.sol'; import '../diamondaccesscontrol/MasterjewelerRole.sol'; import '../diamondaccesscontrol/RetailerRole.sol'; import '../diamondaccesscontrol/CustomerRole.sol'; /** * @title Supply chain main contract * @author Stefanel Stan https://github.com/StefanelStan */ contract SupplyChain is Ownable, MinerRole, ManufacturerRole, MasterjewelerRole, RetailerRole, CustomerRole { /** * @dev As this is a supply chain for diamond jewelry, there is a subtle difference on the * state and processes of the item. When the raw diamond is mined, this is an item whose * itemPrice is to be determined by Miner. A manufacturer can BUY the item * After the item gets cut by a master jeweler, the item is seen as a product, which has a * productPrice determined by manufacturer. * A customer can then purchase the product after paying the productPrice. */ struct Item { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Miner, goes on the package, can be verified by the Customer uint productID; // Product ID potentially a combination of upc + sku uint itemPrice; //item price uint productPrice; // product Price string minerName; // Miner Name string mineInformation; // Mine Information string mineLatitude; // Mine Latitude string mineLongitude; // Mine Longitude string itemNotes; // Item Notes string ipfsHash; // ipfs hash of the picture of the item State itemState; // Item State as represented in the enum above address owner; // Metamask-Ethereum address of the current owner as the product moves through stages address miner; // Metamask-Ethereum address of the Farmer address manufacturer; // Metamask-Ethereum address of the Manufacturer address masterjeweler; // Metamask-Ethereum address of the Masterjeweler address retailer; // Metamask-Ethereum address of the Retailer address customer; // Metamask-Ethereum address of the Customer } /** @dev Please see the notes from struct Item that clarifies the difference between * ForSale/Sold and ForPurchasing/Purchased */ enum State { Mined, // 0 ForSale, // 1 Sold, // 2 Sent, // 3 Received, // 4 SentToCut, // 5 ReceivedForCutting, // 6 Cut, // 7 SentFromCutting, // 8 ReceivedFromCutting, // 9 MarkedForPurchasing, // 10 SentForPurchasing, // 11 ReceivedForPurchasing, // 12 ForPurchasing, // 13 Purchased, // 14 Fetched // 15 } // for Stock Keeping Unit (SKU) uint _sku; // maps the UPC to an Item. mapping (uint => Item) private items; // maps the UPC/item to an array of TxHash & tracks its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) private itemsHistory; // Define 16 events with the same 16 state values and accept 'upc' as input argument event Mined(uint upc); event ForSale(uint upc); event Sold(uint upc); event Sent(uint upc); event Received(uint upc); event SentToCut(uint upc); event ReceivedForCutting(uint upc); event Cut(uint upc); event SentFromCutting(uint upc); event ReceivedFromCutting(uint upc); event MarkedForPurchasing(uint upc); event SentForPurchasing(uint upc); event ReceivedForPurchasing(uint upc); event ForPurchasing(uint upc); event Purchased(uint upc); event Fetched(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller(address _address) { require(msg.sender == _address, "Only the authorized user/address can perform this"); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price, "Not enough payment sent"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValueForSelling(uint _upc) { _; uint _price = items[_upc].itemPrice; uint amountToReturn = msg.value - _price; address payable manufacturerAddres = address(uint160(items[_upc].manufacturer)); manufacturerAddres.transfer(amountToReturn); } // Define a modifier that checks the price and refunds the remaining balance modifier checkValueForPurchasing(uint _upc) { _; uint _price = items[_upc].productPrice; uint amountToReturn = msg.value - _price; address payable customerAddress = address(uint160(items[_upc].customer)); customerAddress.transfer(amountToReturn); } // Define a modifier that checks if an item.state of a upc is Mined modifier mined(uint _upc) { //If the doesn't exist, its State.mined == 0. So there is need for a stronger verification eg: has an owner require(items[_upc].itemState == State.Mined && items[_upc].owner != address(0), "Item state is not Mined"); _; } // Define a modifier that checks if an item.state of a upc is ForSale modifier forSale(uint _upc) { require(items[_upc].itemState == State.ForSale, "Item state is not ForSale"); _; } // Define a modifier that checks if an item.state of a upc is Sold modifier sold(uint _upc) { require(items[_upc].itemState == State.Sold, "Item state is not Sold"); _; } // Define a modifier that checks if an item.state of a upc is Sent modifier sent(uint _upc) { require(items[_upc].itemState == State.Sent, "Item state is not Sent"); _; } // Define a modifier that checks if an item.state of a upc is Received modifier received(uint _upc) { require(items[_upc].itemState == State.Received, "Item state is not Received"); _; } // Define a modifier that checks if an item.state of a upc is SentToCut modifier sentToCut(uint _upc) { require(items[_upc].itemState == State.SentToCut, "Item state is not SentToCut"); _; } // Define a modifier that checks if an item.state of a upc is ReceivedForCutting modifier receivedForCutting(uint _upc) { require(items[_upc].itemState == State.ReceivedForCutting, "Item state is not ReceivedForCutting"); _; } // Define a modifier that checks if an item.state of a upc is Cut modifier cut(uint _upc) { require(items[_upc].itemState == State.Cut, "Item state is not Cut"); _; } // Define a modifier that checks if an item.state of a upc is SentFromCutting modifier sentFromCutting(uint _upc) { require(items[_upc].itemState == State.SentFromCutting, "Item state is not SentFromCutting"); _; } // Define a modifier that checks if an item.state of a upc is ReceivedFromCutting modifier receivedFromCutting(uint _upc) { require(items[_upc].itemState == State.ReceivedFromCutting, "Item state is not ReceivedFromCutting"); _; } // Define a modifier that checks if an item.state of a upc is MarkedForPurchasing modifier markedForPurchasing(uint _upc) { require(items[_upc].itemState == State.MarkedForPurchasing, "Item state is not MarkedForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is SentForPurchasing modifier sentForPurchasing(uint _upc) { require(items[_upc].itemState == State.SentForPurchasing, "Item state is not SentForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is ReceivedForPurchasing modifier receivedForPurchasing(uint _upc) { require(items[_upc].itemState == State.ReceivedForPurchasing, "Item state is not ReceivedForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is ForPurchasing modifier forPurchasing(uint _upc) { require(items[_upc].itemState == State.ForPurchasing, "Item state is not ForPurchasing"); _; } // Define a modifier that checks if an item.state of a upc is Purchased modifier purchased(uint _upc) { require(items[_upc].itemState == State.Purchased, "Item state is not Purchased"); _; } // Define a modifier that checks if an item.state of a upc is Fetched modifier fetched(uint _upc) { require(items[_upc].itemState == State.Fetched, "Item state is not Fetched"); _; } constructor() public payable { _sku = 0; } // Define a function 'kill' if required function kill() external onlyOwner { require(isOwner(), "Only owner can kill this contract"); selfdestruct(address(uint160(owner()))); } /** * @dev Mines an item. * @param _upc the identifier of the item; Generated by the miner. Reverts if not unique * @param _minerName miner's name * @param _mineInformation mine's information * @param _mineLatitude mine's LAtitude * @param _mineLongitude mine's Lontitude * @param _itemNotes notes about the item */ function mineItem( uint _upc, string memory _minerName, string memory _mineInformation, string memory _mineLatitude, string memory _mineLongitude, string memory _itemNotes ) public onlyMiner { require(items[_upc].owner == address(0), 'Item already exists'); items[_upc] = Item(_sku, _upc, _upc + _sku, 0, 0, _minerName, _mineInformation, _mineLatitude, _mineLongitude, _itemNotes, "No Image Hash exists", State.Mined, msg.sender, msg.sender, address(0), address(0), address(0), address(0)); _sku++; emit Mined(_upc); } /** * @dev Marks an item as For Sale * @param _upc the upc of the item * @param _price the price demanded for the item */ function sellItem(uint _upc, uint _price) public onlyMiner mined(_upc) verifyCaller(items[_upc].owner) { Item storage item = items[_upc]; item.itemPrice = _price; item.itemState = State.ForSale; emit ForSale(_upc); } /** * @dev Buys an item. Caller should be a manufacturer * @param _upc the desired _upc item to buy */ function buyItem(uint _upc) public payable onlyManufacturer forSale(_upc) paidEnough(items[_upc].itemPrice) checkValueForSelling(_upc) { Item storage item = items[_upc]; address(uint160(item.miner)).transfer(item.itemPrice); item.owner = msg.sender; item.manufacturer = msg.sender; item.itemState = State.Sold; emit Sold(_upc); } /** * @dev The Miner marks/sends a bought item to the buyer (manufacturer) * @param _upc the item's id to be send to the manufacturer/buyer */ function sendItem(uint _upc) public sold(_upc) verifyCaller(items[_upc].miner) { items[_upc].itemState = State.Sent; emit Sent(_upc); } /** * @dev The rightful buyer (manufacturer) receives the item and marks it as received * @param _upc the item to mark as received */ function receiveItem(uint _upc) public sent(_upc) verifyCaller(items[_upc].manufacturer) { items[_upc].itemState = State.Received; emit Received(_upc); } /** * @dev Send the item to cut * @param _upc the item's id * @param masterjeweler the Masterjeweler's address. The given address has to have Masterjeweler Role */ function sendItemToCut(uint _upc, address masterjeweler) public received(_upc) verifyCaller(items[_upc].manufacturer) { require(isMasterjeweler(masterjeweler), "The given address is not a Masterjeweler Role"); items[_upc].itemState = State.SentToCut; items[_upc].masterjeweler = masterjeweler; emit SentToCut(_upc); } /** * @dev Masterjeweler receives the item to cut * @param _upc the item's id that has been received */ function receiveItemToCut(uint _upc) public sentToCut(_upc) verifyCaller(items[_upc].masterjeweler) onlyMasterjeweler { items[_upc].itemState = State.ReceivedForCutting; emit ReceivedForCutting(_upc); } /** * @dev Masterjeweler cuts the item * @param _upc the item's upc to cut */ function cutItem(uint _upc) public receivedForCutting(_upc) verifyCaller(items[_upc].masterjeweler) onlyMasterjeweler { items[_upc].itemState = State.Cut; emit Cut(_upc); } /** * @dev Masterjeweler returns the cut item * @param _upc the item to return */ function returnCutItem(uint _upc) public cut(_upc) verifyCaller(items[_upc].masterjeweler) { items[_upc].itemState = State.SentFromCutting; emit SentFromCutting(_upc); } /** * @dev Receive the cut item back from the masterjeweler * @param _upc the item's upc */ function receiveCutItem(uint _upc) public sentFromCutting(_upc) verifyCaller(items[_upc].manufacturer) { items[_upc].itemState = State.ReceivedFromCutting; emit ReceivedFromCutting(_upc); } /** * @dev Manufacturer marks the item for Purchasing for the given price * @param _upc the item's upc to mark for purchasing * @param _price the price for the disired product. * @notice The item is to treated as product now. */ function markForPurchasing(uint _upc, uint _price) public receivedFromCutting(_upc) verifyCaller(items[_upc].manufacturer) { items[_upc].itemState = State.MarkedForPurchasing; items[_upc].productPrice = _price; emit MarkedForPurchasing(_upc); } /** * @dev Send the marked item to the retailer to be displayed and purchased * @param _upc the item's upc * @param retailer The address of the retailer. Reverts if the given address is NOT a RetailerRole */ function sendItemForPurchasing(uint _upc, address retailer) public markedForPurchasing(_upc) verifyCaller(items[_upc].manufacturer) { require(isRetailer(retailer), "The given address is not a Retailer Role"); items[_upc].itemState = State.SentForPurchasing; items[_upc].retailer = retailer; emit SentForPurchasing(_upc); } /** * @dev Allows the retailer to receive the item (product) * @param _upc the item to receive */ function receiveItemForPurchasing(uint _upc) public sentForPurchasing(_upc) verifyCaller(items[_upc].retailer) { items[_upc].itemState = State.ReceivedForPurchasing; emit ReceivedForPurchasing(_upc); } function putUpForPurchasing(uint _upc) public receivedForPurchasing(_upc) verifyCaller(items[_upc].retailer) onlyRetailer { items[_upc].itemState = State.ForPurchasing; emit ForPurchasing(_upc); } /** * @dev Allows a customer to purchase the final product * @param _upc the item's upc that is being purchased */ function purchaseItem(uint _upc) public payable forPurchasing(_upc) paidEnough(items[_upc].productPrice) onlyCustomer checkValueForPurchasing(_upc) { Item storage item = items[_upc]; address(uint160(item.retailer)).transfer(item.productPrice); item.owner = msg.sender; item.customer = msg.sender; item.itemState = State.Purchased; emit Purchased(_upc); } /** * @dev Allows the rightful customer to take the product out of the shop * @param _upc the item's upc to fetch/get out of shop */ function fetchItem(uint _upc) public purchased(_upc) verifyCaller(items[_upc].customer) { items[_upc].itemState = State.Fetched; emit Fetched(_upc); } /** * @dev Allows the original miner to upload a image Hash of the item freshly mined. * @param _upc the item's upc to which the image hash belongs * @param _ipfsHash the image's ipfs hash */ function uploadHash(uint _upc, string calldata _ipfsHash) external verifyCaller(items[_upc].miner) { items[_upc].ipfsHash = _ipfsHash; } /** * @dev Read the ipfs image hash of the given upc item * @param _upc the item's upc * @return the image hash */ function readHash(uint _upc) external view returns (string memory){ return items[_upc].ipfsHash; } /** * @dev Method created specially for the purpose easy testing for Udacity Reviewers * This way, any reviewer can promote his/her selected account to be all 5 roles * This method is critical as accounts have to have the X/Y/Z Role to perform specific actions */ function giveMeAllRoles() external { _addMiner(msg.sender); _addManufacturer(msg.sender); _addMasterjeweler(msg.sender); _addRetailer(msg.sender); _addCustomer(msg.sender); } /** * @dev fetch data/info about the given item * @param _upc the item's upc */ function fetchItemBufferOne(uint _upc) public view returns ( uint sku, uint upc, address owner, address miner, string memory minerName, string memory mineInformation, string memory mineLatitude, string memory mineLongitude ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.owner, item.miner, item.minerName, item.mineInformation, item.mineLatitude, item.mineLongitude ); } /** * @dev fetch data/info about the given item * @param _upc the item's upc */ function fetchItemBufferTwo(uint _upc) public view returns ( uint sku, uint upc, uint productID, string memory itemNotes, uint itemPrice, uint productPrice, State itemState, address manufacturer, address masterjeweler, address retailer, address customer ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.productID, item.itemNotes, item.itemPrice, item.productPrice, item.itemState, item.manufacturer, item.masterjeweler, item.retailer, item.customer ); } }
Method created specially for the purpose easy testing for Udacity Reviewers This way, any reviewer can promote his/her selected account to be all 5 roles This method is critical as accounts have to have the X/Y/Z Role to perform specific actions/
function giveMeAllRoles() external { _addMiner(msg.sender); _addManufacturer(msg.sender); _addMasterjeweler(msg.sender); _addRetailer(msg.sender); _addCustomer(msg.sender); }
7,235,455