contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
KWWBoatsVoting
contracts/KWWBoatsVoting.sol
0x8c41343b12c6dabbeab4773c462e916c62016b7c
Solidity
KWWBoatsVoting
contract KWWBoatsVoting is IBoatsVoting, Ownable { address gameManager; int8 public voteDay1 = 2; int8 public voteDay2 = 3; uint8 public durationHours = 24; uint8 public daysBetweenVotes = 7; //tokenId => BoatData mapping(uint16 => BoatData) public boatsDetails; //boatState => State Vote data mapping(uint8 => TypeVote) public votes; /* EXECUTABLE FUNCTIONS */ function setBoatDetails(uint16 idx, BoatData memory data) public override onlyGameManager{ boatsDetails[idx] = data; } function makeVote1(uint16 tokenId, uint256 vote, uint8 boatState) public override onlyGameManager{ require(getCurrentOnlineVote() == 1, "Vote 1 is not online right now"); require(getLastVoteTime(1) > getVoteTimeByDate(boatsDetails[tokenId].timestampVoted1 ,1), "Already Voted!"); votes[boatState].priceSum += vote; votes[boatState].voters += 1; votes[boatState].avg = votes[boatState].priceSum / votes[boatState].voters; boatsDetails[tokenId].vote1 = vote; boatsDetails[tokenId].timestampVoted1 = uint48(block.timestamp); } function makeVote2(uint16 tokenId, bool vote, uint8 boatState) public onlyGameManager{ require(getCurrentOnlineVote() == 2, "Vote 2 is not online right now"); require(getLastVoteTime(2) > getVoteTimeByDate(boatsDetails[tokenId].timestampVoted2 ,2), "Already Voted!"); votes[boatState].agreeToAvg += (vote ? int16(1) : int16(-1)); boatsDetails[tokenId].vote2 = vote; boatsDetails[tokenId].timestampVoted2 = uint48(block.timestamp); } function updatePrice(uint8 boatState) public onlyGameManager { require(getCurrentOnlineVote() == 0, "Vote is online"); require(votes[boatState].voters > 0, "No one voted this week"); if(votes[boatState].agreeToAvg > 0){ votes[boatState].finalPrice = votes[boatState].avg; } votes[boatState].voters = 0; votes[boatState].priceSum = 0; votes[boatState].avg = 0; votes[boatState].agreeToAvg = 0; } function setVoteDetails(uint8 boatState, TypeVote memory vote) public onlyGameManager { votes[boatState] = vote; } function setFinalPrice(uint8 boatState, uint256 finalPrice) public onlyGameManager { votes[boatState].finalPrice = finalPrice; } function setPriceSum(uint8 boatState, uint256 priceSum) public onlyGameManager { votes[boatState].priceSum = priceSum; } function setAvg(uint8 boatState, uint256 avg) public onlyGameManager { votes[boatState].avg = avg; } function setVoters(uint8 boatState, uint16 voters) public onlyGameManager { votes[boatState].voters = voters; } function setAgreeToAvg(uint8 boatState, int16 agreeToAvg) public onlyGameManager { votes[boatState].agreeToAvg = agreeToAvg; } function setVote1(uint16 tokenId, uint256 vote1) public onlyGameManager { boatsDetails[tokenId].vote1 = vote1; } function setVote2(uint16 tokenId, bool vote2) public onlyGameManager { boatsDetails[tokenId].vote2 = vote2; } function setTimestampVoted1(uint16 tokenId, uint48 timestampVoted1) public onlyGameManager { boatsDetails[tokenId].timestampVoted1 = timestampVoted1; } function setTimestampVoted2(uint16 tokenId, uint48 timestampVoted2) public onlyGameManager { boatsDetails[tokenId].timestampVoted2 = timestampVoted2; } /* GETTERS */ function getBoatDetails(uint16 idx) public override view returns(BoatData memory){ return boatsDetails[idx]; } function getVoteDetails(uint8 boatState) public view returns(TypeVote memory){ return votes[boatState]; } function getAveragePrice(uint8 boatState) public view returns(uint256){ return votes[boatState].avg; } function getPrice(uint8 boatState) public view returns(uint256){ return votes[boatState].finalPrice; } function getLastVoteTime(uint8 voteType) public override view returns(int){ return getVoteTimeByDate(block.timestamp, voteType); } function getVoteTimeByDate(uint256 timestamp, uint8 voteType) public override view returns (int){ int8 voteDay = voteType == 1 ? voteDay1 : voteDay2; int8 delta = voteDay - int8(KWWUtils.getWeekday(timestamp)); if(delta > 0) delta = delta - 7; int date = (int(timestamp) + delta * int64(KWWUtils.DAY_IN_SECONDS)); return date - date % int64(KWWUtils.DAY_IN_SECONDS); } function getCurrentVoteEndTime() public view returns(int256) { uint8 onlineVote = getCurrentOnlineVote(); if(onlineVote == 1){ return getLastVoteTime(1) + int64(durationHours * KWWUtils.HOUR_IN_SECONDS); } if(onlineVote == 2){ return getLastVoteTime(2) + int64(durationHours * KWWUtils.HOUR_IN_SECONDS); } return 0; } function getCurrentOnlineVote() public override view returns (uint8) { int lastVote1 = getLastVoteTime(1); int lastVote2 = getLastVoteTime(2); //Vote1 Time if(lastVote1 > lastVote2 && lastVote1 + int64(durationHours * KWWUtils.HOUR_IN_SECONDS) > int(block.timestamp)){ return 1; } if(lastVote2 + int64(durationHours * KWWUtils.HOUR_IN_SECONDS) > int(block.timestamp)){ return 2; } return 0; } /* MODIFIERS */ modifier onlyGameManager() { require(gameManager != address(0), "Game manager not exists"); require(msg.sender == owner() || msg.sender == gameManager, "caller is not the game manager"); _; } /* ONLY OWNER */ function setVoteDay1(uint8 newDay) public override onlyOwner { voteDay1 = int8(newDay); } function setVoteDay2(uint8 newDay) public override onlyOwner { voteDay2 = int8(newDay); } function setDurationHours(uint8 newHours) public override onlyOwner { require(newHours > 0, "Must be more than 0 and less than time between votes"); durationHours = newHours; } function setGameManager(address _newAddress) public onlyOwner{ gameManager = _newAddress; } }
getBoatDetails
function getBoatDetails(uint16 idx) public override view returns(BoatData memory){ return boatsDetails[idx]; }
/* GETTERS */
Comment
v0.8.4+commit.c7e474f2
MIT
ipfs://8f707f7f8f9ebb3464f53a333bb3a80a6aaf6b2844d348c99cac0a09323e7b4c
{ "func_code_index": [ 3673, 3802 ] }
607
KWWBoatsVoting
contracts/KWWBoatsVoting.sol
0x8c41343b12c6dabbeab4773c462e916c62016b7c
Solidity
KWWBoatsVoting
contract KWWBoatsVoting is IBoatsVoting, Ownable { address gameManager; int8 public voteDay1 = 2; int8 public voteDay2 = 3; uint8 public durationHours = 24; uint8 public daysBetweenVotes = 7; //tokenId => BoatData mapping(uint16 => BoatData) public boatsDetails; //boatState => State Vote data mapping(uint8 => TypeVote) public votes; /* EXECUTABLE FUNCTIONS */ function setBoatDetails(uint16 idx, BoatData memory data) public override onlyGameManager{ boatsDetails[idx] = data; } function makeVote1(uint16 tokenId, uint256 vote, uint8 boatState) public override onlyGameManager{ require(getCurrentOnlineVote() == 1, "Vote 1 is not online right now"); require(getLastVoteTime(1) > getVoteTimeByDate(boatsDetails[tokenId].timestampVoted1 ,1), "Already Voted!"); votes[boatState].priceSum += vote; votes[boatState].voters += 1; votes[boatState].avg = votes[boatState].priceSum / votes[boatState].voters; boatsDetails[tokenId].vote1 = vote; boatsDetails[tokenId].timestampVoted1 = uint48(block.timestamp); } function makeVote2(uint16 tokenId, bool vote, uint8 boatState) public onlyGameManager{ require(getCurrentOnlineVote() == 2, "Vote 2 is not online right now"); require(getLastVoteTime(2) > getVoteTimeByDate(boatsDetails[tokenId].timestampVoted2 ,2), "Already Voted!"); votes[boatState].agreeToAvg += (vote ? int16(1) : int16(-1)); boatsDetails[tokenId].vote2 = vote; boatsDetails[tokenId].timestampVoted2 = uint48(block.timestamp); } function updatePrice(uint8 boatState) public onlyGameManager { require(getCurrentOnlineVote() == 0, "Vote is online"); require(votes[boatState].voters > 0, "No one voted this week"); if(votes[boatState].agreeToAvg > 0){ votes[boatState].finalPrice = votes[boatState].avg; } votes[boatState].voters = 0; votes[boatState].priceSum = 0; votes[boatState].avg = 0; votes[boatState].agreeToAvg = 0; } function setVoteDetails(uint8 boatState, TypeVote memory vote) public onlyGameManager { votes[boatState] = vote; } function setFinalPrice(uint8 boatState, uint256 finalPrice) public onlyGameManager { votes[boatState].finalPrice = finalPrice; } function setPriceSum(uint8 boatState, uint256 priceSum) public onlyGameManager { votes[boatState].priceSum = priceSum; } function setAvg(uint8 boatState, uint256 avg) public onlyGameManager { votes[boatState].avg = avg; } function setVoters(uint8 boatState, uint16 voters) public onlyGameManager { votes[boatState].voters = voters; } function setAgreeToAvg(uint8 boatState, int16 agreeToAvg) public onlyGameManager { votes[boatState].agreeToAvg = agreeToAvg; } function setVote1(uint16 tokenId, uint256 vote1) public onlyGameManager { boatsDetails[tokenId].vote1 = vote1; } function setVote2(uint16 tokenId, bool vote2) public onlyGameManager { boatsDetails[tokenId].vote2 = vote2; } function setTimestampVoted1(uint16 tokenId, uint48 timestampVoted1) public onlyGameManager { boatsDetails[tokenId].timestampVoted1 = timestampVoted1; } function setTimestampVoted2(uint16 tokenId, uint48 timestampVoted2) public onlyGameManager { boatsDetails[tokenId].timestampVoted2 = timestampVoted2; } /* GETTERS */ function getBoatDetails(uint16 idx) public override view returns(BoatData memory){ return boatsDetails[idx]; } function getVoteDetails(uint8 boatState) public view returns(TypeVote memory){ return votes[boatState]; } function getAveragePrice(uint8 boatState) public view returns(uint256){ return votes[boatState].avg; } function getPrice(uint8 boatState) public view returns(uint256){ return votes[boatState].finalPrice; } function getLastVoteTime(uint8 voteType) public override view returns(int){ return getVoteTimeByDate(block.timestamp, voteType); } function getVoteTimeByDate(uint256 timestamp, uint8 voteType) public override view returns (int){ int8 voteDay = voteType == 1 ? voteDay1 : voteDay2; int8 delta = voteDay - int8(KWWUtils.getWeekday(timestamp)); if(delta > 0) delta = delta - 7; int date = (int(timestamp) + delta * int64(KWWUtils.DAY_IN_SECONDS)); return date - date % int64(KWWUtils.DAY_IN_SECONDS); } function getCurrentVoteEndTime() public view returns(int256) { uint8 onlineVote = getCurrentOnlineVote(); if(onlineVote == 1){ return getLastVoteTime(1) + int64(durationHours * KWWUtils.HOUR_IN_SECONDS); } if(onlineVote == 2){ return getLastVoteTime(2) + int64(durationHours * KWWUtils.HOUR_IN_SECONDS); } return 0; } function getCurrentOnlineVote() public override view returns (uint8) { int lastVote1 = getLastVoteTime(1); int lastVote2 = getLastVoteTime(2); //Vote1 Time if(lastVote1 > lastVote2 && lastVote1 + int64(durationHours * KWWUtils.HOUR_IN_SECONDS) > int(block.timestamp)){ return 1; } if(lastVote2 + int64(durationHours * KWWUtils.HOUR_IN_SECONDS) > int(block.timestamp)){ return 2; } return 0; } /* MODIFIERS */ modifier onlyGameManager() { require(gameManager != address(0), "Game manager not exists"); require(msg.sender == owner() || msg.sender == gameManager, "caller is not the game manager"); _; } /* ONLY OWNER */ function setVoteDay1(uint8 newDay) public override onlyOwner { voteDay1 = int8(newDay); } function setVoteDay2(uint8 newDay) public override onlyOwner { voteDay2 = int8(newDay); } function setDurationHours(uint8 newHours) public override onlyOwner { require(newHours > 0, "Must be more than 0 and less than time between votes"); durationHours = newHours; } function setGameManager(address _newAddress) public onlyOwner{ gameManager = _newAddress; } }
setVoteDay1
function setVoteDay1(uint8 newDay) public override onlyOwner { voteDay1 = int8(newDay); }
/* ONLY OWNER */
Comment
v0.8.4+commit.c7e474f2
MIT
ipfs://8f707f7f8f9ebb3464f53a333bb3a80a6aaf6b2844d348c99cac0a09323e7b4c
{ "func_code_index": [ 6008, 6114 ] }
608
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
Executor
interface Executor { /// @dev Allows a Module to execute a transaction. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule(address to, uint256 value, bytes calldata data, Enum.Operation operation) external returns (bool success); }
execTransactionFromModule
function execTransactionFromModule(address to, uint256 value, bytes calldata data, Enum.Operation operation) external returns (bool success);
/// @dev Allows a Module to execute a transaction. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction.
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 312, 473 ] }
609
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
setQuestionTimeout
function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; }
/// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 2881, 3074 ] }
610
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
setQuestionCooldown
function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; }
/// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 3382, 3702 ] }
611
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
setAnswerExpiration
function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; }
/// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 4142, 4428 ] }
612
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
setArbitrator
function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; }
/// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 4620, 4757 ] }
613
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
setMinimumBond
function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; }
/// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 4976, 5095 ] }
614
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
setTemplate
function setTemplate(uint256 templateId) public executorOnly() { template = templateId; }
/// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 5436, 5561 ] }
615
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
addProposal
function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); }
/// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 5875, 6022 ] }
616
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
addProposalWithNonce
function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); }
/// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 6345, 8036 ] }
617
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
markProposalAsInvalid
function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); }
/// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 8342, 8712 ] }
618
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
markProposalAsInvalidByHash
function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; }
/// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 8959, 9120 ] }
619
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
markProposalWithExpiredAnswerAsInvalid
function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; }
/// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 9329, 10099 ] }
620
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
executeProposal
function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); }
/// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 10711, 10966 ] }
621
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
executeProposalWithIndex
function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); }
/// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 11656, 13994 ] }
622
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
buildQuestion
function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); }
/// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 14301, 14596 ] }
623
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
getQuestionId
function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); }
/// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used.
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 14729, 15088 ] }
624
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
getChainId
function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; }
/// @dev Returns the chain id used by this contract.
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 15147, 15370 ] }
625
DaoModule
contracts/DaoModule.sol
0x33b821d1ba2bd4bc48693fdbe042668dd9c151ae
Solidity
DaoModule
contract DaoModule { bytes32 public constant INVALIDATED = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; // keccak256( // "Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)" // ); event ProposalQuestionCreated( bytes32 indexed questionId, string indexed proposalId ); Executor public immutable executor; Realitio public immutable oracle; uint256 public template; uint32 public questionTimeout; uint32 public questionCooldown; uint32 public answerExpiration; address public questionArbitrator; uint256 public minimumBond; // Mapping of question hash to question id. Special case: INVALIDATED for question hashes that have been invalidated mapping(bytes32 => bytes32) public questionIds; // Mapping of questionHash to transactionHash to execution state mapping(bytes32 => mapping(bytes32 => bool)) public executedProposalTransactions; /// @param _executor Address of the executor (e.g. a Safe) /// @param _oracle Address of the oracle (e.g. Realitio) /// @param timeout Timeout in seconds that should be required for the oracle /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @param bond Minimum bond that is required for an answer to be accepted /// @param templateId ID of the template that should be used for proposal questions (see https://github.com/realitio/realitio-dapp#structuring-and-fetching-information) /// @notice There need to be at least 60 seconds between end of cooldown and expiration constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) { require(timeout > 0, "Timeout has to be greater 0"); require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); executor = _executor; oracle = _oracle; answerExpiration = expiration; questionTimeout = timeout; questionCooldown = cooldown; questionArbitrator = address(_executor); minimumBond = bond; template = templateId; } modifier executorOnly() { require(msg.sender == address(executor), "Not authorized"); _; } /// @notice This can only be called by the executor function setQuestionTimeout(uint32 timeout) public executorOnly() { require(timeout > 0, "Timeout has to be greater 0"); questionTimeout = timeout; } /// @dev Sets the cooldown before an answer is usable. /// @param cooldown Cooldown in seconds that should be required after a oracle provided answer /// @notice This can only be called by the executor /// @notice There need to be at least 60 seconds between end of cooldown and expiration function setQuestionCooldown(uint32 cooldown) public executorOnly() { uint32 expiration = answerExpiration; require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); questionCooldown = cooldown; } /// @dev Sets the duration for which a positive answer is valid. /// @param expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever) /// @notice A proposal with an expired answer is the same as a proposal that has been marked invalid /// @notice There need to be at least 60 seconds between end of cooldown and expiration /// @notice This can only be called by the executor function setAnswerExpiration(uint32 expiration) public executorOnly() { require(expiration == 0 || expiration - questionCooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration"); answerExpiration = expiration; } /// @dev Sets the question arbitrator that will be used for future questions. /// @param arbitrator Address of the arbitrator /// @notice This can only be called by the executor function setArbitrator(address arbitrator) public executorOnly() { questionArbitrator = arbitrator; } /// @dev Sets the minimum bond that is required for an answer to be accepted. /// @param bond Minimum bond that is required for an answer to be accepted /// @notice This can only be called by the executor function setMinimumBond(uint256 bond) public executorOnly() { minimumBond = bond; } /// @dev Sets the template that should be used for future questions. /// @param templateId ID of the template that should be used for proposal questions /// @notice Check https://github.com/realitio/realitio-dapp#structuring-and-fetching-information for more information /// @notice This can only be called by the executor function setTemplate(uint256 templateId) public executorOnly() { template = templateId; } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice The nonce used for the question by this function is always 0 function addProposal(string memory proposalId, bytes32[] memory txHashes) public { addProposalWithNonce(proposalId, txHashes, 0); } /// @dev Function to add a proposal that should be considered for execution /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param nonce Nonce that should be used when asking the question on the oracle function addProposalWithNonce(string memory proposalId, bytes32[] memory txHashes, uint256 nonce) public { // We load some storage variables into memory to save gas uint256 templateId = template; uint32 timeout = questionTimeout; address arbitrator = questionArbitrator; // We generate the question string used for the oracle string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); if (nonce > 0) { // Previous nonce must have been invalidated by the oracle. // However, if the proposal was internally invalidated, it should not be possible to ask it again. bytes32 currentQuestionId = questionIds[questionHash]; require(currentQuestionId != INVALIDATED, "This proposal has been marked as invalid"); require(oracle.resultFor(currentQuestionId) == INVALIDATED, "Previous proposal was not invalidated"); } else { require(questionIds[questionHash] == bytes32(0), "Proposal has already been submitted"); } bytes32 expectedQuestionId = getQuestionId( templateId, question, arbitrator, timeout, 0, nonce ); // Set the question hash for this quesion id questionIds[questionHash] = expectedQuestionId; // Ask the question with a starting time of 0, so that it can be immediately answered bytes32 questionId = oracle.askQuestion(templateId, question, arbitrator, timeout, 0, nonce); require(expectedQuestionId == questionId, "Unexpected question id"); emit ProposalQuestionCreated(questionId, proposalId); } /// @dev Marks a proposal as invalid, preventing execution of the connected transactions /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @notice This can only be called by the executor function markProposalAsInvalid(string memory proposalId, bytes32[] memory txHashes) public // Executor only is checked in markProposalAsInvalidByHash(bytes32) { string memory question = buildQuestion(proposalId, txHashes); bytes32 questionHash = keccak256(bytes(question)); markProposalAsInvalidByHash(questionHash); } /// @dev Marks a question hash as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes /// @notice This can only be called by the executor function markProposalAsInvalidByHash(bytes32 questionHash) public executorOnly() { questionIds[questionHash] = INVALIDATED; } /// @dev Marks a proposal with an expired answer as invalid, preventing execution of the connected transactions /// @param questionHash Question hash calculated based on the proposal id and txHashes function markProposalWithExpiredAnswerAsInvalid(bytes32 questionHash) public { uint32 expirationDuration = answerExpiration; require(expirationDuration > 0, "Answers are valid forever"); bytes32 questionId = questionIds[questionHash]; require(questionId != INVALIDATED, "Proposal is already invalidated"); require(questionId != bytes32(0), "No question id set for provided proposal"); require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Only positive answers can expire"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); require(finalizeTs + uint256(expirationDuration) < block.timestamp, "Answer has not expired yet"); questionIds[questionHash] = INVALIDATED; } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @notice The txIndex used by this function is always 0 function executeProposal(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation) public { executeProposalWithIndex(proposalId, txHashes, to, value, data, operation, 0); } /// @dev Executes the transactions of a proposal via the executor if accepted /// @param proposalId Id that should identify the proposal uniquely /// @param txHashes EIP-712 hashes of the transactions that should be executed /// @param to Target of the transaction that should be executed /// @param value Wei value of the transaction that should be executed /// @param data Data of the transaction that should be executed /// @param operation Operation (Call or Delegatecall) of the transaction that should be executed /// @param txIndex Index of the transaction hash in txHashes. This is used as the nonce for the transaction, to make the tx hash unique function executeProposalWithIndex(string memory proposalId, bytes32[] memory txHashes, address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txIndex) public { // We use the hash of the question to check the execution state, as the other parameters might change, but the question not bytes32 questionHash = keccak256(bytes(buildQuestion(proposalId, txHashes))); // Lookup question id for this proposal bytes32 questionId = questionIds[questionHash]; // Question hash needs to set to be eligible for execution require(questionId != bytes32(0), "No question id set for provided proposal"); require(questionId != INVALIDATED, "Proposal has been invalidated"); bytes32 txHash = getTransactionHash(to, value, data, operation, txIndex); require(txHashes[txIndex] == txHash, "Unexpected transaction hash"); // Check that the result of the question is 1 (true) require(oracle.resultFor(questionId) == bytes32(uint256(1)), "Transaction was not approved"); uint256 minBond = minimumBond; require(minBond == 0 || minBond <= oracle.getBond(questionId), "Bond on question not high enough"); uint32 finalizeTs = oracle.getFinalizeTS(questionId); // The answer is valid in the time after the cooldown and before the expiration time (if set). require(finalizeTs + uint256(questionCooldown) < block.timestamp, "Wait for additional cooldown"); uint32 expiration = answerExpiration; require(expiration == 0 || finalizeTs + uint256(expiration) >= block.timestamp, "Answer has expired"); // Check this is either the first transaction in the list or that the previous question was already approved require(txIndex == 0 || executedProposalTransactions[questionHash][txHashes[txIndex - 1]], "Previous transaction not executed yet"); // Check that this question was not executed yet require(!executedProposalTransactions[questionHash][txHash], "Cannot execute transaction again"); // Mark transaction as executed executedProposalTransactions[questionHash][txHash] = true; // Execute the transaction via the executor. require(executor.execTransactionFromModule(to, value, data, operation), "Module transaction failed"); } /// @dev Build the question by combining the proposalId and the hex string of the hash of the txHashes /// @param proposalId Id of the proposal that proposes to execute the transactions represented by the txHashes /// @param txHashes EIP-712 Hashes of the transactions that should be executed function buildQuestion(string memory proposalId, bytes32[] memory txHashes) public pure returns(string memory) { string memory txsHash = bytes32ToAsciiString(keccak256(abi.encodePacked(txHashes))); return string(abi.encodePacked(proposalId, bytes3(0xe2909f), txsHash)); } /// @dev Generate the question id. /// @notice It is required that this is the same as for the oracle implementation used. function getQuestionId(uint256 templateId, string memory question, address arbitrator, uint32 timeout, uint32 openingTs, uint256 nonce) public view returns(bytes32) { bytes32 contentHash = keccak256(abi.encodePacked(templateId, openingTs, question)); return keccak256(abi.encodePacked(contentHash, arbitrator, timeout, this, nonce)); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solium-disable-next-line security/no-inline-assembly assembly { id := chainid() } return id; } /// @dev Generates the data for the module transaction hash (required for signing) function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } function getTransactionHash(address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce) public view returns(bytes32) { return keccak256(generateTransactionHashData(to, value, data, operation, nonce)); } function bytes32ToAsciiString(bytes32 _bytes) internal pure returns (string memory) { bytes memory s = new bytes(64); for (uint256 i = 0; i < 32; i++) { uint8 b = uint8(bytes1(_bytes << i * 8)); uint8 hi = uint8(b) / 16; uint8 lo = uint8(b) % 16; s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function char(uint8 b) internal pure returns (bytes1 c) { if (b < 10) return bytes1(b + 0x30); else return bytes1(b + 0x57); } }
generateTransactionHashData
function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns(bytes memory) { uint256 chainId = getChainId(); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); }
/// @dev Generates the data for the module transaction hash (required for signing)
NatSpecSingleLine
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 15459, 16055 ] }
626
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
ERC721
contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); }
approve
function approve(address _to, uint256 _tokenId) public;
// Required methods
LineComment
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 42, 100 ] }
627
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
WorldCupToken
contract WorldCupToken is ERC721 { event Birth(uint256 tokenId, string name, address owner); event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ string public constant NAME = "WorldCupToken"; string public constant SYMBOL = "WorldCupToken"; uint256 private startingPrice = 0.1 ether; mapping (uint256 => address) private teamIndexToOwner; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) private teamIndexToApproved; mapping (uint256 => uint256) private teamIndexToPrice; mapping (string => uint256) private nameIndexToTeam; // eg: Egypt => 0 mapping (string => string) private teamIndexToName; // eg: 0 => Egypt address private ceoAddress; bool private isStop; struct Team { string name; } Team[] private teams; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyStart() { require(isStop == false); _; } function setStop() public onlyCEO { isStop = true; } function setStart() public onlyCEO { isStop = false; } /*** CONSTRUCTOR ***/ function WorldCupToken() public { ceoAddress = msg.sender; isStop=false; _createTeam("Egypt", msg.sender, startingPrice); teamIndexToName["0"]="Egypt"; _createTeam("Morocco", msg.sender, startingPrice); teamIndexToName["1"]="Morocco"; _createTeam("Nigeria", msg.sender, startingPrice); teamIndexToName["2"]="Nigeria"; _createTeam("Senegal", msg.sender, startingPrice); teamIndexToName["3"]="Senegal"; _createTeam("Tunisia", msg.sender, startingPrice); teamIndexToName["4"]="Tunisia"; _createTeam("Australia", msg.sender, startingPrice); teamIndexToName["5"]="Australia"; _createTeam("IR Iran", msg.sender, startingPrice); teamIndexToName["6"]="IR Iran"; _createTeam("Japan", msg.sender, startingPrice); teamIndexToName["7"]="Japan"; _createTeam("Korea Republic", msg.sender, startingPrice); teamIndexToName["8"]="Korea Republic"; _createTeam("Saudi Arabia", msg.sender, startingPrice); teamIndexToName["9"]="Saudi Arabia"; _createTeam("Belgium", msg.sender, startingPrice); teamIndexToName["10"]="Belgium"; _createTeam("Croatia", msg.sender, startingPrice); teamIndexToName["11"]="Croatia"; _createTeam("Denmark", msg.sender, startingPrice); teamIndexToName["12"]="Denmark"; _createTeam("England", msg.sender, startingPrice); teamIndexToName["13"]="England"; _createTeam("France", msg.sender, startingPrice); teamIndexToName["14"]="France"; _createTeam("Germany", msg.sender, startingPrice); teamIndexToName["15"]="Germany"; _createTeam("Iceland", msg.sender, startingPrice); teamIndexToName["16"]="Iceland"; _createTeam("Poland", msg.sender, startingPrice); teamIndexToName["17"]="Poland"; _createTeam("Portugal", msg.sender, startingPrice); teamIndexToName["18"]="Portugal"; _createTeam("Russia", msg.sender, startingPrice); teamIndexToName["19"]="Russia"; _createTeam("Serbia", msg.sender, startingPrice); teamIndexToName["20"]="Serbia"; _createTeam("Spain", msg.sender, startingPrice); teamIndexToName["21"]="Spain"; _createTeam("Sweden", msg.sender, startingPrice); teamIndexToName["22"]="Sweden"; _createTeam("Switzerland", msg.sender, startingPrice); teamIndexToName["23"]="Switzerland"; _createTeam("Costa Rica", msg.sender, startingPrice); teamIndexToName["24"]="Costa Rica"; _createTeam("Mexico", msg.sender, startingPrice); teamIndexToName["25"]="Mexico"; _createTeam("Panama", msg.sender, startingPrice); teamIndexToName["26"]="Panama"; _createTeam("Argentina", msg.sender, startingPrice); teamIndexToName["27"]="Argentina"; _createTeam("Brazil", msg.sender, startingPrice); teamIndexToName["28"]="Brazil"; _createTeam("Colombia", msg.sender, startingPrice); teamIndexToName["29"]="Colombia"; _createTeam("Peru", msg.sender, startingPrice); teamIndexToName["30"]="Peru"; _createTeam("Uruguay", msg.sender, startingPrice); teamIndexToName["31"]="Uruguay"; } function approve( address _to, uint256 _tokenId ) public onlyStart { require(_owns(msg.sender, _tokenId)); teamIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function getTeamId(string _name) public view returns (uint256 id) { return nameIndexToTeam[_name]; } function getTeam(uint256 _tokenId) public view returns ( string teamName, uint256 sellingPrice, address owner ) { Team storage team = teams[_tokenId]; teamName = team.name; sellingPrice = teamIndexToPrice[_tokenId]; owner = teamIndexToOwner[_tokenId]; } function getTeam4name(string _name) public view returns ( string teamName, uint256 sellingPrice, address owner ) { uint256 _tokenId = nameIndexToTeam[_name]; Team storage team = teams[_tokenId]; require(SafeMath.diffString(_name,team.name)==true); teamName = team.name; sellingPrice = teamIndexToPrice[_tokenId]; owner = teamIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string) { return NAME; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = teamIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCEO { _payout(_to); } function () public payable onlyStart { string memory data=string(msg.data); require(SafeMath.diffString(data,"")==false); //data is not empty string memory _name=teamIndexToName[data]; require(SafeMath.diffString(_name,"")==false); //name is not empty if(nameIndexToTeam[_name]==0){ require(SafeMath.diffString(_name,teams[0].name)==true); } purchase(nameIndexToTeam[_name]); } function purchase(uint256 _tokenId) public payable onlyStart { address oldOwner = teamIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = teamIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 92), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); teamIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130),100); _transfer(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.send(payment); //oldOwner take 92% of the sellingPrice } TokenSold(_tokenId, sellingPrice, teamIndexToPrice[_tokenId], oldOwner, newOwner, teams[_tokenId].name); msg.sender.send(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return teamIndexToPrice[_tokenId]; } function symbol() public pure returns (string) { return SYMBOL; } function takeOwnership(uint256 _tokenId) public onlyStart{ address newOwner = msg.sender; address oldOwner = teamIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPersons = totalSupply(); uint256 resultIndex = 0; uint256 teamId; for (teamId = 0; teamId <= totalPersons; teamId++) { if (teamIndexToOwner[teamId] == _owner) { result[resultIndex] = teamId; resultIndex++; } } return result; } } function totalSupply() public view returns (uint256 total) { return teams.length; } function transfer( address _to, uint256 _tokenId ) public onlyStart { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) public onlyStart{ require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return teamIndexToApproved[_tokenId] == _to; } function _createTeam(string _name, address _owner, uint256 _price) private { Team memory _team = Team({ name: _name }); uint256 newTeamId = teams.push(_team) - 1; nameIndexToTeam[_name]=newTeamId; Birth(newTeamId, _name, _owner); teamIndexToPrice[newTeamId] = _price; _transfer(address(0), _owner, newTeamId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == teamIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.send(this.balance); } else { _to.send(this.balance); } } function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; teamIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete teamIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } }
WorldCupToken
function WorldCupToken() public { ceoAddress = msg.sender; isStop=false; _createTeam("Egypt", msg.sender, startingPrice); teamIndexToName["0"]="Egypt"; _createTeam("Morocco", msg.sender, startingPrice); teamIndexToName["1"]="Morocco"; _createTeam("Nigeria", msg.sender, startingPrice); teamIndexToName["2"]="Nigeria"; _createTeam("Senegal", msg.sender, startingPrice); teamIndexToName["3"]="Senegal"; _createTeam("Tunisia", msg.sender, startingPrice); teamIndexToName["4"]="Tunisia"; _createTeam("Australia", msg.sender, startingPrice); teamIndexToName["5"]="Australia"; _createTeam("IR Iran", msg.sender, startingPrice); teamIndexToName["6"]="IR Iran"; _createTeam("Japan", msg.sender, startingPrice); teamIndexToName["7"]="Japan"; _createTeam("Korea Republic", msg.sender, startingPrice); teamIndexToName["8"]="Korea Republic"; _createTeam("Saudi Arabia", msg.sender, startingPrice); teamIndexToName["9"]="Saudi Arabia"; _createTeam("Belgium", msg.sender, startingPrice); teamIndexToName["10"]="Belgium"; _createTeam("Croatia", msg.sender, startingPrice); teamIndexToName["11"]="Croatia"; _createTeam("Denmark", msg.sender, startingPrice); teamIndexToName["12"]="Denmark"; _createTeam("England", msg.sender, startingPrice); teamIndexToName["13"]="England"; _createTeam("France", msg.sender, startingPrice); teamIndexToName["14"]="France"; _createTeam("Germany", msg.sender, startingPrice); teamIndexToName["15"]="Germany"; _createTeam("Iceland", msg.sender, startingPrice); teamIndexToName["16"]="Iceland"; _createTeam("Poland", msg.sender, startingPrice); teamIndexToName["17"]="Poland"; _createTeam("Portugal", msg.sender, startingPrice); teamIndexToName["18"]="Portugal"; _createTeam("Russia", msg.sender, startingPrice); teamIndexToName["19"]="Russia"; _createTeam("Serbia", msg.sender, startingPrice); teamIndexToName["20"]="Serbia"; _createTeam("Spain", msg.sender, startingPrice); teamIndexToName["21"]="Spain"; _createTeam("Sweden", msg.sender, startingPrice); teamIndexToName["22"]="Sweden"; _createTeam("Switzerland", msg.sender, startingPrice); teamIndexToName["23"]="Switzerland"; _createTeam("Costa Rica", msg.sender, startingPrice); teamIndexToName["24"]="Costa Rica"; _createTeam("Mexico", msg.sender, startingPrice); teamIndexToName["25"]="Mexico"; _createTeam("Panama", msg.sender, startingPrice); teamIndexToName["26"]="Panama"; _createTeam("Argentina", msg.sender, startingPrice); teamIndexToName["27"]="Argentina"; _createTeam("Brazil", msg.sender, startingPrice); teamIndexToName["28"]="Brazil"; _createTeam("Colombia", msg.sender, startingPrice); teamIndexToName["29"]="Colombia"; _createTeam("Peru", msg.sender, startingPrice); teamIndexToName["30"]="Peru"; _createTeam("Uruguay", msg.sender, startingPrice); teamIndexToName["31"]="Uruguay"; }
/*** CONSTRUCTOR ***/
NatSpecMultiLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 1303, 4701 ] }
628
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
WorldCupToken
contract WorldCupToken is ERC721 { event Birth(uint256 tokenId, string name, address owner); event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ string public constant NAME = "WorldCupToken"; string public constant SYMBOL = "WorldCupToken"; uint256 private startingPrice = 0.1 ether; mapping (uint256 => address) private teamIndexToOwner; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) private teamIndexToApproved; mapping (uint256 => uint256) private teamIndexToPrice; mapping (string => uint256) private nameIndexToTeam; // eg: Egypt => 0 mapping (string => string) private teamIndexToName; // eg: 0 => Egypt address private ceoAddress; bool private isStop; struct Team { string name; } Team[] private teams; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyStart() { require(isStop == false); _; } function setStop() public onlyCEO { isStop = true; } function setStart() public onlyCEO { isStop = false; } /*** CONSTRUCTOR ***/ function WorldCupToken() public { ceoAddress = msg.sender; isStop=false; _createTeam("Egypt", msg.sender, startingPrice); teamIndexToName["0"]="Egypt"; _createTeam("Morocco", msg.sender, startingPrice); teamIndexToName["1"]="Morocco"; _createTeam("Nigeria", msg.sender, startingPrice); teamIndexToName["2"]="Nigeria"; _createTeam("Senegal", msg.sender, startingPrice); teamIndexToName["3"]="Senegal"; _createTeam("Tunisia", msg.sender, startingPrice); teamIndexToName["4"]="Tunisia"; _createTeam("Australia", msg.sender, startingPrice); teamIndexToName["5"]="Australia"; _createTeam("IR Iran", msg.sender, startingPrice); teamIndexToName["6"]="IR Iran"; _createTeam("Japan", msg.sender, startingPrice); teamIndexToName["7"]="Japan"; _createTeam("Korea Republic", msg.sender, startingPrice); teamIndexToName["8"]="Korea Republic"; _createTeam("Saudi Arabia", msg.sender, startingPrice); teamIndexToName["9"]="Saudi Arabia"; _createTeam("Belgium", msg.sender, startingPrice); teamIndexToName["10"]="Belgium"; _createTeam("Croatia", msg.sender, startingPrice); teamIndexToName["11"]="Croatia"; _createTeam("Denmark", msg.sender, startingPrice); teamIndexToName["12"]="Denmark"; _createTeam("England", msg.sender, startingPrice); teamIndexToName["13"]="England"; _createTeam("France", msg.sender, startingPrice); teamIndexToName["14"]="France"; _createTeam("Germany", msg.sender, startingPrice); teamIndexToName["15"]="Germany"; _createTeam("Iceland", msg.sender, startingPrice); teamIndexToName["16"]="Iceland"; _createTeam("Poland", msg.sender, startingPrice); teamIndexToName["17"]="Poland"; _createTeam("Portugal", msg.sender, startingPrice); teamIndexToName["18"]="Portugal"; _createTeam("Russia", msg.sender, startingPrice); teamIndexToName["19"]="Russia"; _createTeam("Serbia", msg.sender, startingPrice); teamIndexToName["20"]="Serbia"; _createTeam("Spain", msg.sender, startingPrice); teamIndexToName["21"]="Spain"; _createTeam("Sweden", msg.sender, startingPrice); teamIndexToName["22"]="Sweden"; _createTeam("Switzerland", msg.sender, startingPrice); teamIndexToName["23"]="Switzerland"; _createTeam("Costa Rica", msg.sender, startingPrice); teamIndexToName["24"]="Costa Rica"; _createTeam("Mexico", msg.sender, startingPrice); teamIndexToName["25"]="Mexico"; _createTeam("Panama", msg.sender, startingPrice); teamIndexToName["26"]="Panama"; _createTeam("Argentina", msg.sender, startingPrice); teamIndexToName["27"]="Argentina"; _createTeam("Brazil", msg.sender, startingPrice); teamIndexToName["28"]="Brazil"; _createTeam("Colombia", msg.sender, startingPrice); teamIndexToName["29"]="Colombia"; _createTeam("Peru", msg.sender, startingPrice); teamIndexToName["30"]="Peru"; _createTeam("Uruguay", msg.sender, startingPrice); teamIndexToName["31"]="Uruguay"; } function approve( address _to, uint256 _tokenId ) public onlyStart { require(_owns(msg.sender, _tokenId)); teamIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function getTeamId(string _name) public view returns (uint256 id) { return nameIndexToTeam[_name]; } function getTeam(uint256 _tokenId) public view returns ( string teamName, uint256 sellingPrice, address owner ) { Team storage team = teams[_tokenId]; teamName = team.name; sellingPrice = teamIndexToPrice[_tokenId]; owner = teamIndexToOwner[_tokenId]; } function getTeam4name(string _name) public view returns ( string teamName, uint256 sellingPrice, address owner ) { uint256 _tokenId = nameIndexToTeam[_name]; Team storage team = teams[_tokenId]; require(SafeMath.diffString(_name,team.name)==true); teamName = team.name; sellingPrice = teamIndexToPrice[_tokenId]; owner = teamIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string) { return NAME; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = teamIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCEO { _payout(_to); } function () public payable onlyStart { string memory data=string(msg.data); require(SafeMath.diffString(data,"")==false); //data is not empty string memory _name=teamIndexToName[data]; require(SafeMath.diffString(_name,"")==false); //name is not empty if(nameIndexToTeam[_name]==0){ require(SafeMath.diffString(_name,teams[0].name)==true); } purchase(nameIndexToTeam[_name]); } function purchase(uint256 _tokenId) public payable onlyStart { address oldOwner = teamIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = teamIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 92), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); teamIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130),100); _transfer(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.send(payment); //oldOwner take 92% of the sellingPrice } TokenSold(_tokenId, sellingPrice, teamIndexToPrice[_tokenId], oldOwner, newOwner, teams[_tokenId].name); msg.sender.send(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return teamIndexToPrice[_tokenId]; } function symbol() public pure returns (string) { return SYMBOL; } function takeOwnership(uint256 _tokenId) public onlyStart{ address newOwner = msg.sender; address oldOwner = teamIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPersons = totalSupply(); uint256 resultIndex = 0; uint256 teamId; for (teamId = 0; teamId <= totalPersons; teamId++) { if (teamIndexToOwner[teamId] == _owner) { result[resultIndex] = teamId; resultIndex++; } } return result; } } function totalSupply() public view returns (uint256 total) { return teams.length; } function transfer( address _to, uint256 _tokenId ) public onlyStart { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) public onlyStart{ require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return teamIndexToApproved[_tokenId] == _to; } function _createTeam(string _name, address _owner, uint256 _price) private { Team memory _team = Team({ name: _name }); uint256 newTeamId = teams.push(_team) - 1; nameIndexToTeam[_name]=newTeamId; Birth(newTeamId, _name, _owner); teamIndexToPrice[newTeamId] = _price; _transfer(address(0), _owner, newTeamId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == teamIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.send(this.balance); } else { _to.send(this.balance); } } function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; teamIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete teamIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } }
_owns
function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == teamIndexToOwner[_tokenId]; }
/// Check for token ownership
NatSpecSingleLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 10378, 10518 ] }
629
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
WorldCupToken
contract WorldCupToken is ERC721 { event Birth(uint256 tokenId, string name, address owner); event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ string public constant NAME = "WorldCupToken"; string public constant SYMBOL = "WorldCupToken"; uint256 private startingPrice = 0.1 ether; mapping (uint256 => address) private teamIndexToOwner; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) private teamIndexToApproved; mapping (uint256 => uint256) private teamIndexToPrice; mapping (string => uint256) private nameIndexToTeam; // eg: Egypt => 0 mapping (string => string) private teamIndexToName; // eg: 0 => Egypt address private ceoAddress; bool private isStop; struct Team { string name; } Team[] private teams; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyStart() { require(isStop == false); _; } function setStop() public onlyCEO { isStop = true; } function setStart() public onlyCEO { isStop = false; } /*** CONSTRUCTOR ***/ function WorldCupToken() public { ceoAddress = msg.sender; isStop=false; _createTeam("Egypt", msg.sender, startingPrice); teamIndexToName["0"]="Egypt"; _createTeam("Morocco", msg.sender, startingPrice); teamIndexToName["1"]="Morocco"; _createTeam("Nigeria", msg.sender, startingPrice); teamIndexToName["2"]="Nigeria"; _createTeam("Senegal", msg.sender, startingPrice); teamIndexToName["3"]="Senegal"; _createTeam("Tunisia", msg.sender, startingPrice); teamIndexToName["4"]="Tunisia"; _createTeam("Australia", msg.sender, startingPrice); teamIndexToName["5"]="Australia"; _createTeam("IR Iran", msg.sender, startingPrice); teamIndexToName["6"]="IR Iran"; _createTeam("Japan", msg.sender, startingPrice); teamIndexToName["7"]="Japan"; _createTeam("Korea Republic", msg.sender, startingPrice); teamIndexToName["8"]="Korea Republic"; _createTeam("Saudi Arabia", msg.sender, startingPrice); teamIndexToName["9"]="Saudi Arabia"; _createTeam("Belgium", msg.sender, startingPrice); teamIndexToName["10"]="Belgium"; _createTeam("Croatia", msg.sender, startingPrice); teamIndexToName["11"]="Croatia"; _createTeam("Denmark", msg.sender, startingPrice); teamIndexToName["12"]="Denmark"; _createTeam("England", msg.sender, startingPrice); teamIndexToName["13"]="England"; _createTeam("France", msg.sender, startingPrice); teamIndexToName["14"]="France"; _createTeam("Germany", msg.sender, startingPrice); teamIndexToName["15"]="Germany"; _createTeam("Iceland", msg.sender, startingPrice); teamIndexToName["16"]="Iceland"; _createTeam("Poland", msg.sender, startingPrice); teamIndexToName["17"]="Poland"; _createTeam("Portugal", msg.sender, startingPrice); teamIndexToName["18"]="Portugal"; _createTeam("Russia", msg.sender, startingPrice); teamIndexToName["19"]="Russia"; _createTeam("Serbia", msg.sender, startingPrice); teamIndexToName["20"]="Serbia"; _createTeam("Spain", msg.sender, startingPrice); teamIndexToName["21"]="Spain"; _createTeam("Sweden", msg.sender, startingPrice); teamIndexToName["22"]="Sweden"; _createTeam("Switzerland", msg.sender, startingPrice); teamIndexToName["23"]="Switzerland"; _createTeam("Costa Rica", msg.sender, startingPrice); teamIndexToName["24"]="Costa Rica"; _createTeam("Mexico", msg.sender, startingPrice); teamIndexToName["25"]="Mexico"; _createTeam("Panama", msg.sender, startingPrice); teamIndexToName["26"]="Panama"; _createTeam("Argentina", msg.sender, startingPrice); teamIndexToName["27"]="Argentina"; _createTeam("Brazil", msg.sender, startingPrice); teamIndexToName["28"]="Brazil"; _createTeam("Colombia", msg.sender, startingPrice); teamIndexToName["29"]="Colombia"; _createTeam("Peru", msg.sender, startingPrice); teamIndexToName["30"]="Peru"; _createTeam("Uruguay", msg.sender, startingPrice); teamIndexToName["31"]="Uruguay"; } function approve( address _to, uint256 _tokenId ) public onlyStart { require(_owns(msg.sender, _tokenId)); teamIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function getTeamId(string _name) public view returns (uint256 id) { return nameIndexToTeam[_name]; } function getTeam(uint256 _tokenId) public view returns ( string teamName, uint256 sellingPrice, address owner ) { Team storage team = teams[_tokenId]; teamName = team.name; sellingPrice = teamIndexToPrice[_tokenId]; owner = teamIndexToOwner[_tokenId]; } function getTeam4name(string _name) public view returns ( string teamName, uint256 sellingPrice, address owner ) { uint256 _tokenId = nameIndexToTeam[_name]; Team storage team = teams[_tokenId]; require(SafeMath.diffString(_name,team.name)==true); teamName = team.name; sellingPrice = teamIndexToPrice[_tokenId]; owner = teamIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string) { return NAME; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = teamIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCEO { _payout(_to); } function () public payable onlyStart { string memory data=string(msg.data); require(SafeMath.diffString(data,"")==false); //data is not empty string memory _name=teamIndexToName[data]; require(SafeMath.diffString(_name,"")==false); //name is not empty if(nameIndexToTeam[_name]==0){ require(SafeMath.diffString(_name,teams[0].name)==true); } purchase(nameIndexToTeam[_name]); } function purchase(uint256 _tokenId) public payable onlyStart { address oldOwner = teamIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = teamIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 92), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); teamIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130),100); _transfer(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.send(payment); //oldOwner take 92% of the sellingPrice } TokenSold(_tokenId, sellingPrice, teamIndexToPrice[_tokenId], oldOwner, newOwner, teams[_tokenId].name); msg.sender.send(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return teamIndexToPrice[_tokenId]; } function symbol() public pure returns (string) { return SYMBOL; } function takeOwnership(uint256 _tokenId) public onlyStart{ address newOwner = msg.sender; address oldOwner = teamIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPersons = totalSupply(); uint256 resultIndex = 0; uint256 teamId; for (teamId = 0; teamId <= totalPersons; teamId++) { if (teamIndexToOwner[teamId] == _owner) { result[resultIndex] = teamId; resultIndex++; } } return result; } } function totalSupply() public view returns (uint256 total) { return teams.length; } function transfer( address _to, uint256 _tokenId ) public onlyStart { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) public onlyStart{ require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return teamIndexToApproved[_tokenId] == _to; } function _createTeam(string _name, address _owner, uint256 _price) private { Team memory _team = Team({ name: _name }); uint256 newTeamId = teams.push(_team) - 1; nameIndexToTeam[_name]=newTeamId; Birth(newTeamId, _name, _owner); teamIndexToPrice[newTeamId] = _price; _transfer(address(0), _owner, newTeamId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == teamIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.send(this.balance); } else { _to.send(this.balance); } } function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; teamIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete teamIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } }
_payout
function _payout(address _to) private { if (_to == address(0)) { ceoAddress.send(this.balance); } else { _to.send(this.balance); } }
/// For paying out balance on contract
NatSpecSingleLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 10561, 10728 ] }
630
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } function diffString(string a, string b) internal pure returns (bool) { bytes memory ab=bytes(a); bytes memory bb=bytes(b); if(ab.length!=bb.length){ return false; } uint len=ab.length; for(uint i=0;i<len;i++){ if(ab[i]!=bb[i]){ return false; } } return true; } }
mul
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 Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 87, 270 ] }
631
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } function diffString(string a, string b) internal pure returns (bool) { bytes memory ab=bytes(a); bytes memory bb=bytes(b); if(ab.length!=bb.length){ return false; } uint len=ab.length; for(uint i=0;i<len;i++){ if(ab[i]!=bb[i]){ return false; } } return true; } }
div
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; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 352, 625 ] }
632
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } function diffString(string a, string b) internal pure returns (bool) { bytes memory ab=bytes(a); bytes memory bb=bytes(b); if(ab.length!=bb.length){ return false; } uint len=ab.length; for(uint i=0;i<len;i++){ if(ab[i]!=bb[i]){ return false; } } return true; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 738, 854 ] }
633
WorldCupToken
WorldCupToken.sol
0x2ee5054ee925a122976281e1dfea22dc873de96f
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } function diffString(string a, string b) internal pure returns (bool) { bytes memory ab=bytes(a); bytes memory bb=bytes(b); if(ab.length!=bb.length){ return false; } uint len=ab.length; for(uint i=0;i<len;i++){ if(ab[i]!=bb[i]){ return false; } } return true; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.22+commit.4cb486ee
bzzr://058e3374d1884d72b6c50821321b1d0aeec55b2933510d76af2ac7678fbb136a
{ "func_code_index": [ 916, 1052 ] }
634
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
IERC20
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); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 90, 149 ] }
635
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
IERC20
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); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 228, 300 ] }
636
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
IERC20
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); }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 516, 597 ] }
637
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
IERC20
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); }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 868, 955 ] }
638
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
IERC20
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); }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1604, 1682 ] }
639
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
IERC20
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); }
transferFrom
function transferFrom(address sender, address recipient, 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1985, 2086 ] }
640
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
add
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 on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 241, 421 ] }
641
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
sub
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 on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 681, 819 ] }
642
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
sub
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 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._ */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1139, 1330 ] }
643
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
mul
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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1566, 2029 ] }
644
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
div
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 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 2480, 2614 ] }
645
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
div
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 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._ */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 3125, 3467 ] }
646
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
mod
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 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 3907, 4039 ] }
647
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeMath
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; } }
/** * @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. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @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._ */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 4539, 4706 ] }
648
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Address
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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
isContract
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
/** * @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 * ==== */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 589, 1203 ] }
649
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Address
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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
toPayable
function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); }
/** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1408, 1537 ] }
650
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Address
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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); }
/** * @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]. * * _Available since v2.4.0._ */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 2490, 2859 ] }
651
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
SafeERC20
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)); } 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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"); } } }
callOptionalReturn
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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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"); } }
/** * @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). */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 2088, 3187 ] }
652
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Math
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); } }
max
function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; }
/** * @dev Returns the largest of two numbers. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 79, 188 ] }
653
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Math
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); } }
min
function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; }
/** * @dev Returns the smallest of two numbers. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 255, 363 ] }
654
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Math
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); } }
average
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); }
/** * @dev Returns the average of two numbers. The result is rounded towards * zero. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 472, 666 ] }
655
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Context
contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
/* * @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. */
Comment
_msgSender
function _msgSender() internal view returns (address payable) { return msg.sender; }
// solhint-disable-previous-line no-empty-blocks
LineComment
v0.5.17+commit.d19bba13
{ "func_code_index": [ 259, 359 ] }
656
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 480, 561 ] }
657
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
isOwner
function isOwner() public view returns (bool) { return _msgSender() == _owner; }
/** * @dev Returns true if the caller is the current owner. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 831, 927 ] }
658
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1265, 1406 ] }
659
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1551, 1662 ] }
660
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
_transferOwnership
function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). */
NatSpecMultiLine
v0.5.17+commit.d19bba13
{ "func_code_index": [ 1759, 1988 ] }
661
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
Uni
interface Uni { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); // Balancer swap function function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter); }
swapExactAmountIn
function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter);
// Balancer swap function
LineComment
v0.5.17+commit.d19bba13
{ "func_code_index": [ 259, 485 ] }
662
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
DFDComptroller
contract DFDComptroller is RewardDistributionRecipient, IDFDComptroller { using SafeERC20 for IERC20; using SafeMath for uint; uint public constant DURATION = 7 days; address public constant bal = address(0xD8E9690eFf99E21a2de25E0b148ffaf47F47C972); IERC20 public constant dusd = IERC20(0x5BC25f649fc4e26069dDF4cF4010F9f706c23831); IERC20 public constant dfd = IERC20(0x20c36f062a31865bED8a5B1e512D9a1A20AA333A); IComptroller public constant comptroller = IComptroller(0xf79b548ff56E661ee19a59303178E444E9e81FCc); address public beneficiary; uint public periodFinish; uint public rewardRate; uint public lastUpdateTime; uint public rewardStored; uint public rewardPaid; mapping(address => bool) public isHarvester; event RewardAdded(uint reward); event RewardPaid(address indexed user, uint256 reward); event Harvested(uint indexed dusd, uint indexed dfd); modifier onlyHarvester() { require(isHarvester[_msgSender()], "Caller is not authorized harvester"); _; } function getReward() external { _updateReward(); require(msg.sender == beneficiary, "GET_REWARD_NO_AUTH"); uint reward = rewardStored.sub(rewardPaid); if (reward > 0) { rewardPaid = rewardStored; dfd.safeTransfer(beneficiary, reward); emit RewardPaid(beneficiary, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution { _updateReward(); dfd.safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } function harvest(uint minAmountOut) onlyHarvester external { // This contract will receive dusd because it should be a registered beneficiary comptroller.harvest(); uint256 _dusd = dusd.balanceOf(address(this)); if (_dusd > 0) { dusd.approve(bal, _dusd); (uint tokenAmountOut,) = Uni(bal).swapExactAmountIn(address(dusd), _dusd, address(dfd), minAmountOut, uint(-1) /* max */); if (tokenAmountOut > 0) { dfd.safeTransfer(beneficiary, tokenAmountOut); } emit Harvested(_dusd, tokenAmountOut); } } function setHarvester(address _harvester, bool _status) external onlyOwner { isHarvester[_harvester] = _status; } function setBeneficiary(address _beneficiary) external onlyOwner { beneficiary = _beneficiary; } /* ##### View ##### */ function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(_timestamp(), periodFinish); } function availableReward() public view returns(uint) { return lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .add(rewardStored) .sub(rewardPaid); } /* ##### Internal ##### */ function _updateReward() internal { uint _lastTimeRewardApplicable = lastTimeRewardApplicable(); rewardStored = rewardStored.add( _lastTimeRewardApplicable .sub(lastUpdateTime) .mul(rewardRate) ); lastUpdateTime = _lastTimeRewardApplicable; } function _timestamp() internal view returns (uint) { return block.timestamp; } }
lastTimeRewardApplicable
function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(_timestamp(), periodFinish); }
/* ##### View ##### */
Comment
v0.5.17+commit.d19bba13
{ "func_code_index": [ 3026, 3156 ] }
663
DFDComptroller
DFDComptroller.sol
0xf5f850daddc393ce325d8ac395519224f498460f
Solidity
DFDComptroller
contract DFDComptroller is RewardDistributionRecipient, IDFDComptroller { using SafeERC20 for IERC20; using SafeMath for uint; uint public constant DURATION = 7 days; address public constant bal = address(0xD8E9690eFf99E21a2de25E0b148ffaf47F47C972); IERC20 public constant dusd = IERC20(0x5BC25f649fc4e26069dDF4cF4010F9f706c23831); IERC20 public constant dfd = IERC20(0x20c36f062a31865bED8a5B1e512D9a1A20AA333A); IComptroller public constant comptroller = IComptroller(0xf79b548ff56E661ee19a59303178E444E9e81FCc); address public beneficiary; uint public periodFinish; uint public rewardRate; uint public lastUpdateTime; uint public rewardStored; uint public rewardPaid; mapping(address => bool) public isHarvester; event RewardAdded(uint reward); event RewardPaid(address indexed user, uint256 reward); event Harvested(uint indexed dusd, uint indexed dfd); modifier onlyHarvester() { require(isHarvester[_msgSender()], "Caller is not authorized harvester"); _; } function getReward() external { _updateReward(); require(msg.sender == beneficiary, "GET_REWARD_NO_AUTH"); uint reward = rewardStored.sub(rewardPaid); if (reward > 0) { rewardPaid = rewardStored; dfd.safeTransfer(beneficiary, reward); emit RewardPaid(beneficiary, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution { _updateReward(); dfd.safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } function harvest(uint minAmountOut) onlyHarvester external { // This contract will receive dusd because it should be a registered beneficiary comptroller.harvest(); uint256 _dusd = dusd.balanceOf(address(this)); if (_dusd > 0) { dusd.approve(bal, _dusd); (uint tokenAmountOut,) = Uni(bal).swapExactAmountIn(address(dusd), _dusd, address(dfd), minAmountOut, uint(-1) /* max */); if (tokenAmountOut > 0) { dfd.safeTransfer(beneficiary, tokenAmountOut); } emit Harvested(_dusd, tokenAmountOut); } } function setHarvester(address _harvester, bool _status) external onlyOwner { isHarvester[_harvester] = _status; } function setBeneficiary(address _beneficiary) external onlyOwner { beneficiary = _beneficiary; } /* ##### View ##### */ function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(_timestamp(), periodFinish); } function availableReward() public view returns(uint) { return lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .add(rewardStored) .sub(rewardPaid); } /* ##### Internal ##### */ function _updateReward() internal { uint _lastTimeRewardApplicable = lastTimeRewardApplicable(); rewardStored = rewardStored.add( _lastTimeRewardApplicable .sub(lastUpdateTime) .mul(rewardRate) ); lastUpdateTime = _lastTimeRewardApplicable; } function _timestamp() internal view returns (uint) { return block.timestamp; } }
_updateReward
function _updateReward() internal { uint _lastTimeRewardApplicable = lastTimeRewardApplicable(); rewardStored = rewardStored.add( _lastTimeRewardApplicable .sub(lastUpdateTime) .mul(rewardRate) ); lastUpdateTime = _lastTimeRewardApplicable; }
/* ##### Internal ##### */
Comment
v0.5.17+commit.d19bba13
{ "func_code_index": [ 3421, 3747 ] }
664
LuckyBox
contracts/luckybox/LuckyBox.sol
0xe19866986976e84b2c2691169c9f9b1baa433893
Solidity
LuckyBox
contract LuckyBox is Pausable { using SafeMath for *; uint256 public goldBoxAmountForSale; uint256 public silverBoxAmountForSale; uint256 public goldBoxPrice; // amount of eth for each gold bag. uint256 public silverBoxPrice; address public wallet; mapping (address => uint256) public goldSalesRecord; mapping (address => uint256) public silverSalesRecord; uint256 public goldSaleLimit; uint256 public silverSaleLimit; constructor(address _wallet, uint256 _goldBoxAmountForSale, uint256 _silverBoxAmountForSale) public { require(_wallet != address(0), "need a good wallet to store fund"); require(_goldBoxAmountForSale > 0, "Gold bag amount need to be no-zero"); require(_silverBoxAmountForSale > 0, "Silver bag amount need to be no-zero"); wallet = _wallet; goldBoxAmountForSale = _goldBoxAmountForSale; silverBoxAmountForSale = _silverBoxAmountForSale; goldSaleLimit = 10; silverSaleLimit = 100; } function buyBoxs(address _buyer, uint256 _goldBoxAmount, uint256 _silverBoxAmount) payable public whenNotPaused { require(_buyer != address(0)); require(_goldBoxAmount <= goldBoxAmountForSale && _silverBoxAmount <= silverBoxAmountForSale); require(goldSalesRecord[_buyer] + _goldBoxAmount <= goldSaleLimit); require(silverSalesRecord[_buyer] + _silverBoxAmount <= silverSaleLimit); uint256 charge = _goldBoxAmount.mul(goldBoxPrice).add(_silverBoxAmount.mul(silverBoxPrice)); require(msg.value >= charge, "No enough ether for buying lucky bags."); require(_goldBoxAmount > 0 || _silverBoxAmount > 0); if (_goldBoxAmount > 0) { goldBoxAmountForSale = goldBoxAmountForSale.sub(_goldBoxAmount); goldSalesRecord[_buyer] += _goldBoxAmount; emit GoldBoxSale(_buyer, _goldBoxAmount, goldBoxPrice); } if (_silverBoxAmount > 0) { silverBoxAmountForSale = silverBoxAmountForSale.sub(_silverBoxAmount); silverSalesRecord[_buyer] += _silverBoxAmount; emit SilverBoxSale(_buyer, _silverBoxAmount, silverBoxPrice); } wallet.transfer(charge); if (msg.value > charge) { uint256 weiToRefund = msg.value.sub(charge); _buyer.transfer(weiToRefund); emit EthRefunded(_buyer, weiToRefund); } } function buyBoxs(uint256 _goldBoxAmount, uint256 _silverBoxAmount) payable public whenNotPaused { buyBoxs(msg.sender, _goldBoxAmount, _silverBoxAmount); } function updateGoldBoxAmountAndPrice(uint256 _goldBoxAmountForSale, uint256 _goldBoxPrice, uint256 _goldLimit) public onlyOwner { goldBoxAmountForSale = _goldBoxAmountForSale; goldBoxPrice = _goldBoxPrice; goldSaleLimit = _goldLimit; } function updateSilverBoxAmountAndPrice(uint256 _silverBoxAmountForSale, uint256 _silverBoxPrice, uint256 _silverLimit) public onlyOwner { silverBoxAmountForSale = _silverBoxAmountForSale; silverBoxPrice = _silverBoxPrice; silverSaleLimit = _silverLimit; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyOwner public { if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event GoldBoxSale(address indexed _user, uint256 _amount, uint256 _price); event SilverBoxSale(address indexed _user, uint256 _amount, uint256 _price); event EthRefunded(address indexed buyer, uint256 value); event ClaimedTokens(address indexed _token, address indexed _to, uint _amount); }
claimTokens
function claimTokens(address _token) onlyOwner public { if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); }
////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://bd5baecaec99e2d28aacef94dd8f2c6af71c336f843a6eca11f988fcf3d10d30
{ "func_code_index": [ 3572, 3920 ] }
665
Oracle
Oracle.sol
0x9b8b9f6146b29cc32208f42b995e70f0eb2807f3
Solidity
Oracle
contract Oracle is Manageable { address[] private _calculations; address public usdcAddress; constructor(address _managementListAddress, address _usdcAddress) Manageable(_managementListAddress) { usdcAddress = _usdcAddress; } /** * The oracle supports an array of calculation contracts. Each calculation contract must implement getPriceUsdc(). * When setting calculation contracts all calculations must be set at the same time (we intentionally do not support for adding/removing calculations). * The order of calculation contracts matters as it determines the order preference in the cascading fallback mechanism. */ function setCalculations(address[] memory calculationAddresses) public onlyManagers { _calculations = calculationAddresses; } function calculations() external view returns (address[] memory) { return (_calculations); } function getPriceUsdcRecommended(address tokenAddress) public view returns (uint256) { (bool success, bytes memory data) = address(this).staticcall( abi.encodeWithSignature("getPriceUsdc(address)", tokenAddress) ); if (success) { return abi.decode(data, (uint256)); } revert("Oracle: No price found"); } /** * Cascading fallback proxy * * Loop through all contracts in _calculations and attempt to forward the method call to each underlying contract. * This allows users to call getPriceUsdc() on the oracle contract and the result of the first non-reverting contract that * implements getPriceUsdc() will be returned. * * This mechanism also exposes all public methods for calculation contracts. This allows a user to * call oracle.isIronBankMarket() or oracle.isCurveLpToken() even though these methods live on different contracts. */ fallback() external { for (uint256 i = 0; i < _calculations.length; i++) { address calculation = _calculations[i]; assembly { let _target := calculation calldatacopy(0, 0, calldatasize()) let success := staticcall( gas(), _target, 0, calldatasize(), 0, 0 ) returndatacopy(0, 0, returndatasize()) if success { return(0, returndatasize()) } } } revert("Oracle: Fallback proxy failed to return data"); } }
setCalculations
function setCalculations(address[] memory calculationAddresses) public onlyManagers { _calculations = calculationAddresses; }
/** * The oracle supports an array of calculation contracts. Each calculation contract must implement getPriceUsdc(). * When setting calculation contracts all calculations must be set at the same time (we intentionally do not support for adding/removing calculations). * The order of calculation contracts matters as it determines the order preference in the cascading fallback mechanism. */
NatSpecMultiLine
v0.8.2+commit.661d1103
None
ipfs://55dab22b066012d3a361f6fbae7cceee9048d1267a233e4cce18b831087099c6
{ "func_code_index": [ 695, 862 ] }
666
Oracle
Oracle.sol
0x9b8b9f6146b29cc32208f42b995e70f0eb2807f3
Solidity
Oracle
contract Oracle is Manageable { address[] private _calculations; address public usdcAddress; constructor(address _managementListAddress, address _usdcAddress) Manageable(_managementListAddress) { usdcAddress = _usdcAddress; } /** * The oracle supports an array of calculation contracts. Each calculation contract must implement getPriceUsdc(). * When setting calculation contracts all calculations must be set at the same time (we intentionally do not support for adding/removing calculations). * The order of calculation contracts matters as it determines the order preference in the cascading fallback mechanism. */ function setCalculations(address[] memory calculationAddresses) public onlyManagers { _calculations = calculationAddresses; } function calculations() external view returns (address[] memory) { return (_calculations); } function getPriceUsdcRecommended(address tokenAddress) public view returns (uint256) { (bool success, bytes memory data) = address(this).staticcall( abi.encodeWithSignature("getPriceUsdc(address)", tokenAddress) ); if (success) { return abi.decode(data, (uint256)); } revert("Oracle: No price found"); } /** * Cascading fallback proxy * * Loop through all contracts in _calculations and attempt to forward the method call to each underlying contract. * This allows users to call getPriceUsdc() on the oracle contract and the result of the first non-reverting contract that * implements getPriceUsdc() will be returned. * * This mechanism also exposes all public methods for calculation contracts. This allows a user to * call oracle.isIronBankMarket() or oracle.isCurveLpToken() even though these methods live on different contracts. */ fallback() external { for (uint256 i = 0; i < _calculations.length; i++) { address calculation = _calculations[i]; assembly { let _target := calculation calldatacopy(0, 0, calldatasize()) let success := staticcall( gas(), _target, 0, calldatasize(), 0, 0 ) returndatacopy(0, 0, returndatasize()) if success { return(0, returndatasize()) } } } revert("Oracle: Fallback proxy failed to return data"); } }
/** * Cascading fallback proxy * * Loop through all contracts in _calculations and attempt to forward the method call to each underlying contract. * This allows users to call getPriceUsdc() on the oracle contract and the result of the first non-reverting contract that * implements getPriceUsdc() will be returned. * * This mechanism also exposes all public methods for calculation contracts. This allows a user to * call oracle.isIronBankMarket() or oracle.isCurveLpToken() even though these methods live on different contracts. */
NatSpecMultiLine
v0.8.2+commit.661d1103
None
ipfs://55dab22b066012d3a361f6fbae7cceee9048d1267a233e4cce18b831087099c6
{ "func_code_index": [ 2011, 2753 ] }
667
Catlacs
contracts/Catlacs.sol
0x60d32d3bdb7af2f221564f57fd9f4ef0cb4a2392
Solidity
Catlacs
contract Catlacs is ERC721Enumerable, Ownable, ReentrancyGuard { using Strings for uint256; IERC1155 public gutterCatNFTAddress; string private _baseTokenURI = "https://raw.githubusercontent.com/nftinvesting/Catlacs/master/other/"; string private _contractURI = "https://raw.githubusercontent.com/nftinvesting/Catlacs/master/other/contract_uri.json"; event Action(uint256 nftID, uint256 value, uint256 actionID, string payload); constructor(address _catsNFTAddress) ERC721("Catlacs", "CATLACS") { gutterCatNFTAddress = IERC1155(_catsNFTAddress); } function mint(uint256 _catID) external nonReentrant { //verify ownership require( gutterCatNFTAddress.balanceOf(msg.sender, _catID) > 0, "you have to own this cat with this id" ); require(!_exists(_catID), "Mint: Token already exist."); _safeMint(msg.sender, _catID); } //a custom action that supports anything. function action( uint256 _nftID, uint256 _actionID, string memory payload ) external payable { require(ownerOf(_nftID) == msg.sender, "you must own this NFT"); emit Action(_nftID, msg.value, _actionID, payload); } /* * Non important functions */ function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved"); _burn(tokenId); } function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_baseTokenURI, _tokenId.toString())); } function setBaseURI(string memory newBaseURI) public onlyOwner { _baseTokenURI = newBaseURI; } function setContractURI(string memory newuri) public onlyOwner { _contractURI = newuri; } function contractURI() public view returns (string memory) { return _contractURI; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function reclaimToken(IERC20 token) public onlyOwner { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
action
function action( uint256 _nftID, uint256 _actionID, string memory payload ) external payable { require(ownerOf(_nftID) == msg.sender, "you must own this NFT"); emit Action(_nftID, msg.value, _actionID, payload); }
//a custom action that supports anything.
LineComment
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 898, 1124 ] }
668
Catlacs
contracts/Catlacs.sol
0x60d32d3bdb7af2f221564f57fd9f4ef0cb4a2392
Solidity
Catlacs
contract Catlacs is ERC721Enumerable, Ownable, ReentrancyGuard { using Strings for uint256; IERC1155 public gutterCatNFTAddress; string private _baseTokenURI = "https://raw.githubusercontent.com/nftinvesting/Catlacs/master/other/"; string private _contractURI = "https://raw.githubusercontent.com/nftinvesting/Catlacs/master/other/contract_uri.json"; event Action(uint256 nftID, uint256 value, uint256 actionID, string payload); constructor(address _catsNFTAddress) ERC721("Catlacs", "CATLACS") { gutterCatNFTAddress = IERC1155(_catsNFTAddress); } function mint(uint256 _catID) external nonReentrant { //verify ownership require( gutterCatNFTAddress.balanceOf(msg.sender, _catID) > 0, "you have to own this cat with this id" ); require(!_exists(_catID), "Mint: Token already exist."); _safeMint(msg.sender, _catID); } //a custom action that supports anything. function action( uint256 _nftID, uint256 _actionID, string memory payload ) external payable { require(ownerOf(_nftID) == msg.sender, "you must own this NFT"); emit Action(_nftID, msg.value, _actionID, payload); } /* * Non important functions */ function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved"); _burn(tokenId); } function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_baseTokenURI, _tokenId.toString())); } function setBaseURI(string memory newBaseURI) public onlyOwner { _baseTokenURI = newBaseURI; } function setContractURI(string memory newuri) public onlyOwner { _contractURI = newuri; } function contractURI() public view returns (string memory) { return _contractURI; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function reclaimToken(IERC20 token) public onlyOwner { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
burn
function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved"); _burn(tokenId); }
/* * Non important functions */
Comment
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 1163, 1322 ] }
669
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Context
contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
/* * @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. */
Comment
_msgSender
function _msgSender() internal view returns (address payable) { return msg.sender; }
// solhint-disable-previous-line no-empty-blocks
LineComment
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 265, 368 ] }
670
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. * * 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. */
NatSpecMultiLine
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 497, 581 ] }
671
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. * * 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. */
NatSpecMultiLine
isOwner
function isOwner() public view returns (bool) { return _msgSender() == _owner; }
/** * @dev Returns true if the caller is the current owner. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 863, 962 ] }
672
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. * * 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. */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @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. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 1308, 1453 ] }
673
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. * * 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. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 1603, 1717 ] }
674
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Ownable
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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. * * 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. */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 1818, 2052 ] }
675
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
_addToBlocklist
function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; }
/** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 1117, 1364 ] }
676
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
batchAddToBlocklist
function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } }
/** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 1567, 1759 ] }
677
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
addToBlocklist
function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); }
/** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 1965, 2086 ] }
678
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
_removeFromBlocklist
function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; }
/** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 2292, 2684 ] }
679
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
batchRemoveFromBlocklist
function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } }
/** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 2891, 3093 ] }
680
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
removeFromBlocklist
function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); }
/** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 3303, 3434 ] }
681
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
isBlocklisted
function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; }
/** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 3604, 3989 ] }
682
Blocklist
Blocklist.sol
0x9c8a2011ccb697d7ede3c94f9fba5686a04deacb
Solidity
Blocklist
contract Blocklist is Ownable { /** * @dev The index of each user in the list */ mapping(address => uint256) private _userIndex; /** * @dev The list itself */ address[] private _userList; /** * @notice Event emitted when a user is added to the blocklist */ event addedToBlocklist(address indexed account, address by); /** * @notice Event emitted when a user is removed from the blocklist */ event removedFromBlocklist(address indexed account, address by); /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyInBlocklist(address account) { require(isBlocklisted(account), "Not in blocklist"); _; } /** * @notice Modifier to facilitate checking the blocklist */ modifier onlyNotInBlocklist(address account) { require(!isBlocklisted(account), "Already in blocklist"); _; } /** * @dev Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; } /** * @notice Adds many addresses to the blocklist at once * @param accounts[] The list of addresses to add * @dev Fails if at least one of the addresses was already blocklisted */ function batchAddToBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_addToBlocklist(accounts[i])); } } /** * @notice Adds an address to the blocklist * @param account The address to add * @return true if the operation succeeded * @dev Fails if the address was already blocklisted */ function addToBlocklist(address account) external onlyOwner returns(bool) { return _addToBlocklist(account); } /** * @dev Removes an address from the blocklist * @param account The address to remove * @return true if the operation succeeds * @dev Fails if the address was not blocklisted */ function _removeFromBlocklist(address account) private onlyInBlocklist(account) returns(bool) { uint rowToDelete = _userIndex[account]; address keyToMove = _userList[_userList.length-1]; _userList[rowToDelete] = keyToMove; _userIndex[keyToMove] = rowToDelete; _userList.length--; emit removedFromBlocklist(account, msg.sender); return true; } /** * @notice Removes many addresses from the blocklist at once * @param accounts[] The list of addresses to remove * @dev Fails if at least one of the addresses was not blocklisted */ function batchRemoveFromBlocklist(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { require(_removeFromBlocklist(accounts[i])); } } /** * @notice Removes an address from the blocklist * @param account The address to remove * @dev Fails if the address was not blocklisted * @return true if the operation succeeded */ function removeFromBlocklist(address account) external onlyOwner returns(bool) { return _removeFromBlocklist(account); } /** * @notice Consults whether an address is blocklisted * @param account The address to check * @return bool True if the address is blocklisted */ function isBlocklisted(address account) public view returns(bool) { if(_userList.length == 0) return false; // We don't want to throw when querying for an out-of-bounds index. // It can happen when the list has been shrunk after a deletion. if(_userIndex[account] >= _userList.length) return false; return _userList[_userIndex[account]] == account; } /** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */ function getFullList() public view returns(address[] memory) { return _userList; } }
/** * @title Blocklist * @dev This contract manages a list of addresses and has a simple CRUD */
NatSpecMultiLine
getFullList
function getFullList() public view returns(address[] memory) { return _userList; }
/** * @notice Fetches the list of all blocklisted addresses * @return array The list of currently blocklisted addresses */
NatSpecMultiLine
v0.5.16+commit.9c3226ce
Apache-2.0
bzzr://19d509ad781f8a222c98fb9abcd0929c32fa5b8a89791dd6ceac592aa6aa1db9
{ "func_code_index": [ 4130, 4223 ] }
683
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() public { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 261, 321 ] }
684
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 644, 820 ] }
685
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
powerUpContract
function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; }
/** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 2598, 3166 ] }
686
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
emergencyStop
function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); }
//for Emergency stop of the sale
LineComment
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 3211, 3401 ] }
687
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
finalize
function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); }
/** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 3553, 3765 ] }
688
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
saleTimeOver
function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; }
// @return true if all the tiers has been ended
LineComment
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 3827, 4142 ] }
689
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
withdrawFunds
function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); }
//if crowdsales is over, the money rasied should be transferred to the wallet address
LineComment
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 4238, 4336 ] }
690
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
setTiersInfo
function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); }
/** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 5070, 7238 ] }
691
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
ownerWithdrawUnspentCredits
function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); }
/** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 7410, 7626 ] }
692
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
function()public payable{ buyTokens(msg.sender); }
//Fallback function used to buytokens
LineComment
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 7674, 7740 ] }
693
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
buyTokens
function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); }
/** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 7892, 9150 ] }
694
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
getCurrentlyRunningTier
function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; }
/** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 9509, 9756 ] }
695
TRANXCrowdsales
TRANXCrowdsales.sol
0xaa18c6a2fd0891f3d2d7fd79b869d73a98ce9c7f
Solidity
TRANXCrowdsales
contract TRANXCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function TRANXCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
getFundingInfoForUser
function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); }
/** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://a61d079b4af507c07f7c44fedf8ca1257ec93b16eb7113ca166643b4852313ec
{ "func_code_index": [ 9889, 10034 ] }
696
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } }
mul
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 Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 89, 272 ] }
697
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } }
div
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; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 356, 629 ] }
698
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 744, 860 ] }
699
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
SafeMath
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't hold return c; } /** * @dev Substracts 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; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 924, 1060 ] }
700
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
Ownable
function Ownable() public { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 261, 321 ] }
701
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 640, 816 ] }
702
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } }
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev total number of tokens in existence */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 199, 287 ] }
703
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } }
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 445, 836 ] }
704
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @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 balance) { return balances[_owner]; } }
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
/** * @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. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 1042, 1154 ] }
705
DetherToken
DetherToken.sol
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @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(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _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'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; Approval(msg.sender, _spender, _value); return true; } /** * @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 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, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _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 */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://31679c746f39dbdd5c090cd5514df308ef9098903284459826a5c4f30a8510bd
{ "func_code_index": [ 401, 853 ] }
706