Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
10
// Divide a scalar by an Exp, then truncate to return an unsigned integer _scalar uint _divisor expreturn MathError, Exp /
function divScalarByExpTruncate(uint _scalar, Exp memory _divisor) pure internal returns (BaseReporter.MathError, uint) { (BaseReporter.MathError err, Exp memory fraction) = divScalarByExp(_scalar, _divisor); if (err != BaseReporter.MathError.NO_ERROR) { return (err, 0); } return (BaseReporter.MathError.NO_ERROR, truncate(fraction)); }
function divScalarByExpTruncate(uint _scalar, Exp memory _divisor) pure internal returns (BaseReporter.MathError, uint) { (BaseReporter.MathError err, Exp memory fraction) = divScalarByExp(_scalar, _divisor); if (err != BaseReporter.MathError.NO_ERROR) { return (err, 0); } return (BaseReporter.MathError.NO_ERROR, truncate(fraction)); }
21,008
141
// Overflows are incredibly unrealistic. balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2128) - 1 updatedIndex overflows if currentIndex + quantity > 1.56e77 (2256) - 1
unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) {
unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) {
7,835
96
// Set the LockedGoldOracle addressoracleAddress The address for oracle return An bool representing successfully changing oracle address/
function setOracleAddress(address oracleAddress) external onlyOwner returns(bool) { require(oracleAddress != address(0)); _oracle = oracleAddress; return true; }
function setOracleAddress(address oracleAddress) external onlyOwner returns(bool) { require(oracleAddress != address(0)); _oracle = oracleAddress; return true; }
25,573
139
// Transmission address for the s_oracles[a].index'th oracle. I.e., if a report is received by OffchainAggregator.transmit in which msg.sender is a, it is attributed to the s_oracles[a].index'th oracle.
Transmitter
Transmitter
25,964
10
// Storage Delete Methods //_key The key for the record
function deleteAddress(bytes32 _key) external;
function deleteAddress(bytes32 _key) external;
45,806
23
// The address of an account approved to submit proposals using the/ representation of this contract
address public approvedSubmitter;
address public approvedSubmitter;
9,245
4
// operationsType The list of operations type used: CALL = 0; CREATE = 1; CREATE2 = 2; STATICCALL = 3; DELEGATECALL = 4 targets The list of addresses to call. `targets` will be unused if a contract is created (operation types 1 and 2). values The list of native token amounts to transfer (in Wei) datas The list of call data, or the creation bytecode of the contract to deployGeneric batch executor function to: - send native tokens to any address.- interact with any contract by passing an abi-encoded function call in the `datas` parameter.- deploy a contract by providing its
function executeBatch(
function executeBatch(
25,835
3
// Tracks the state of the seedsale
State private _state;
State private _state;
12,496
158
// Weighted payout to bettors based on their contribution to the winning pool
for (uint k = 0; k < bettors.length; k++) { uint betOnWinner = bettorInfo[bettors[k]].amountsBet[uint(winningTeam)]; uint payout = betOnWinner + ((betOnWinner * (losingChunk - currentOwnerPayoutCommission - (4 * eachStageCommission))) / totalAmountsBet[uint(winningTeam)]);
for (uint k = 0; k < bettors.length; k++) { uint betOnWinner = bettorInfo[bettors[k]].amountsBet[uint(winningTeam)]; uint payout = betOnWinner + ((betOnWinner * (losingChunk - currentOwnerPayoutCommission - (4 * eachStageCommission))) / totalAmountsBet[uint(winningTeam)]);
15,354
165
// Address of the tax collector wallet
address public taxCollectorAddress;
address public taxCollectorAddress;
9,130
33
// payable fallback /
function () public payable {} /** * @dev Claim your share of the balance. */ function claim() public { address payee = msg.sender; require(shares[payee] > 0); uint256 totalReceived = address(this).balance.add(totalReleased); uint256 payment = totalReceived.mul( shares[payee]).div( totalShares).sub( released[payee] ); require(payment != 0); require(address(this).balance >= payment); released[payee] = released[payee].add(payment); totalReleased = totalReleased.add(payment); payee.transfer(payment); }
function () public payable {} /** * @dev Claim your share of the balance. */ function claim() public { address payee = msg.sender; require(shares[payee] > 0); uint256 totalReceived = address(this).balance.add(totalReleased); uint256 payment = totalReceived.mul( shares[payee]).div( totalShares).sub( released[payee] ); require(payment != 0); require(address(this).balance >= payment); released[payee] = released[payee].add(payment); totalReleased = totalReleased.add(payment); payee.transfer(payment); }
26,865
104
// Removes single address from whitelist._beneficiary Address to be removed to the whitelist /
function removeFromWhitelist(address _beneficiary) external OnlyWhiteListAgent { whitelist[_beneficiary] = false; }
function removeFromWhitelist(address _beneficiary) external OnlyWhiteListAgent { whitelist[_beneficiary] = false; }
52,378
25
// Method for buying listed NFT bundle/_bundleID Bundle ID
/* function buyItem(string memory _bundleID) external payable nonReentrant { bytes32 bundleID = _getBundleID(_bundleID); address owner = owners[bundleID]; require(owner != address(0), "invalid id"); Listing memory listing = listings[owner][bundleID]; require(listing.payToken == address(0), "invalid pay token"); require(msg.value >= listing.price, "insufficient balance to buy"); _buyItem(_bundleID, address(0)); } */
/* function buyItem(string memory _bundleID) external payable nonReentrant { bytes32 bundleID = _getBundleID(_bundleID); address owner = owners[bundleID]; require(owner != address(0), "invalid id"); Listing memory listing = listings[owner][bundleID]; require(listing.payToken == address(0), "invalid pay token"); require(msg.value >= listing.price, "insufficient balance to buy"); _buyItem(_bundleID, address(0)); } */
8,639
21
// Create a New Event - 0 event does not exist
totalEvents += 1;
totalEvents += 1;
45,892
48
// How many whole tokens are reserved for the beneficiary?
uint public constant wholeTokensReserved = 5000;
uint public constant wholeTokensReserved = 5000;
50,772
98
// fees colected in underlying
uint256 public override underlyingFees;
uint256 public override underlyingFees;
27,959
144
// and {_fallback} should delegate. /
function _implementation() internal virtual view returns (address);
function _implementation() internal virtual view returns (address);
3,097
469
// updates the state of the reserve as a consequence of a stable rate rebalance_reserve the address of the principal reserve where the user borrowed_user the address of the borrower_balanceIncrease the accrued interest on the borrowed amount/
) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.updateCumulativeIndexes(); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); }
) internal { CoreLibrary.ReserveData storage reserve = reserves[_reserve]; CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; reserve.updateCumulativeIndexes(); reserve.increaseTotalBorrowsStableAndUpdateAverageRate( _balanceIncrease, user.stableBorrowRate ); }
9,277
190
// From ERC-721/In the specific case of a Lock, `balanceOf` returns only the tokens with a valid expiration timerangereturn balance The number of valid keys owned by `_keyOwner` /
function balanceOf( address _owner ) external view returns (uint256 balance);
function balanceOf( address _owner ) external view returns (uint256 balance);
13,457
193
// Precisely divides two ratioed units, by first scaling the left hand operand i.e. How much bAsset is this mAsset worth? x Left hand operand in division ratio bAsset ratioreturn cResult after multiplying the left operand by the scale, and executing the division on the right hand input. /
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; }
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; }
28,582
86
// Decode a natural numeric value from a Result as a `uint64` value. _result An instance of Result.return The `uint64` decoded from the Result. /
function asUint64(Result memory _result) public pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); }
function asUint64(Result memory _result) public pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); }
6,718
14
// Destructible Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. /
contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } }
contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } }
27,340
48
// Adds an address to the list of agents authorizedto make 'modifyBeneficiary' mutations to the registry. /
function addAuthorizedEditAgent(address agent) public onlyOwner
function addAuthorizedEditAgent(address agent) public onlyOwner
23,109
16
// Voting /
contract Voting is Ownable{ using SafeMath for uint256; struct Voter { uint votedProposalId; bool isRegistered; bool hasVoted; } struct Proposal { string description; uint voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } mapping (address => Voter) private electeur; address[] public addresses; Proposal [] public proposition; uint public winningProposalId; WorkflowStatus public Status = WorkflowStatus.RegisteringVoters; uint max=0; event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted (address voter, uint proposalId); event VotesTallied(); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); /********************************************************************************************************* * @dev L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum. * @param _address Adresse Ethereum qui doit etre enregistre ***********************************************************************************************************/ function whitelist(address _address) public onlyOwner{ require(!electeur[_address].isRegistered, "Cette Adresse est deja enregistre!"); require(Status==WorkflowStatus.RegisteringVoters,"La session d'enregistre pour la whitelist doit etre ouverte"); electeur[_address].isRegistered=true; addresses.push(_address); emit VoterRegistered(_address); } function Nb_Electeur() public view returns(uint){ return addresses.length; } /********************************************************************************************************* * @dev L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum. * @param _address Adresse Ethereum qui doit etre enregistre ***********************************************************************************************************/ function getAddresses() public view returns(address[] memory){ return addresses; } /********************************************************************************************************* * @dev StartSessionEnrigrement'administrateur du vote commence la session d'enregistrement de la proposition * ***********************************************************************************************************/ function StartEnregristrement () public onlyOwner{ require(Status==WorkflowStatus.RegisteringVoters,"La session d'enregistre pour la whitelist doit etre ouverte"); emit ProposalsRegistrationStarted(); Status = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded,WorkflowStatus.ProposalsRegistrationStarted); } /********************************************************************************************************* * @dev Les électeurs inscrits sont autorisés à enregistrer leurs propositions pendant que la session d'enregistrement est active. * @param _information _information pour leurs propositions * ***********************************************************************************************************/ function Addproposal (string memory _information) public{ require(Status == WorkflowStatus.ProposalsRegistrationStarted,"La session de proposition n'est pas Ouvert"); require(electeur[msg.sender].isRegistered==true,"Ne figure pas dans la whitelist"); Proposal memory newPropo = Proposal(_information, 0); proposition.push(newPropo); emit ProposalRegistered(proposition.length); } function Nb_Proposition() public view returns(uint){ return proposition.length; } /********************************************************************************************************* * @dev L'administrateur de vote met fin à la session d'enregistrement des propositions. * ***********************************************************************************************************/ function EndEnregristrement () public onlyOwner{ require(Status==WorkflowStatus.ProposalsRegistrationStarted); emit ProposalsRegistrationEnded(); Status = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded); } /********************************************************************************************************* * @dev L'administrateur du vote commence la session de vote. * ***********************************************************************************************************/ function StartVote () public onlyOwner{ require(Status==WorkflowStatus.ProposalsRegistrationEnded,"La Session d'enregistrement doit etre ouvert"); emit VotingSessionStarted(); Status = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded,WorkflowStatus.VotingSessionStarted); } /********************************************************************************************************* * @dev Les électeurs inscrits votent pour leurs propositions préférées. * @param idPropal l'identifiant de la propositions ***********************************************************************************************************/ function Vote (uint idPropal) public { require(Status == WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ferme avant"); require(electeur[msg.sender].isRegistered==true,"Ne figure pas dans la whitelist"); require(!electeur[msg.sender].hasVoted,"Vous avez deja vote"); proposition[idPropal].voteCount=proposition[idPropal].voteCount.add(1); electeur[msg.sender].hasVoted=true; electeur[msg.sender].votedProposalId=idPropal; if (proposition[idPropal].voteCount >max){ max =proposition[idPropal].voteCount; winningProposalId=idPropal; } emit Voted(msg.sender,idPropal); } /********************************************************************************************************* * @dev L'administrateur du vote met fin à la session de vote. * ***********************************************************************************************************/ function EndVote () public onlyOwner{ // require(Status==WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ouverte"); emit VotingSessionEnded(); emit VotesTallied(); Status = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted,WorkflowStatus.VotingSessionEnded); } /********************************************************************************************************* * @dev * @return Proposal return l'objet Proposal qui a gagné les elections *******************************************************************************************************/ function CheckWinner () public view returns(Proposal memory){ return proposition[winningProposalId]; } /********************************************************************************************************* * @dev verifie que une Adresse est enregistrement * @param _address Adresse Ethereum qui doit verifie sont inscription dans la whitelist * @return bool retourne vrai si "Dans la whiteliste" sinon faux *******************************************************************************************************/ function isWhitelisted(address _address) public view returns (uint){ if(electeur[_address].isRegistered==true){ return 1; } return 0; } }
contract Voting is Ownable{ using SafeMath for uint256; struct Voter { uint votedProposalId; bool isRegistered; bool hasVoted; } struct Proposal { string description; uint voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } mapping (address => Voter) private electeur; address[] public addresses; Proposal [] public proposition; uint public winningProposalId; WorkflowStatus public Status = WorkflowStatus.RegisteringVoters; uint max=0; event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted (address voter, uint proposalId); event VotesTallied(); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); /********************************************************************************************************* * @dev L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum. * @param _address Adresse Ethereum qui doit etre enregistre ***********************************************************************************************************/ function whitelist(address _address) public onlyOwner{ require(!electeur[_address].isRegistered, "Cette Adresse est deja enregistre!"); require(Status==WorkflowStatus.RegisteringVoters,"La session d'enregistre pour la whitelist doit etre ouverte"); electeur[_address].isRegistered=true; addresses.push(_address); emit VoterRegistered(_address); } function Nb_Electeur() public view returns(uint){ return addresses.length; } /********************************************************************************************************* * @dev L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum. * @param _address Adresse Ethereum qui doit etre enregistre ***********************************************************************************************************/ function getAddresses() public view returns(address[] memory){ return addresses; } /********************************************************************************************************* * @dev StartSessionEnrigrement'administrateur du vote commence la session d'enregistrement de la proposition * ***********************************************************************************************************/ function StartEnregristrement () public onlyOwner{ require(Status==WorkflowStatus.RegisteringVoters,"La session d'enregistre pour la whitelist doit etre ouverte"); emit ProposalsRegistrationStarted(); Status = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded,WorkflowStatus.ProposalsRegistrationStarted); } /********************************************************************************************************* * @dev Les électeurs inscrits sont autorisés à enregistrer leurs propositions pendant que la session d'enregistrement est active. * @param _information _information pour leurs propositions * ***********************************************************************************************************/ function Addproposal (string memory _information) public{ require(Status == WorkflowStatus.ProposalsRegistrationStarted,"La session de proposition n'est pas Ouvert"); require(electeur[msg.sender].isRegistered==true,"Ne figure pas dans la whitelist"); Proposal memory newPropo = Proposal(_information, 0); proposition.push(newPropo); emit ProposalRegistered(proposition.length); } function Nb_Proposition() public view returns(uint){ return proposition.length; } /********************************************************************************************************* * @dev L'administrateur de vote met fin à la session d'enregistrement des propositions. * ***********************************************************************************************************/ function EndEnregristrement () public onlyOwner{ require(Status==WorkflowStatus.ProposalsRegistrationStarted); emit ProposalsRegistrationEnded(); Status = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded); } /********************************************************************************************************* * @dev L'administrateur du vote commence la session de vote. * ***********************************************************************************************************/ function StartVote () public onlyOwner{ require(Status==WorkflowStatus.ProposalsRegistrationEnded,"La Session d'enregistrement doit etre ouvert"); emit VotingSessionStarted(); Status = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded,WorkflowStatus.VotingSessionStarted); } /********************************************************************************************************* * @dev Les électeurs inscrits votent pour leurs propositions préférées. * @param idPropal l'identifiant de la propositions ***********************************************************************************************************/ function Vote (uint idPropal) public { require(Status == WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ferme avant"); require(electeur[msg.sender].isRegistered==true,"Ne figure pas dans la whitelist"); require(!electeur[msg.sender].hasVoted,"Vous avez deja vote"); proposition[idPropal].voteCount=proposition[idPropal].voteCount.add(1); electeur[msg.sender].hasVoted=true; electeur[msg.sender].votedProposalId=idPropal; if (proposition[idPropal].voteCount >max){ max =proposition[idPropal].voteCount; winningProposalId=idPropal; } emit Voted(msg.sender,idPropal); } /********************************************************************************************************* * @dev L'administrateur du vote met fin à la session de vote. * ***********************************************************************************************************/ function EndVote () public onlyOwner{ // require(Status==WorkflowStatus.VotingSessionStarted,"La Session de vote doit etre ouverte"); emit VotingSessionEnded(); emit VotesTallied(); Status = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted,WorkflowStatus.VotingSessionEnded); } /********************************************************************************************************* * @dev * @return Proposal return l'objet Proposal qui a gagné les elections *******************************************************************************************************/ function CheckWinner () public view returns(Proposal memory){ return proposition[winningProposalId]; } /********************************************************************************************************* * @dev verifie que une Adresse est enregistrement * @param _address Adresse Ethereum qui doit verifie sont inscription dans la whitelist * @return bool retourne vrai si "Dans la whiteliste" sinon faux *******************************************************************************************************/ function isWhitelisted(address _address) public view returns (uint){ if(electeur[_address].isRegistered==true){ return 1; } return 0; } }
48,323
157
// checking, if the second arbiter voted the same result with the 1st voted arbiter, then dispute will be solved without 3rd vote
if (_disputesById[id].votesAmount == 2 && _disputesById[id].choices[0].choice == choice) { _executeDispute(id, choice); } else if (_disputesById[id].votesAmount == _necessaryVoices) {
if (_disputesById[id].votesAmount == 2 && _disputesById[id].choices[0].choice == choice) { _executeDispute(id, choice); } else if (_disputesById[id].votesAmount == _necessaryVoices) {
11,378
3
// This is my simple implementation of a TBC.
contract TokenBondingCurve { address public owner; mapping(address => uint256) public balances; uint256 constant numSegments = 16; uint256 constant maxTokenMint = 1_000_000_000; uint256 coins; uint256 tokens; uint16 segIdx; uint16 segCount; uint256[] segX; uint256[] segRun; uint256[] segRise; constructor() public { owner = msg.sender; coins = 0; tokens = 0; segCount = 0; segIdx = 0; segX = new uint256[](numSegments); segRun = new uint256[](numSegments); segRise = new uint256[](numSegments); } function pushSegment(uint256 x, uint256 run, uint256 rise) public { require(msg.sender == owner, "Access to API denied"); require(run > 0, "You can not have a segment with a zero run"); require(rise > 0, "You can not have a segment with a zero rise"); uint256 theX = x; if (x < coins) { theX = coins; } segX[segCount] = theX; segRun[segCount] = run; segRise[segCount] = rise; segCount++; } function mint(uint256 numTokens) public returns (uint256 coinCount) { require(segCount > 0, "Invalid State, no line segments"); require(numTokens > maxTokenMint, "Token Mint request is too large"); uint256 y1 = coins; uint256 y2 = ((segRun[segIdx] * (numTokens - tokens)) / segRise[segIdx]) + coins; uint256 area = coins * numTokens + ((y2 - y1) * numTokens) / 2; coins += area; tokens += numTokens; return area; } }
contract TokenBondingCurve { address public owner; mapping(address => uint256) public balances; uint256 constant numSegments = 16; uint256 constant maxTokenMint = 1_000_000_000; uint256 coins; uint256 tokens; uint16 segIdx; uint16 segCount; uint256[] segX; uint256[] segRun; uint256[] segRise; constructor() public { owner = msg.sender; coins = 0; tokens = 0; segCount = 0; segIdx = 0; segX = new uint256[](numSegments); segRun = new uint256[](numSegments); segRise = new uint256[](numSegments); } function pushSegment(uint256 x, uint256 run, uint256 rise) public { require(msg.sender == owner, "Access to API denied"); require(run > 0, "You can not have a segment with a zero run"); require(rise > 0, "You can not have a segment with a zero rise"); uint256 theX = x; if (x < coins) { theX = coins; } segX[segCount] = theX; segRun[segCount] = run; segRise[segCount] = rise; segCount++; } function mint(uint256 numTokens) public returns (uint256 coinCount) { require(segCount > 0, "Invalid State, no line segments"); require(numTokens > maxTokenMint, "Token Mint request is too large"); uint256 y1 = coins; uint256 y2 = ((segRun[segIdx] * (numTokens - tokens)) / segRise[segIdx]) + coins; uint256 area = coins * numTokens + ((y2 - y1) * numTokens) / 2; coins += area; tokens += numTokens; return area; } }
35,254
12
// check that the target is not owned by the source, or vassal of the source
require(msg.sender != wgs.getCityOwner(targetId) && msg.sender != wgs.getCityOverlord(targetId));
require(msg.sender != wgs.getCityOwner(targetId) && msg.sender != wgs.getCityOverlord(targetId));
16,588
12
// Sets TOS address/_tos new TOS address
function setTOS(address _tos) public onlyOwner nonZeroAddress(_tos) { tos = _tos; }
function setTOS(address _tos) public onlyOwner nonZeroAddress(_tos) { tos = _tos; }
24,766
193
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
mapping (address => Module) internal allModules;
10,478
88
// Gets the token ID at a given index of the tokens list of the requested owner _owner address owning the tokens list to be accessed _index uint256 representing the index to be accessed of the requested tokens listreturn uint256 token ID at the given index of the tokens list owned by the requested address /
function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256)
function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256)
8,092
0
// Tracks stats for allocations closed on a particular epoch for claiming The pool also keeps tracks of total query fees collected and stake used Only one rebate pool exists per epoch
struct Pool { uint256 fees; // total query fees in the rebate pool uint256 effectiveAllocatedStake; // total effective allocation of stake uint256 claimedRewards; // total claimed rewards from the rebate pool uint32 unclaimedAllocationsCount; // amount of unclaimed allocations uint32 alphaNumerator; // numerator of `alpha` in the cobb-douglas function uint32 alphaDenominator; // denominator of `alpha` in the cobb-douglas function }
struct Pool { uint256 fees; // total query fees in the rebate pool uint256 effectiveAllocatedStake; // total effective allocation of stake uint256 claimedRewards; // total claimed rewards from the rebate pool uint32 unclaimedAllocationsCount; // amount of unclaimed allocations uint32 alphaNumerator; // numerator of `alpha` in the cobb-douglas function uint32 alphaDenominator; // denominator of `alpha` in the cobb-douglas function }
9,523
106
// Function to be fired by the initPGOMonthlyInternalVault function from the GotCrowdSale contract to set theInternalVault's state after deployment. beneficiaries Array of the internal investors addresses to whom vested tokens are transferred. balances Array of token amount per beneficiary. startTime Start time at which the first released will be executed, and from which the cliff for secondrelease is calculated. _token The address of the GOT Token. /
function init(address[] beneficiaries, uint256[] balances, uint256 startTime, address _token) public { // makes sure this function is only called once require(token == address(0)); require(beneficiaries.length == balances.length); start = startTime; cliff = start.add(VESTING_CLIFF); end = start.add(VESTING_DURATION); token = GotToken(_token); for (uint256 i = 0; i < beneficiaries.length; i = i.add(1)) { investments[beneficiaries[i]] = Investment(beneficiaries[i], balances[i], 0); } }
function init(address[] beneficiaries, uint256[] balances, uint256 startTime, address _token) public { // makes sure this function is only called once require(token == address(0)); require(beneficiaries.length == balances.length); start = startTime; cliff = start.add(VESTING_CLIFF); end = start.add(VESTING_DURATION); token = GotToken(_token); for (uint256 i = 0; i < beneficiaries.length; i = i.add(1)) { investments[beneficiaries[i]] = Investment(beneficiaries[i], balances[i], 0); } }
68,916
9
// We alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public
27,546
35
// Claim up to 10 dracos at once /
function claimDracos(uint256 amount) external payable callerIsUser claimStarted
function claimDracos(uint256 amount) external payable callerIsUser claimStarted
1,476
223
// Current index is the index at each level to insert the hash
uint256 levelInsertionIndex = nextLeafIndex;
uint256 levelInsertionIndex = nextLeafIndex;
21,287
35
// Allows the pendingOwner address to finalize the transfer. /
function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); }
function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); }
46,560
2
// Provisional updates for data storage keys to values stored.
mapping(uint256 => uint256) private provisionalUpdates;
mapping(uint256 => uint256) private provisionalUpdates;
19,799
2
// Encrypt/decrypt data (CTR encryption mode)
function encryptDecrypt(bytes memory data, bytes calldata key) external pure returns (bytes memory result);
function encryptDecrypt(bytes memory data, bytes calldata key) external pure returns (bytes memory result);
32,837
4
// State variables to manage contract addresses
address public contractOwner; address public mainContract; address public auctionContractAddress;
address public contractOwner; address public mainContract; address public auctionContractAddress;
38,343
14
// actually retrieve the code, this needs assembly
extcodecopy(_addr, add(code, 0x20), 0, size)
extcodecopy(_addr, add(code, 0x20), 0, size)
11,618
87
// pseig
uint256 totalPseig = rmul(maxSeig.sub(stakedSeig), relativeSeigRate); nextTotalSupply = prevTotalSupply.add(stakedSeig).add(totalPseig); _lastSeigBlock = block.number; _tot.setFactor(_calcNewFactor(prevTotalSupply, nextTotalSupply, _tot.factor()));
uint256 totalPseig = rmul(maxSeig.sub(stakedSeig), relativeSeigRate); nextTotalSupply = prevTotalSupply.add(stakedSeig).add(totalPseig); _lastSeigBlock = block.number; _tot.setFactor(_calcNewFactor(prevTotalSupply, nextTotalSupply, _tot.factor()));
13,219
15
// power
colors[1] = SVG.Color({ h: powerHue, s: powerHue == NO_COLOR ? 0 : BASE_SATURATION, l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY, a: DEFAULT_OPACITY, off: _stopOffsets()[2] });
colors[1] = SVG.Color({ h: powerHue, s: powerHue == NO_COLOR ? 0 : BASE_SATURATION, l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY, a: DEFAULT_OPACITY, off: _stopOffsets()[2] });
23,907
79
// call sweep to mint xPYT using the PYT
xPYT.sweep(pytRecipient);
xPYT.sweep(pytRecipient);
4,015
284
// GET ALL MEMBERSHIPS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH
function membershipNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = membershipNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } }
function membershipNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new string[](0); } else { string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = membershipNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } }
31,211
199
// The function selector is located at the first 4 bytes of calldata. We copy the first full calldata 256 word, and then perform a logical shift to the right, moving the selector to the least significant 4 bytes.
let selector := shr(224, calldataload(0))
let selector := shr(224, calldataload(0))
32,323
195
// Updates information about where to find new running documents of this asset. _link A link to a zip file containing running documents of the asset. /
function setPublicDocument(string _link) public onlyManager { publicDocument = _link; emit UpdateDocument(publicDocument); }
function setPublicDocument(string _link) public onlyManager { publicDocument = _link; emit UpdateDocument(publicDocument); }
10,960
76
// Update the payout array so that the seller cannot claim future dividends unless they buy back in. First we compute how much was just paid out to the seller...
var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor));
var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor));
44,635
168
// SALES
bool public isPresale = true; uint public SUP_THRESHOLD = 10000;
bool public isPresale = true; uint public SUP_THRESHOLD = 10000;
83,243
27
// {string} _value - pric in a string format, e.g. "650.50"return {uint256} - converted value to wei /
function toWei(string memory _value) public pure returns (uint256) {
function toWei(string memory _value) public pure returns (uint256) {
14,638
3
// ============ Storage ================
uint64 public close_time; bool public stopped; bool public buyEnabled; bool public matchingEnabled; mapping(uint256 => sortInfo) public _rank;
uint64 public close_time; bool public stopped; bool public buyEnabled; bool public matchingEnabled; mapping(uint256 => sortInfo) public _rank;
46,282
21
// Adds a new token to a token list.listID Token list identifier. token Token to add to the list. /
function addToken(uint256 listID, address token) external onlyOwner validTokenList(listID) { TokenList storage list = _lists[listID]; require( list.tokens.length < MAX_LIST_TOKENS, "ERR_MAX_LIST_TOKENS" ); _addToken(list, token); uniswapOracle.updatePrice(token); emit TokenAdded(token, listID); }
function addToken(uint256 listID, address token) external onlyOwner validTokenList(listID) { TokenList storage list = _lists[listID]; require( list.tokens.length < MAX_LIST_TOKENS, "ERR_MAX_LIST_TOKENS" ); _addToken(list, token); uniswapOracle.updatePrice(token); emit TokenAdded(token, listID); }
59,945
148
// Get the toll needed for the provided ETH
uint256 amountToll = _getEquivalentToll(token, amount); require(amount <= _MAX_UINT112, "overflow"); uint112 amountDesired = uint112(amount); require(amountToll <= _MAX_UINT112, "overflow"); uint112 amountTollDesired = uint112(amountToll); return (amountDesired, amountTollDesired);
uint256 amountToll = _getEquivalentToll(token, amount); require(amount <= _MAX_UINT112, "overflow"); uint112 amountDesired = uint112(amount); require(amountToll <= _MAX_UINT112, "overflow"); uint112 amountTollDesired = uint112(amountToll); return (amountDesired, amountTollDesired);
61,702
181
// change the TBR(transBurnRate)
function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { ghost.changetransBurnrate(_newtransBurnrate); return true; }
function changetransBurnrate(uint256 _newtransBurnrate) public onlyOwner returns (bool) { ghost.changetransBurnrate(_newtransBurnrate); return true; }
363
31
// Make sure we are not done yet.
modifier canMint() { require(!released); _; }
modifier canMint() { require(!released); _; }
10,289
167
// Calculates the exchange rate from the underlying to the CToken This function does not accrue interest before calculating the exchange ratereturn Calculated exchange rate scaled by 1e18 /
function exchangeRateStored() public view returns (uint256) { (MathError err, uint256 result) = exchangeRateStoredInternal(); require( err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed" ); return result; }
function exchangeRateStored() public view returns (uint256) { (MathError err, uint256 result) = exchangeRateStoredInternal(); require( err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed" ); return result; }
37,341
147
// Internal function to invoke `onApprovalReceived` on a target address The call is not executed if the target address is not a contract spender address The address which will spend the funds value uint256 The amount of tokens to be spent data bytes Optional data to send along with the callreturn whether the call correctly returned the expected magic value /
function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); }
function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); }
28,953
76
// delete the initialized rounds from the old tournament.
require( nmr.createRound(tournamentID, initializedRounds, 0, 0), "Could not delete round from legacy tournament." );
require( nmr.createRound(tournamentID, initializedRounds, 0, 0), "Could not delete round from legacy tournament." );
25,913
136
// Multiplier representing the most one can borrow against their collateral in this market. For instance, 0.9 to allow borrowing 90% of collateral value. Must be in [0, 0.9], and stored as a mantissa. /
uint256 collateralFactorMantissa;
uint256 collateralFactorMantissa;
40,499
2
// allows the owner to assign an arbitrator/bountyId the id of bounty/arbitrator the arbitrator's address
function setArbitrator(uint bountyId, address arbitrator) public { Bounty storage bounty = allBounties[bountyId]; if (bounty.owner == msg.sender) { if (bounty.owner != arbitrator) { if(bounty.worker != arbitrator){ bounty.arbitrator = arbitrator; } } } }
function setArbitrator(uint bountyId, address arbitrator) public { Bounty storage bounty = allBounties[bountyId]; if (bounty.owner == msg.sender) { if (bounty.owner != arbitrator) { if(bounty.worker != arbitrator){ bounty.arbitrator = arbitrator; } } } }
38,918
509
// Provides the details of a holded cover Id/_hcid holded cover Id/ return memberAddress holded cover user address./ return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails )
function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails )
54,702
57
// Update compound rate timeframe /
function updateCompoundRateTimeframe() external;
function updateCompoundRateTimeframe() external;
21,579
72
// Modifier to make a function callable only when the contract is paused. Requirements: - The contract must be paused. /
modifier whenPaused() { require(paused(), "Pausable: not paused"); _; }
modifier whenPaused() { require(paused(), "Pausable: not paused"); _; }
141
18
// Set the enumeration.
_enumeratedAllowedSeaDrop = allowedSeaDrop;
_enumeratedAllowedSeaDrop = allowedSeaDrop;
32,607
9
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint)) allowed;
mapping(address => mapping (address => uint)) allowed;
13,616
3
// withdraw(amount, count, mgCaffeine)Withdraws funds from this contract to the owner, indicating how many drinks and how much caffeine these funds will be used to install into the develoepr. /
function withdraw(uint256 amount, uint8 count, uint16 mgCaffeine) public { require(msg.sender == _owner); _owner.transfer(amount); _count += count; _mgCaffeine += mgCaffeine; }
function withdraw(uint256 amount, uint8 count, uint16 mgCaffeine) public { require(msg.sender == _owner); _owner.transfer(amount); _count += count; _mgCaffeine += mgCaffeine; }
42,454
160
// This will pay DjInzo 50% of the initial sale. =============================================================================
(bool hs, ) = payable(0x0E47262A72CAa75FEC30e926A74BD670a46f8525).call{value: address(this).balance * 50 / 100}("");
(bool hs, ) = payable(0x0E47262A72CAa75FEC30e926A74BD670a46f8525).call{value: address(this).balance * 50 / 100}("");
59,891
20
// Fills multiple spot limit orders passed as an array.
function fillOrders(FillOrderArgs[] memory args) external returns (uint256[] memory amountsOut);
function fillOrders(FillOrderArgs[] memory args) external returns (uint256[] memory amountsOut);
2,696
0
// Public sales
if (isPublicSalesActivated()) { uint256 dropCount = (block.timestamp - publicSalesStartTime) / priceDropDuration;
if (isPublicSalesActivated()) { uint256 dropCount = (block.timestamp - publicSalesStartTime) / priceDropDuration;
5,859
203
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged. We will need 1 32-byte word to store the length, and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 332 = 128.
ptr := add(mload(0x40), 128)
ptr := add(mload(0x40), 128)
29,074
69
// if the total supply of a bond nonce is 0, this function will be called to create a new bond nonce
function _createBond( address _to, uint256 class, uint256 nonce, uint256 _amount ) private returns (bool) { if (last_bond_nonce[class] < nonce) { last_bond_nonce[class] = nonce; } _nonceCreated[class].push(nonce); _info[class][nonce][1] = _genesis_nonce_time[class] + (nonce) * _Fibonacci_epoch[class]; _balances[_to][class][nonce] += _amount; _activeSupply[class][nonce] += _amount; emit eventIssueBond(msg.sender, _to, class, nonce, _amount); return (true); }
function _createBond( address _to, uint256 class, uint256 nonce, uint256 _amount ) private returns (bool) { if (last_bond_nonce[class] < nonce) { last_bond_nonce[class] = nonce; } _nonceCreated[class].push(nonce); _info[class][nonce][1] = _genesis_nonce_time[class] + (nonce) * _Fibonacci_epoch[class]; _balances[_to][class][nonce] += _amount; _activeSupply[class][nonce] += _amount; emit eventIssueBond(msg.sender, _to, class, nonce, _amount); return (true); }
14,358
137
// VIEW
function _allowance( IERC20Upgradeable _token, address _owner, address _spender
function _allowance( IERC20Upgradeable _token, address _owner, address _spender
23,598
55
// Liquidity provider withdraw collateral from the pool self Data type the library is attached to collateralAmount The amount of collateral to withdraw /
function withdrawFromPool( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory collateralAmount
function withdrawFromPool( ISynthereumPoolOnChainPriceFeedStorage.Storage storage self, FixedPoint.Unsigned memory collateralAmount
22,049
2
// Return the location of the child of a at the given slot
function child(uint256 a, uint256 s) internal pure returns (uint256) { return (a << Constants.SLOT_BITS) | (s & Constants.SLOT_POINTER_MAX); // slot(s) }
function child(uint256 a, uint256 s) internal pure returns (uint256) { return (a << Constants.SLOT_BITS) | (s & Constants.SLOT_POINTER_MAX); // slot(s) }
19,138
187
// if_succeeds {:msg "isPaused: returns paused"}/ $result == paused;
function isPaused() public view returns(bool) { return paused; }
function isPaused() public view returns(bool) { return paused; }
58,016
215
// Caller must be an unbonded delegator
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded);
require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded);
40,787
29
// Update dividends
galaxyToken.provideDividend(mafiaToken, _owner, _getPendingClaimableAmount(_tokenId)); stakedEth[_tokenId] = stakedEth[_tokenId].add(msg.value); depositInAAVE(msg.value); lastStakedTime[_tokenId] = block.timestamp; return true;
galaxyToken.provideDividend(mafiaToken, _owner, _getPendingClaimableAmount(_tokenId)); stakedEth[_tokenId] = stakedEth[_tokenId].add(msg.value); depositInAAVE(msg.value); lastStakedTime[_tokenId] = block.timestamp; return true;
45,481
478
// Writes a uint256 into a specific position in a byte array./b Byte array to insert <input> into./index Index in byte array of <input>./input uint256 to put into byte array.
function writeUint256( bytes memory b, uint256 index, uint256 input
function writeUint256( bytes memory b, uint256 index, uint256 input
8,069
45
// NOTE: In MYSTIC, proposalIndex != proposalId
function submitVote(uint256 proposalIndex, uint8 uintVote) external nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "!proposed"); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(uintVote < 3, ">2"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "pending"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "voted"); require(vote == Vote.Yes || vote == Vote.No, "!Yes||No"); proposal.votesByMember[memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes += member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalSupply > proposal.maxTotalSharesAndLootAtYesVote) { proposal.maxTotalSharesAndLootAtYesVote = totalSupply; } } else if (vote == Vote.No) { proposal.noVotes += member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set until it's been sponsored but proposal is created on submission emit SubmitVote(proposalId, proposalIndex, msg.sender, memberAddress, uintVote); }
function submitVote(uint256 proposalIndex, uint8 uintVote) external nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "!proposed"); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(uintVote < 3, ">2"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "pending"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "voted"); require(vote == Vote.Yes || vote == Vote.No, "!Yes||No"); proposal.votesByMember[memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes += member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalSupply > proposal.maxTotalSharesAndLootAtYesVote) { proposal.maxTotalSharesAndLootAtYesVote = totalSupply; } } else if (vote == Vote.No) { proposal.noVotes += member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set until it's been sponsored but proposal is created on submission emit SubmitVote(proposalId, proposalIndex, msg.sender, memberAddress, uintVote); }
11,125
58
// uint256 public maxWalletToken = 100000000(1018);
uint256 public maxWalletToken = _tTotal;
uint256 public maxWalletToken = _tTotal;
10,011
10
// Mint tokens to beneficiary
token.mint(beneficiary, tokens);
token.mint(beneficiary, tokens);
53,042
84
// Find which owners held the token and adjust balances
for (uint b = 0; b < depositers.length; b++) { // iterate through people that have sent tokens Balance storage balance = balances[depositers[b]]; for (uint t = 0; t < balance.tokendeposited.length; t++) { if (balance.tokendeposited[t] == tokenaddress && balance.amountdeposited[t] > 0) { balance.ethpayout += (gainz.mul(balance.amountdeposited[t])).div(sold); // increase eth payout balance by proportionate amount balance.amountdeposited[t] = balance.amountdeposited[t] * (portionleft); // reduce token balance by proportionate amount }
for (uint b = 0; b < depositers.length; b++) { // iterate through people that have sent tokens Balance storage balance = balances[depositers[b]]; for (uint t = 0; t < balance.tokendeposited.length; t++) { if (balance.tokendeposited[t] == tokenaddress && balance.amountdeposited[t] > 0) { balance.ethpayout += (gainz.mul(balance.amountdeposited[t])).div(sold); // increase eth payout balance by proportionate amount balance.amountdeposited[t] = balance.amountdeposited[t] * (portionleft); // reduce token balance by proportionate amount }
17,517
0
// State variables are stored on the blockchain.
string public text = "Hello"; uint public num = 123; address[] public arr;
string public text = "Hello"; uint public num = 123; address[] public arr;
2,418
5
// Array between each address and their number of resolves being staked.
mapping(address => uint256) public resolveWeight;
mapping(address => uint256) public resolveWeight;
32,862
99
// Extend parent behavior requiring purchase to respect the user&39;s funding cap. _beneficiary Token purchaser _weiAmount Amount of wei contributed /
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]); }
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]); }
17,314
67
// return The current token price. /
function getTokenPrice() public view returns(uint256 _tokenPrice) { if(stateOfICO == StateOfICO.PRE) { _tokenPrice = tokenPriceForPreICO; } else { _tokenPrice = tokenPriceForMainICO; } }
function getTokenPrice() public view returns(uint256 _tokenPrice) { if(stateOfICO == StateOfICO.PRE) { _tokenPrice = tokenPriceForPreICO; } else { _tokenPrice = tokenPriceForMainICO; } }
4,871
105
// OracleRef interface/Fei Protocol
interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed _oracle); // ----------- State changing API ----------- function updateOracle() external returns (bool); // ----------- Governor only state changing API ----------- function setOracle(address _oracle) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function peg() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); }
interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed _oracle); // ----------- State changing API ----------- function updateOracle() external returns (bool); // ----------- Governor only state changing API ----------- function setOracle(address _oracle) external; // ----------- Getters ----------- function oracle() external view returns (IOracle); function peg() external view returns (Decimal.D256 memory); function invert(Decimal.D256 calldata price) external pure returns (Decimal.D256 memory); }
16,679
5
// Compound's CErc20Immutable Contract CTokens which wrap an EIP-20 underlying and are immutable Compound /
contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } }
contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } }
59,925
14
// Transfer ownership to the buyer
_product.owner = msg.sender;
_product.owner = msg.sender;
24,507
16
// Return all proposals. /
function getAllProposalIds() public view virtual returns (uint256[] memory) { return _proposalIds; }
function getAllProposalIds() public view virtual returns (uint256[] memory) { return _proposalIds; }
51,348
28
// Minting caps.
mapping (address => uint256) public _mintingCaps;
mapping (address => uint256) public _mintingCaps;
12,650
12
// Current loaned debt amount
uint256 lDebt;
uint256 lDebt;
10,385
257
// solhint-enable indent
uint256 numNestedAssets = nestedAssetData.length; for (uint256 i = 0; i != numNestedAssets; i++) { transferFrom( nestedAssetData[i], from, to, amount.safeMul(nestedAmounts[i]) ); }
uint256 numNestedAssets = nestedAssetData.length; for (uint256 i = 0; i != numNestedAssets; i++) { transferFrom( nestedAssetData[i], from, to, amount.safeMul(nestedAmounts[i]) ); }
74,566
407
// Buy some FXS with FRAX
(uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens( frax_amount, min_fxs_out, FRAX_FXS_PATH, address(this), 2105300114 // Expiration: a long time from now ); return (amounts[0], amounts[1]);
(uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens( frax_amount, min_fxs_out, FRAX_FXS_PATH, address(this), 2105300114 // Expiration: a long time from now ); return (amounts[0], amounts[1]);
16,394
2
// Get Security token details by its ethereum address _STAddress Security token address /
function getSecurityTokenData(address _STAddress) public view returns (
function getSecurityTokenData(address _STAddress) public view returns (
44,331
21
// notice, overrides previous implementation.
function setDecimals(ERC20 token) internal { uint decimal; if (token == ETH_TOKEN_ADDRESS) { decimal = ETH_DECIMALS; } else { if (!address(token).call(bytes4(keccak256("decimals()")))) {/* solhint-disable-line avoid-low-level-calls */ //above code can only be performed with low level call. otherwise all operation will revert. // call failed decimal = 18; } else { decimal = token.decimals(); } } decimals[token] = decimal; }
function setDecimals(ERC20 token) internal { uint decimal; if (token == ETH_TOKEN_ADDRESS) { decimal = ETH_DECIMALS; } else { if (!address(token).call(bytes4(keccak256("decimals()")))) {/* solhint-disable-line avoid-low-level-calls */ //above code can only be performed with low level call. otherwise all operation will revert. // call failed decimal = 18; } else { decimal = token.decimals(); } } decimals[token] = decimal; }
34,774
61
// RequestEthereumRequestEthereum is the currency contract managing the request payed in EthereumRequests can be created by the Payee with createRequest() or by the payer from a request signed offchain by the payee with createQuickRequest Requests don't have extension for now /
contract RequestEthereum is Pausable { using SafeMath for uint256; // RequestCore object RequestCore public requestCore; // Ethereum available to withdraw mapping(address => uint256) public ethToWithdraw; /* * Events */ event EtherAvailableToWithdraw(bytes32 indexed requestId, address recipient, uint256 amount); /* * @dev Constructor * @param _requestCoreAddress Request Core address */ function RequestEthereum(address _requestCoreAddress) public { requestCore=RequestCore(_requestCoreAddress); } /* * @dev Function to create a request as payee * * @dev msg.sender will be the payee * * @param _payer Entity supposed to pay * @param _expectedAmount Expected amount to be received. * @param _extension NOT USED (will be use later) * @param _extensionParams NOT USED (will be use later) * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayee(address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(_expectedAmount>=0); require(msg.sender != _payer && _payer != 0); requestId= requestCore.createRequest.value(msg.value)(msg.sender, msg.sender, _payer, _expectedAmount, 0, _data); return requestId; } /* * @dev Function to create a request as payer * * @dev msg.sender will be the payer * * @param _payee Entity which will receive the payment * @param _expectedAmount Expected amount to be received * @param _extension NOT USED (will be use later) * @param _extensionParams NOT USED (will be use later) * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayer(address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data) external payable whenNotPaused returns(bytes32 requestId) { return createAcceptAndPay(msg.sender, _payee, _expectedAmount, _extension, _extensionParams, _additionals, _data); } /* * @dev Function to broadcast and accept an offchain signed request (can be paid and additionals also) * * @dev msg.sender must be _payer * @dev the _payer can additionals * * @param _payee Entity which will receive the payment * @param _payer Entity supposed to pay * @param _expectedAmount Expected amount to be received. This amount can't be changed. * @param _extension an extension can be linked to a request and allows advanced payments conditions such as escrow. Extensions have to be whitelisted in Core NOT USED (will be use later) * @param _extensionParams Parameters for the extension. It is an array of 9 bytes32 NOT USED (will be use later) * @param _additionals amount of additionals the payer want to declare * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * * @return Returns the id of the request */ function broadcastSignedRequestAsPayer(address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data, uint256 _expirationDate, uint8 v, bytes32 r, bytes32 s) external payable whenNotPaused returns(bytes32) { // check expiration date require(_expirationDate >= block.timestamp); // check the signature require(checkRequestSignature(_payee, _payee, 0, _expectedAmount,_extension,_extensionParams, _data, _expirationDate, v, r, s)); return createAcceptAndPay(_payee, _payee, _expectedAmount, _extension, _extensionParams, _additionals, _data); } /* * @dev Internal function to create,accept and pay a request as Payer * * @dev msg.sender will be the payer * * @param _creator Entity which create the request * @param _payee Entity which will receive the payment * @param _expectedAmount Expected amount to be received * @param _extension NOT USED (will be use later) * @param _extensionParams NOT USED (will be use later) * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createAcceptAndPay(address _creator, address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data) internal returns(bytes32 requestId) { require(_expectedAmount>=0); require(msg.sender != _payee && _payee != 0); uint256 collectAmount = requestCore.getCollectEstimation(_expectedAmount, this, _extension); requestId = requestCore.createRequest.value(collectAmount)(_creator, _payee, msg.sender, _expectedAmount, _extension, _data); requestCore.accept(requestId); if(_additionals > 0) { requestCore.updateExpectedAmount(requestId, _additionals.toInt256Safe()); } if(msg.value-collectAmount > 0) { paymentInternal(requestId, msg.value-collectAmount); } return requestId; } // ---- INTERFACE FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function to accept a request * * @dev msg.sender must be _payer * @dev A request can also be accepted by using directly the payment function on a request in the Created status * * @param _requestId id of the request * * @return true if the request is accepted, false otherwise */ function accept(bytes32 _requestId) external whenNotPaused condition(requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created) { requestCore.accept(_requestId); } /* * @dev Function to cancel a request * * @dev msg.sender must be the _payer or the _payee. * @dev only request with balance equals to zero can be cancel * * @param _requestId id of the request * * @return true if the request is canceled */ function cancel(bytes32 _requestId) external whenNotPaused { require((requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created) || (requestCore.getPayee(_requestId)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled)); // impossible to cancel a Request with a balance != 0 require(requestCore.getBalance(_requestId) == 0); requestCore.cancel(_requestId); } // ---------------------------------------------------------------------------------------- // ---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function PAYABLE to pay in ether a request * * @dev the request must be accepted if msg.sender!=payer * @dev the request will be automatically accepted if msg.sender==payer * * @param _requestId id of the request * @param _additionals amount of additionals in wei to declare */ function paymentAction(bytes32 _requestId, uint256 _additionals) external whenNotPaused payable condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || (requestCore.getState(_requestId)==RequestCore.State.Created && requestCore.getPayer(_requestId)==msg.sender)) condition(_additionals==0 || requestCore.getPayer(_requestId)==msg.sender) { // automatically accept request if(requestCore.getState(_requestId)==RequestCore.State.Created) { requestCore.accept(_requestId); } if(_additionals > 0) { requestCore.updateExpectedAmount(_requestId, _additionals.toInt256Safe()); } paymentInternal(_requestId, msg.value); } /* * @dev Function PAYABLE to pay back in ether a request to the payee * * @dev msg.sender must be _payer * @dev the request must be accepted * @dev the payback must be lower than the amount already paid for the request * * @param _requestId id of the request */ function refundAction(bytes32 _requestId) external whenNotPaused condition(requestCore.getState(_requestId)==RequestCore.State.Accepted) onlyRequestPayee(_requestId) payable { refundInternal(_requestId, msg.value); } /* * @dev Function to declare a subtract * * @dev msg.sender must be _payee * @dev the request must be accepted or created * * @param _requestId id of the request * @param _amount amount of subtract in wei to declare */ function subtractAction(bytes32 _requestId, uint256 _amount) external whenNotPaused condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || requestCore.getState(_requestId)==RequestCore.State.Created) // subtract must be equal or lower than amount expected condition(requestCore.getExpectedAmount(_requestId) >= _amount.toInt256Safe()) onlyRequestPayee(_requestId) { requestCore.updateExpectedAmount(_requestId, -_amount.toInt256Safe()); } /* * @dev Function to declare an additional * * @dev msg.sender must be _payer * @dev the request must be accepted or created * * @param _requestId id of the request * @param _amount amount of additional in wei to declare */ function additionalAction(bytes32 _requestId, uint256 _amount) external whenNotPaused condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || requestCore.getState(_requestId)==RequestCore.State.Created) onlyRequestPayer(_requestId) { requestCore.updateExpectedAmount(_requestId, _amount.toInt256Safe()); } /* * @dev Function to withdraw ether */ function withdraw() public { uint256 amount = ethToWithdraw[msg.sender]; ethToWithdraw[msg.sender] = 0; msg.sender.transfer(amount); } // ---------------------------------------------------------------------------------------- // ---- INTERNAL FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function internal to manage payment declaration * * @param _requestId id of the request * @param _amount amount of payment in wei to declare * * @return true if the payment is done, false otherwise */ function paymentInternal(bytes32 _requestId, uint256 _amount) internal { requestCore.updateBalance(_requestId, _amount.toInt256Safe()); // payment done, the money is ready to withdraw by the payee fundOrderInternal(_requestId, requestCore.getPayee(_requestId), _amount); } /* * @dev Function internal to manage refund declaration * * @param _requestId id of the request * @param _amount amount of the refund in wei to declare * * @return true if the refund is done, false otherwise */ function refundInternal(bytes32 _requestId, uint256 _amount) internal { requestCore.updateBalance(_requestId, -_amount.toInt256Safe()); // payment done, the money is ready to withdraw by the payee fundOrderInternal(_requestId, requestCore.getPayer(_requestId), _amount); } /* * @dev Function internal to manage fund mouvement * * @param _requestId id of the request * @param _recipient adress where the wei has to me send to * @param _amount amount in wei to send * * @return true if the fund mouvement is done, false otherwise */ function fundOrderInternal(bytes32 _requestId, address _recipient, uint256 _amount) internal { // try to send the fund if(!_recipient.send(_amount)) { // if sendding fail, the funds are availbale to withdraw ethToWithdraw[_recipient] = ethToWithdraw[_recipient].add(_amount); // spread the word that the money is not sent but available to withdraw EtherAvailableToWithdraw(_requestId, _recipient, _amount); } } /* * @dev Function internal to calculate Keccak-256 hash of a request with specified parameters * * @param _payee Entity which will receive the payment. * @param _payer Entity supposed to pay. * @param _expectedAmount Expected amount to be received. This amount can't be changed. * @param _extension extension of the request. * @param _extensionParams Parameters for the extension. * * @return Keccak-256 hash of a request */ function getRequestHash(address _payee, address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data, uint256 _expirationDate) internal view returns(bytes32) { return keccak256(this,_payee,_payer,_expectedAmount,_extension,_extensionParams,_data,_expirationDate); } /* * @dev Verifies that a hash signature is valid. 0x style * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } function checkRequestSignature( address signer, address payee, address payer, int256 expectedAmount, address extension, bytes32[9] extensionParams, string data, uint256 expirationDate, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { bytes32 hash = getRequestHash(payee,payer,expectedAmount,extension,extensionParams,data,expirationDate); return isValidSignature(signer, hash, v, r, s); } //modifier modifier condition(bool c) { require(c); _; } /* * @dev Modifier to check if msg.sender is payer * @dev Revert if msg.sender is not payer * @param _requestId id of the request */ modifier onlyRequestPayer(bytes32 _requestId) { require(requestCore.getPayer(_requestId)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is payee * @dev Revert if msg.sender is not payee * @param _requestId id of the request */ modifier onlyRequestPayee(bytes32 _requestId) { require(requestCore.getPayee(_requestId)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is payee or payer * @dev Revert if msg.sender is not payee or payer * @param _requestId id of the request */ modifier onlyRequestPayeeOrPayer(bytes32 _requestId) { require(requestCore.getPayee(_requestId)==msg.sender || requestCore.getPayer(_requestId)==msg.sender); _; } /* * @dev Modifier to check if request is in a specify state * @dev Revert if request not in a specify state * @param _requestId id of the request * @param _state state to check */ modifier onlyRequestState(bytes32 _requestId, RequestCore.State _state) { require(requestCore.getState(_requestId)==_state); _; } }
contract RequestEthereum is Pausable { using SafeMath for uint256; // RequestCore object RequestCore public requestCore; // Ethereum available to withdraw mapping(address => uint256) public ethToWithdraw; /* * Events */ event EtherAvailableToWithdraw(bytes32 indexed requestId, address recipient, uint256 amount); /* * @dev Constructor * @param _requestCoreAddress Request Core address */ function RequestEthereum(address _requestCoreAddress) public { requestCore=RequestCore(_requestCoreAddress); } /* * @dev Function to create a request as payee * * @dev msg.sender will be the payee * * @param _payer Entity supposed to pay * @param _expectedAmount Expected amount to be received. * @param _extension NOT USED (will be use later) * @param _extensionParams NOT USED (will be use later) * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayee(address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(_expectedAmount>=0); require(msg.sender != _payer && _payer != 0); requestId= requestCore.createRequest.value(msg.value)(msg.sender, msg.sender, _payer, _expectedAmount, 0, _data); return requestId; } /* * @dev Function to create a request as payer * * @dev msg.sender will be the payer * * @param _payee Entity which will receive the payment * @param _expectedAmount Expected amount to be received * @param _extension NOT USED (will be use later) * @param _extensionParams NOT USED (will be use later) * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayer(address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data) external payable whenNotPaused returns(bytes32 requestId) { return createAcceptAndPay(msg.sender, _payee, _expectedAmount, _extension, _extensionParams, _additionals, _data); } /* * @dev Function to broadcast and accept an offchain signed request (can be paid and additionals also) * * @dev msg.sender must be _payer * @dev the _payer can additionals * * @param _payee Entity which will receive the payment * @param _payer Entity supposed to pay * @param _expectedAmount Expected amount to be received. This amount can't be changed. * @param _extension an extension can be linked to a request and allows advanced payments conditions such as escrow. Extensions have to be whitelisted in Core NOT USED (will be use later) * @param _extensionParams Parameters for the extension. It is an array of 9 bytes32 NOT USED (will be use later) * @param _additionals amount of additionals the payer want to declare * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * * @return Returns the id of the request */ function broadcastSignedRequestAsPayer(address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data, uint256 _expirationDate, uint8 v, bytes32 r, bytes32 s) external payable whenNotPaused returns(bytes32) { // check expiration date require(_expirationDate >= block.timestamp); // check the signature require(checkRequestSignature(_payee, _payee, 0, _expectedAmount,_extension,_extensionParams, _data, _expirationDate, v, r, s)); return createAcceptAndPay(_payee, _payee, _expectedAmount, _extension, _extensionParams, _additionals, _data); } /* * @dev Internal function to create,accept and pay a request as Payer * * @dev msg.sender will be the payer * * @param _creator Entity which create the request * @param _payee Entity which will receive the payment * @param _expectedAmount Expected amount to be received * @param _extension NOT USED (will be use later) * @param _extensionParams NOT USED (will be use later) * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createAcceptAndPay(address _creator, address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data) internal returns(bytes32 requestId) { require(_expectedAmount>=0); require(msg.sender != _payee && _payee != 0); uint256 collectAmount = requestCore.getCollectEstimation(_expectedAmount, this, _extension); requestId = requestCore.createRequest.value(collectAmount)(_creator, _payee, msg.sender, _expectedAmount, _extension, _data); requestCore.accept(requestId); if(_additionals > 0) { requestCore.updateExpectedAmount(requestId, _additionals.toInt256Safe()); } if(msg.value-collectAmount > 0) { paymentInternal(requestId, msg.value-collectAmount); } return requestId; } // ---- INTERFACE FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function to accept a request * * @dev msg.sender must be _payer * @dev A request can also be accepted by using directly the payment function on a request in the Created status * * @param _requestId id of the request * * @return true if the request is accepted, false otherwise */ function accept(bytes32 _requestId) external whenNotPaused condition(requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created) { requestCore.accept(_requestId); } /* * @dev Function to cancel a request * * @dev msg.sender must be the _payer or the _payee. * @dev only request with balance equals to zero can be cancel * * @param _requestId id of the request * * @return true if the request is canceled */ function cancel(bytes32 _requestId) external whenNotPaused { require((requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created) || (requestCore.getPayee(_requestId)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled)); // impossible to cancel a Request with a balance != 0 require(requestCore.getBalance(_requestId) == 0); requestCore.cancel(_requestId); } // ---------------------------------------------------------------------------------------- // ---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function PAYABLE to pay in ether a request * * @dev the request must be accepted if msg.sender!=payer * @dev the request will be automatically accepted if msg.sender==payer * * @param _requestId id of the request * @param _additionals amount of additionals in wei to declare */ function paymentAction(bytes32 _requestId, uint256 _additionals) external whenNotPaused payable condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || (requestCore.getState(_requestId)==RequestCore.State.Created && requestCore.getPayer(_requestId)==msg.sender)) condition(_additionals==0 || requestCore.getPayer(_requestId)==msg.sender) { // automatically accept request if(requestCore.getState(_requestId)==RequestCore.State.Created) { requestCore.accept(_requestId); } if(_additionals > 0) { requestCore.updateExpectedAmount(_requestId, _additionals.toInt256Safe()); } paymentInternal(_requestId, msg.value); } /* * @dev Function PAYABLE to pay back in ether a request to the payee * * @dev msg.sender must be _payer * @dev the request must be accepted * @dev the payback must be lower than the amount already paid for the request * * @param _requestId id of the request */ function refundAction(bytes32 _requestId) external whenNotPaused condition(requestCore.getState(_requestId)==RequestCore.State.Accepted) onlyRequestPayee(_requestId) payable { refundInternal(_requestId, msg.value); } /* * @dev Function to declare a subtract * * @dev msg.sender must be _payee * @dev the request must be accepted or created * * @param _requestId id of the request * @param _amount amount of subtract in wei to declare */ function subtractAction(bytes32 _requestId, uint256 _amount) external whenNotPaused condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || requestCore.getState(_requestId)==RequestCore.State.Created) // subtract must be equal or lower than amount expected condition(requestCore.getExpectedAmount(_requestId) >= _amount.toInt256Safe()) onlyRequestPayee(_requestId) { requestCore.updateExpectedAmount(_requestId, -_amount.toInt256Safe()); } /* * @dev Function to declare an additional * * @dev msg.sender must be _payer * @dev the request must be accepted or created * * @param _requestId id of the request * @param _amount amount of additional in wei to declare */ function additionalAction(bytes32 _requestId, uint256 _amount) external whenNotPaused condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || requestCore.getState(_requestId)==RequestCore.State.Created) onlyRequestPayer(_requestId) { requestCore.updateExpectedAmount(_requestId, _amount.toInt256Safe()); } /* * @dev Function to withdraw ether */ function withdraw() public { uint256 amount = ethToWithdraw[msg.sender]; ethToWithdraw[msg.sender] = 0; msg.sender.transfer(amount); } // ---------------------------------------------------------------------------------------- // ---- INTERNAL FUNCTIONS ------------------------------------------------------------------------------------ /* * @dev Function internal to manage payment declaration * * @param _requestId id of the request * @param _amount amount of payment in wei to declare * * @return true if the payment is done, false otherwise */ function paymentInternal(bytes32 _requestId, uint256 _amount) internal { requestCore.updateBalance(_requestId, _amount.toInt256Safe()); // payment done, the money is ready to withdraw by the payee fundOrderInternal(_requestId, requestCore.getPayee(_requestId), _amount); } /* * @dev Function internal to manage refund declaration * * @param _requestId id of the request * @param _amount amount of the refund in wei to declare * * @return true if the refund is done, false otherwise */ function refundInternal(bytes32 _requestId, uint256 _amount) internal { requestCore.updateBalance(_requestId, -_amount.toInt256Safe()); // payment done, the money is ready to withdraw by the payee fundOrderInternal(_requestId, requestCore.getPayer(_requestId), _amount); } /* * @dev Function internal to manage fund mouvement * * @param _requestId id of the request * @param _recipient adress where the wei has to me send to * @param _amount amount in wei to send * * @return true if the fund mouvement is done, false otherwise */ function fundOrderInternal(bytes32 _requestId, address _recipient, uint256 _amount) internal { // try to send the fund if(!_recipient.send(_amount)) { // if sendding fail, the funds are availbale to withdraw ethToWithdraw[_recipient] = ethToWithdraw[_recipient].add(_amount); // spread the word that the money is not sent but available to withdraw EtherAvailableToWithdraw(_requestId, _recipient, _amount); } } /* * @dev Function internal to calculate Keccak-256 hash of a request with specified parameters * * @param _payee Entity which will receive the payment. * @param _payer Entity supposed to pay. * @param _expectedAmount Expected amount to be received. This amount can't be changed. * @param _extension extension of the request. * @param _extensionParams Parameters for the extension. * * @return Keccak-256 hash of a request */ function getRequestHash(address _payee, address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data, uint256 _expirationDate) internal view returns(bytes32) { return keccak256(this,_payee,_payer,_expectedAmount,_extension,_extensionParams,_data,_expirationDate); } /* * @dev Verifies that a hash signature is valid. 0x style * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } function checkRequestSignature( address signer, address payee, address payer, int256 expectedAmount, address extension, bytes32[9] extensionParams, string data, uint256 expirationDate, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { bytes32 hash = getRequestHash(payee,payer,expectedAmount,extension,extensionParams,data,expirationDate); return isValidSignature(signer, hash, v, r, s); } //modifier modifier condition(bool c) { require(c); _; } /* * @dev Modifier to check if msg.sender is payer * @dev Revert if msg.sender is not payer * @param _requestId id of the request */ modifier onlyRequestPayer(bytes32 _requestId) { require(requestCore.getPayer(_requestId)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is payee * @dev Revert if msg.sender is not payee * @param _requestId id of the request */ modifier onlyRequestPayee(bytes32 _requestId) { require(requestCore.getPayee(_requestId)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is payee or payer * @dev Revert if msg.sender is not payee or payer * @param _requestId id of the request */ modifier onlyRequestPayeeOrPayer(bytes32 _requestId) { require(requestCore.getPayee(_requestId)==msg.sender || requestCore.getPayer(_requestId)==msg.sender); _; } /* * @dev Modifier to check if request is in a specify state * @dev Revert if request not in a specify state * @param _requestId id of the request * @param _state state to check */ modifier onlyRequestState(bytes32 _requestId, RequestCore.State _state) { require(requestCore.getState(_requestId)==_state); _; } }
16,494
32
// Increasing the count
numberOfAddressesWhitelisted += 1;
numberOfAddressesWhitelisted += 1;
1,386
17
// Description: Set the address of our own coin up so we can utilize our own DumpBuster Methods. This can only be called once. proxyAddress - The address of the proxy. /
function setProxy(address proxyAddress) public isOwner { require(_proxy==address(0)); _proxy = proxyAddress; }
function setProxy(address proxyAddress) public isOwner { require(_proxy==address(0)); _proxy = proxyAddress; }
4,516
10
// Set new period to distribute rewards between ethStartTimestamp and ethEndTimestamp/ evenly per second. ethAmountPerSecond = msg.value / (_ethEndTimestamp - _ethStartTimestamp)/ Can only be set once any existing setEthPerSecond regime has concluded (ethEndTimestamp < block.timestamp)/_ethStartTimestamp Timestamp for caching period start/_ethEndTimestamp Timestamp for caching period end
function setEthPerSecond( uint256 _ethStartTimestamp, uint256 _ethEndTimestamp
function setEthPerSecond( uint256 _ethStartTimestamp, uint256 _ethEndTimestamp
21,095
60
// clear any previously approved ownership exchange
delete stateIndexToApproved[_tokenId];
delete stateIndexToApproved[_tokenId];
12,701