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 |
|---|---|---|---|---|
113 | // Exposes internal function that withdraws a quantity of tokens from the vault anddeattributes the tokens respectively, to system modules. _fromAddress to decredit for withdraw_toAddress to transfer tokens to_token Address of token being withdrawn_quantityAmount of tokens to withdraw / | function withdrawModule(
| function withdrawModule(
| 27,492 |
10 | // uint256 _academicYearStart, uint256 _academicYearEnd, | string memory _merit
)
| string memory _merit
)
| 24,265 |
156 | // Updates address of 'trustedWallet_B' _trustedWalletNew address for 'trustedWallet_B' / | function setTrustedWallet_B(address _trustedWallet) external onlyRole(DEFAULT_ADMIN_ROLE) {
trustedWallet_B = _trustedWallet;
}
| function setTrustedWallet_B(address _trustedWallet) external onlyRole(DEFAULT_ADMIN_ROLE) {
trustedWallet_B = _trustedWallet;
}
| 58,027 |
7 | // main contract | abstract contract Main is ERC20 {
// ---------------------------------------- data
string public merchantName;
string public productName;
uint256 public cost;
uint256 public timeFrame;
address payable public merchantAddress;
constructor (string memory merchantName_, string memory productName_, uint256 cost_, uint256 timeFrame_, address payable merchantAddress_){
merchantName = merchantName_;
productName = productName_;
cost = cost_;
timeFrame = timeFrame_;
merchantAddress = merchantAddress_;
}
//finds users address
address public userAddress = msg.sender;
uint256 userBalance = userAddress.balance;
uint256 merchantBalace = merchantAddress.balance;
//calls on the first transfer of funds
function initTransfer(userAddress_, merchantAddress, cost) public {
if(userBalance_ < cost_) {
revert();
}
else {
_transfer(userAddress_, merchantAddress_, cost);
changeSubStatus();
}
}
// ------------------------------------------ paying/main
//function that is in charge of paying to address
function transfer(uint256 userBalance_, address payable userAddress_, uint256 cost_, address payable merchantAddress_) public {
_transfer(userAddress_, merchantAddress_, cost);
}
// takes in merchant address, user balance, cost,
// transfer amount(cost) from user balance to merchant address
// check if user has enough funds
function transferFunds (userAddress_, merchantAddress, cost) public {
if(userBalance_ < cost_) {
revert();
}
else {
_transfer(userAddress_, merchantAddress_, cost);
}
}
function names(merchantName_, productName_) public view {
return(merchantName_, productName_);
}
} | abstract contract Main is ERC20 {
// ---------------------------------------- data
string public merchantName;
string public productName;
uint256 public cost;
uint256 public timeFrame;
address payable public merchantAddress;
constructor (string memory merchantName_, string memory productName_, uint256 cost_, uint256 timeFrame_, address payable merchantAddress_){
merchantName = merchantName_;
productName = productName_;
cost = cost_;
timeFrame = timeFrame_;
merchantAddress = merchantAddress_;
}
//finds users address
address public userAddress = msg.sender;
uint256 userBalance = userAddress.balance;
uint256 merchantBalace = merchantAddress.balance;
//calls on the first transfer of funds
function initTransfer(userAddress_, merchantAddress, cost) public {
if(userBalance_ < cost_) {
revert();
}
else {
_transfer(userAddress_, merchantAddress_, cost);
changeSubStatus();
}
}
// ------------------------------------------ paying/main
//function that is in charge of paying to address
function transfer(uint256 userBalance_, address payable userAddress_, uint256 cost_, address payable merchantAddress_) public {
_transfer(userAddress_, merchantAddress_, cost);
}
// takes in merchant address, user balance, cost,
// transfer amount(cost) from user balance to merchant address
// check if user has enough funds
function transferFunds (userAddress_, merchantAddress, cost) public {
if(userBalance_ < cost_) {
revert();
}
else {
_transfer(userAddress_, merchantAddress_, cost);
}
}
function names(merchantName_, productName_) public view {
return(merchantName_, productName_);
}
} | 41,258 |
134 | // oraclize calback gas price is set to 4 gwei, should be quite ok | oraclize_setCustomGasPrice(4000000000);
| oraclize_setCustomGasPrice(4000000000);
| 31,432 |
50 | // paymnent must be greater than 1GWei and less than 100k ETH | require((msg.value > 1000000000) && (msg.value < 100000000000000000000000), "payment invalid");
_;
| require((msg.value > 1000000000) && (msg.value < 100000000000000000000000), "payment invalid");
_;
| 21,476 |
21 | // error handling | contract TestThrows {
function testAssert() public pure {
assert(1 == 2);
}
function testRequire() public pure {
require(2 == 1);
}
function testRevert() public pure {
revert();
}
function testThrow() public pure {
throw;
}
} | contract TestThrows {
function testAssert() public pure {
assert(1 == 2);
}
function testRequire() public pure {
require(2 == 1);
}
function testRevert() public pure {
revert();
}
function testThrow() public pure {
throw;
}
} | 30,336 |
12 | // Total amount of claimed tokens | uint256 public totalTokensClaimed;
| uint256 public totalTokensClaimed;
| 20,682 |
16 | // Return the owner of an NFT. If the result is the zero address,/ the token is considered invalid and we throw/tokenID The identifier for an NFT/ return The address of the owner of the NFT | function ownerOf(uint256 tokenID) external view isValidToken(tokenID) returns (address) {
return _ownerOf[tokenID];
}
| function ownerOf(uint256 tokenID) external view isValidToken(tokenID) returns (address) {
return _ownerOf[tokenID];
}
| 52,684 |
0 | // Creates request for Oraclize to get the BTC price payment_ The amount of WETH used as payment for Oraclize / | function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId) {
weth.withdraw(payment_);
require(oraclize_getPrice("URL", gasLimit) <= address(this).balance, "CryptoWatch.getAssetPrice: Ether balance is less than oraclize price");
queryId = oraclize_query("URL", "json(https://api.cryptowat.ch/markets/coinbase-pro/btcusd/price).result.price", gasLimit);
}
| function getAssetPrice(uint128 payment_) internal returns (bytes32 queryId) {
weth.withdraw(payment_);
require(oraclize_getPrice("URL", gasLimit) <= address(this).balance, "CryptoWatch.getAssetPrice: Ether balance is less than oraclize price");
queryId = oraclize_query("URL", "json(https://api.cryptowat.ch/markets/coinbase-pro/btcusd/price).result.price", gasLimit);
}
| 9,035 |
26 | // Declare a state variable representing the global seed. This value is set upon completion of the reveal phase and is used as a component of metadata generation for each token. | bytes32 public globalSeed;
| bytes32 public globalSeed;
| 31,869 |
5 | // The return value should match this arithmetic | oracle.latestBlockTimestamp() + oracle.SUBMISSION_INTERVAL()
);
| oracle.latestBlockTimestamp() + oracle.SUBMISSION_INTERVAL()
);
| 30,407 |
1 | // Locks baseUri when set to true | bool private _baseUri_frozen;
| bool private _baseUri_frozen;
| 20,180 |
10 | // The owners of the users. | mapping(uint256 userId => address) userOwners;
| mapping(uint256 userId => address) userOwners;
| 23,069 |
62 | // the next line is the loop condition: while(uint256(mc < end) + cb == 2) | for {
} eq(add(lt(mc, end), cb), 2) {
| for {
} eq(add(lt(mc, end), cb), 2) {
| 20,830 |
68 | // Core of the governance system, designed to be extended though various modules. This contract is abstract and requires several function to be implemented in various modules: | * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {_getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver {
using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
// This queue keeps track of the governor operating on itself. Calls to functions protected by the
// {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
// consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
// execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
DoubleEndedQueue.Bytes32Deque private _governanceCall;
/**
* @dev Restricts a function so it can only be executed through governance proposals. For example, governance
* parameter setters in {GovernorSettings} are protected using this modifier.
*
* The governance executing address may be different from the Governor's own address, for example it could be a
* timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
* functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
* for example, additional timelock proposers are not able to change governance parameters without going through the
* governance protocol (since v4.6).
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
if (_executor() != address(this)) {
bytes32 msgDataHash = keccak256(_msgData());
// loop until popping the expected operation - throw if deque is empty (operation not authorized)
while (_governanceCall.popFront() != msgDataHash) {}
}
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
*/
receive() external payable virtual {
require(_executor() == address(this));
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
// In addition to the current interfaceId, also support previous version of the interfaceId that did not
// include the castVoteWithReasonAndParams() function as standard
return
interfaceId ==
(type(IGovernor).interfaceId ^
this.castVoteWithReasonAndParams.selector ^
this.castVoteWithReasonAndParamsBySig.selector ^
this.getVotesWithParams.selector) ||
interfaceId == type(IGovernor).interfaceId ||
interfaceId == type(IERC1155Receiver).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* across multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
}
if (proposal.canceled) {
return ProposalState.Canceled;
}
uint256 snapshot = proposalSnapshot(proposalId);
if (snapshot == 0) {
revert("Governor: unknown proposal id");
}
if (snapshot >= block.number) {
return ProposalState.Pending;
}
uint256 deadline = proposalDeadline(proposalId);
if (deadline >= block.number) {
return ProposalState.Active;
}
if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
return ProposalState.Succeeded;
} else {
return ProposalState.Defeated;
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256) {
return 0;
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Get the voting weight of `account` at a specific `blockNumber`, for a vote as described by `params`.
*/
function _getVotes(
address account,
uint256 blockNumber,
bytes memory params
) internal view virtual returns (uint256);
/**
* @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight,
bytes memory params
) internal virtual;
/**
* @dev Default additional encoded parameters used by castVote methods that don't include them
*
* Note: Should be overridden by specific implementations to use an appropriate value, the
* meaning of the additional params, in the context of that implementation
*/
function _defaultParams() internal view virtual returns (bytes memory) {
return "";
}
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(_msgSender(), block.number - 1) >= proposalThreshold(),
"Governor: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
_execute(proposalId, targets, values, calldatas, descriptionHash);
_afterExecute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overridden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Hook before execution is triggered.
*/
function _beforeExecute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory, /* values */
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
if (_executor() != address(this)) {
for (uint256 i = 0; i < targets.length; ++i) {
if (targets[i] == address(this)) {
_governanceCall.pushBack(keccak256(calldatas[i]));
}
}
}
}
/**
* @dev Hook after execution is triggered.
*/
function _afterExecute(
uint256, /* proposalId */
address[] memory, /* targets */
uint256[] memory, /* values */
bytes[] memory, /* calldatas */
bytes32 /*descriptionHash*/
) internal virtual {
if (_executor() != address(this)) {
if (!_governanceCall.empty()) {
_governanceCall.clear();
}
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-getVotes}.
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return _getVotes(account, blockNumber, _defaultParams());
}
/**
* @dev See {IGovernor-getVotesWithParams}.
*/
function getVotesWithParams(
address account,
uint256 blockNumber,
bytes memory params
) public view virtual override returns (uint256) {
return _getVotes(account, blockNumber, params);
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteWithReasonAndParams}.
*/
function castVoteWithReasonAndParams(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason, params);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
*/
function castVoteWithReasonAndParamsBySig(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(
keccak256(
abi.encode(
EXTENDED_BALLOT_TYPEHASH,
proposalId,
support,
keccak256(bytes(reason)),
keccak256(params)
)
)
),
v,
r,
s
);
return _castVote(proposalId, voter, support, reason, params);
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
return _castVote(proposalId, account, support, reason, _defaultParams());
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason,
bytes memory params
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = _getVotes(account, proposal.voteStart.getDeadline(), params);
_countVote(proposalId, account, support, weight, params);
if (params.length == 0) {
emit VoteCast(account, proposalId, support, weight, reason);
} else {
emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
}
return weight;
}
/**
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
*/
function relay(
address target,
uint256 value,
bytes calldata data
) external virtual onlyGovernance {
Address.functionCallWithValue(target, data, value);
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @dev See {IERC1155Receiver-onERC1155Received}.
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev See {IERC1155Receiver-onERC1155BatchReceived}.
*/
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
| * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {_getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver {
using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
// This queue keeps track of the governor operating on itself. Calls to functions protected by the
// {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
// consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
// execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
DoubleEndedQueue.Bytes32Deque private _governanceCall;
/**
* @dev Restricts a function so it can only be executed through governance proposals. For example, governance
* parameter setters in {GovernorSettings} are protected using this modifier.
*
* The governance executing address may be different from the Governor's own address, for example it could be a
* timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
* functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
* for example, additional timelock proposers are not able to change governance parameters without going through the
* governance protocol (since v4.6).
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
if (_executor() != address(this)) {
bytes32 msgDataHash = keccak256(_msgData());
// loop until popping the expected operation - throw if deque is empty (operation not authorized)
while (_governanceCall.popFront() != msgDataHash) {}
}
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
*/
receive() external payable virtual {
require(_executor() == address(this));
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
// In addition to the current interfaceId, also support previous version of the interfaceId that did not
// include the castVoteWithReasonAndParams() function as standard
return
interfaceId ==
(type(IGovernor).interfaceId ^
this.castVoteWithReasonAndParams.selector ^
this.castVoteWithReasonAndParamsBySig.selector ^
this.getVotesWithParams.selector) ||
interfaceId == type(IGovernor).interfaceId ||
interfaceId == type(IERC1155Receiver).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* across multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
}
if (proposal.canceled) {
return ProposalState.Canceled;
}
uint256 snapshot = proposalSnapshot(proposalId);
if (snapshot == 0) {
revert("Governor: unknown proposal id");
}
if (snapshot >= block.number) {
return ProposalState.Pending;
}
uint256 deadline = proposalDeadline(proposalId);
if (deadline >= block.number) {
return ProposalState.Active;
}
if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
return ProposalState.Succeeded;
} else {
return ProposalState.Defeated;
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256) {
return 0;
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Get the voting weight of `account` at a specific `blockNumber`, for a vote as described by `params`.
*/
function _getVotes(
address account,
uint256 blockNumber,
bytes memory params
) internal view virtual returns (uint256);
/**
* @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight,
bytes memory params
) internal virtual;
/**
* @dev Default additional encoded parameters used by castVote methods that don't include them
*
* Note: Should be overridden by specific implementations to use an appropriate value, the
* meaning of the additional params, in the context of that implementation
*/
function _defaultParams() internal view virtual returns (bytes memory) {
return "";
}
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(_msgSender(), block.number - 1) >= proposalThreshold(),
"Governor: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
_execute(proposalId, targets, values, calldatas, descriptionHash);
_afterExecute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overridden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Hook before execution is triggered.
*/
function _beforeExecute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory, /* values */
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
if (_executor() != address(this)) {
for (uint256 i = 0; i < targets.length; ++i) {
if (targets[i] == address(this)) {
_governanceCall.pushBack(keccak256(calldatas[i]));
}
}
}
}
/**
* @dev Hook after execution is triggered.
*/
function _afterExecute(
uint256, /* proposalId */
address[] memory, /* targets */
uint256[] memory, /* values */
bytes[] memory, /* calldatas */
bytes32 /*descriptionHash*/
) internal virtual {
if (_executor() != address(this)) {
if (!_governanceCall.empty()) {
_governanceCall.clear();
}
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-getVotes}.
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return _getVotes(account, blockNumber, _defaultParams());
}
/**
* @dev See {IGovernor-getVotesWithParams}.
*/
function getVotesWithParams(
address account,
uint256 blockNumber,
bytes memory params
) public view virtual override returns (uint256) {
return _getVotes(account, blockNumber, params);
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteWithReasonAndParams}.
*/
function castVoteWithReasonAndParams(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason, params);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
*/
function castVoteWithReasonAndParamsBySig(
uint256 proposalId,
uint8 support,
string calldata reason,
bytes memory params,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(
keccak256(
abi.encode(
EXTENDED_BALLOT_TYPEHASH,
proposalId,
support,
keccak256(bytes(reason)),
keccak256(params)
)
)
),
v,
r,
s
);
return _castVote(proposalId, voter, support, reason, params);
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
return _castVote(proposalId, account, support, reason, _defaultParams());
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason,
bytes memory params
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = _getVotes(account, proposal.voteStart.getDeadline(), params);
_countVote(proposalId, account, support, weight, params);
if (params.length == 0) {
emit VoteCast(account, proposalId, support, weight, reason);
} else {
emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
}
return weight;
}
/**
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
*/
function relay(
address target,
uint256 value,
bytes calldata data
) external virtual onlyGovernance {
Address.functionCallWithValue(target, data, value);
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @dev See {IERC1155Receiver-onERC1155Received}.
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev See {IERC1155Receiver-onERC1155BatchReceived}.
*/
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
| 17,129 |
324 | // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. | FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
| FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
| 2,638 |
1 | // mint it | _mint(theList[x], _nextUp());
_oneTeamMint();
| _mint(theList[x], _nextUp());
_oneTeamMint();
| 4,688 |
2 | // array of Applications Objects | mapping (uint => mapping (uint => uint)) private AppsOBJprice; // AppsOBJ[_app][_obj] = price; (in virtual units (PMC))
mapping (uint => mapping (uint => uint)) private AppsOBJduration;
| mapping (uint => mapping (uint => uint)) private AppsOBJprice; // AppsOBJ[_app][_obj] = price; (in virtual units (PMC))
mapping (uint => mapping (uint => uint)) private AppsOBJduration;
| 31,983 |
27 | // OwnableThe Ownable contract has an owner address, and provides basicauthorization control functions, this simplifies the implementation of "user permissions"./ | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: sender is not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
owner = address(0);
emit OwnershipRenounced(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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Ownable: transfer to zero address");
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
| contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: sender is not owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
owner = address(0);
emit OwnershipRenounced(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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Ownable: transfer to zero address");
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
| 39,468 |
55 | // Return array of all whitelisted addresses return address[]Array of addresses / | function validAddresses()
external
view
returns (address[] memory)
| function validAddresses()
external
view
returns (address[] memory)
| 26,983 |
5 | // Creator Royalty Interface | IERC721CreatorRoyalty public iERC721CreatorRoyalty;
| IERC721CreatorRoyalty public iERC721CreatorRoyalty;
| 2,456 |
101 | // lock everything that is lockable | _lockLiquidity(balanceOf(address(this)));
| _lockLiquidity(balanceOf(address(this)));
| 43,667 |
18 | // owner可以退回合约内的token. / | function revoke() public {
require (msg.sender == owner);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(owner, amount);
}
| function revoke() public {
require (msg.sender == owner);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(owner, amount);
}
| 8,556 |
5 | // Check if an airline is registered/ | function isRegistered(address airline) external returns (bool);
| function isRegistered(address airline) external returns (bool);
| 32,387 |
257 | // save last committed period to the storage if both periods will be empty after minting because we won't be able to calculate last committed period see getLastCommittedPeriod(address) | StakerInfo storage info = stakerInfo[msg.sender];
uint16 previousPeriod = getCurrentPeriod() - 1;
if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) {
info.lastCommittedPeriod = info.nextCommittedPeriod;
}
| StakerInfo storage info = stakerInfo[msg.sender];
uint16 previousPeriod = getCurrentPeriod() - 1;
if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) {
info.lastCommittedPeriod = info.nextCommittedPeriod;
}
| 50,093 |
5 | // Logged when an operator is added or removed. | event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function setRecord(
bytes32 node,
address owner,
address resolver,
| event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function setRecord(
bytes32 node,
address owner,
address resolver,
| 31,012 |
3 | // Increase the PlanetAdded by User | _mint(msg.sender, newItemId);
| _mint(msg.sender, newItemId);
| 26,734 |
118 | // - The max supply. / | uint256 internal constant MAX_SUPPLY = 26_930_000e18;
| uint256 internal constant MAX_SUPPLY = 26_930_000e18;
| 13,448 |
4 | // free memory pointer | let memPtr := mload(0x40)
| let memPtr := mload(0x40)
| 11,111 |
141 | // check oracle type | require(vault.oracleType(asset, msg.sender) == ORACLE_TYPE, "Unit Protocol: WRONG_ORACLE_TYPE");
| require(vault.oracleType(asset, msg.sender) == ORACLE_TYPE, "Unit Protocol: WRONG_ORACLE_TYPE");
| 74,958 |
24 | // Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance/ to a function before the pool is initialized. The reentrancy guard is required throughout the contract because/ we use balance checks to determine the payment status of interactions such as mint, swap and flash. | modifier lock() {
require(slot0.unlocked, 'LOK');
slot0.unlocked = false;
_;
slot0.unlocked = true;
}
| modifier lock() {
require(slot0.unlocked, 'LOK');
slot0.unlocked = false;
_;
slot0.unlocked = true;
}
| 27,231 |
54 | // Called by our MarketContract (owner) when redemption occurs.This means that either a single user is redeeming/ both short and long tokens in order to claim their collateral, or the contract has settled, and only a single/ side of the tokens are needed to redeem (handled by the collateral pool)/qtyToRedeem quantity of tokens to burn (remove from supply / circulation)/redeemer the person redeeming these tokens (who are we taking the balance from) | function redeemToken(
uint256 qtyToRedeem,
address redeemer
) external onlyOwner
| function redeemToken(
uint256 qtyToRedeem,
address redeemer
) external onlyOwner
| 15,796 |
0 | // Uoptimal[0;1] in Wad | uint256 public immutable _U_Optimal_WAD;
| uint256 public immutable _U_Optimal_WAD;
| 34,142 |
161 | // Feature is disabled | require(
false,
"Feature not supported"
);
require(
lpAddresses.length == allowedToDeposit.length,
"Invalid arrays"
);
| require(
false,
"Feature not supported"
);
require(
lpAddresses.length == allowedToDeposit.length,
"Invalid arrays"
);
| 7,116 |
72 | // See {BEP20-balanceOf}. / | function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
| function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
| 368 |
632 | // collateral occupation rate calculation collateral occupation rate = sum(collateral Ratecollateral balance) / sum(collateral balance) / | function calculateCollateralRate() external view returns (uint256);
| function calculateCollateralRate() external view returns (uint256);
| 77,718 |
18 | // returns total balance of PCV in the Deposit excluding the FEI/returns stale values from Compound if the market hasn't been updated | function balance() public view override returns (uint256) {
uint256 exchangeRate = cToken.exchangeRateStored();
return cToken.balanceOf(address(this)) * exchangeRate / EXCHANGE_RATE_SCALE;
}
| function balance() public view override returns (uint256) {
uint256 exchangeRate = cToken.exchangeRateStored();
return cToken.balanceOf(address(this)) * exchangeRate / EXCHANGE_RATE_SCALE;
}
| 64,580 |
2 | // Changes amount of Bytes each erc20NYM is tradable for. Can only be called by Owner._newBytesPerTokenAmountAmount of Bytes BBC is worth per 1 erc20NYM token. / | function changeRatio(uint256 _newBytesPerTokenAmount) public onlyOwner {
require(_newBytesPerTokenAmount != 0, "BandwidthGenerator: price cannot be 0");
BytesPerToken = _newBytesPerTokenAmount;
emit RatioChanged(_newBytesPerTokenAmount);
}
| function changeRatio(uint256 _newBytesPerTokenAmount) public onlyOwner {
require(_newBytesPerTokenAmount != 0, "BandwidthGenerator: price cannot be 0");
BytesPerToken = _newBytesPerTokenAmount;
emit RatioChanged(_newBytesPerTokenAmount);
}
| 45,162 |
10 | // Calculate the expected results for zap minting/_ethIn Amount of Collateral token input./ return _xTokenOut : the amount of XToken output./ return _yTokenOutTwap : the amount of YToken output by swapping based on Twap price/ return _ethFee : the fee amount in Collateral token./ return _ethSwapIn : the amount of Collateral token to swap | function calcMint(uint256 _ethIn)
public
view
returns (
uint256 _xTokenOut,
uint256 _yTokenOutTwap,
uint256 _ethFee,
uint256 _ethSwapIn
)
| function calcMint(uint256 _ethIn)
public
view
returns (
uint256 _xTokenOut,
uint256 _yTokenOutTwap,
uint256 _ethFee,
uint256 _ethSwapIn
)
| 18,152 |
132 | // Check For Rogue Faction token in Wallet | function _checkRogue(AddressID memory ownerID, AddressData memory ownerData)
private
returns (AddressID memory oID, AddressData memory o)
| function _checkRogue(AddressID memory ownerID, AddressData memory ownerData)
private
returns (AddressID memory oID, AddressData memory o)
| 52,624 |
89 | // address lotteryTokenAddress; | uint256 randomSeed;
uint256 startedAt;
| uint256 randomSeed;
uint256 startedAt;
| 33,472 |
29 | // Calculate the demand amount of Ether | uint256 eth = tmv.mul(precision()).div(rate());
require(msg.value >= eth, "Not enough funds");
emit Funded(eth);
| uint256 eth = tmv.mul(precision()).div(rate());
require(msg.value >= eth, "Not enough funds");
emit Funded(eth);
| 43,513 |
170 | // Validates a swap of borrow rate mode. reserve The reserve state on which the user is swapping the rate userConfig The user reserves configuration stableDebt The stable debt of the user variableDebt The variable debt of the user currentRateMode The rate mode of the borrow / | function validateSwapRateMode(
DataTypes.ReserveData storage reserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 stableDebt,
uint256 variableDebt,
DataTypes.InterestRateMode currentRateMode
| function validateSwapRateMode(
DataTypes.ReserveData storage reserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 stableDebt,
uint256 variableDebt,
DataTypes.InterestRateMode currentRateMode
| 19,564 |
256 | // Withdraw assets | _withdrawBoostedAsset(
dfWallet, USDC_ADDRESS, CUSDC_ADDRESS, amountUSDC, receiver, flashloanUSDC, flashloanType, flashloanFromAddress
);
_withdrawBoostedAsset(
dfWallet, DAI_ADDRESS, CDAI_ADDRESS, amountDAI, receiver, flashloanDAI, flashloanType, flashloanFromAddress
);
_withdrawAsset(
dfWallet, ETH_ADDRESS, CETH_ADDRESS, amountETH, receiver
| _withdrawBoostedAsset(
dfWallet, USDC_ADDRESS, CUSDC_ADDRESS, amountUSDC, receiver, flashloanUSDC, flashloanType, flashloanFromAddress
);
_withdrawBoostedAsset(
dfWallet, DAI_ADDRESS, CDAI_ADDRESS, amountDAI, receiver, flashloanDAI, flashloanType, flashloanFromAddress
);
_withdrawAsset(
dfWallet, ETH_ADDRESS, CETH_ADDRESS, amountETH, receiver
| 30,364 |
4 | // Fulfill an order with an arbitrary number of items for offer andconsideration. Note that this function does not supportcriteria-based orders or partial filling of orders (thoughfilling the remainder of a partially-filled order is supported).order The order to fulfill. Note that both the offerer and the fulfiller must first approve this contract (or the corresponding conduit if indicated) to transfer any relevant tokens on their behalf and that contracts must implement `onERC1155Received` to receive ERC1155 tokens as consideration. fulfillerConduitKey A bytes32 value indicating what conduit, if any, to source the fulfiller's token approvals from. The zero hash signifies that no conduit | function fulfillOrder(Order calldata order, bytes32 fulfillerConduitKey)
external
payable
returns (bool fulfilled);
| function fulfillOrder(Order calldata order, bytes32 fulfillerConduitKey)
external
payable
returns (bool fulfilled);
| 14,024 |
48 | // Returns the exit date of the validator. | function getExitDate() external view returns (uint256);
| function getExitDate() external view returns (uint256);
| 79,920 |
30 | // Returns the total amount claimable until the nowPoint point in time vesting schedule to calculate amount for user to retrieve the already spent amount nowTime point in time to check for / | function _amountForClaim(
VestingProperties storage vesting,
UserProperties storage user,
uint256 nowTime
| function _amountForClaim(
VestingProperties storage vesting,
UserProperties storage user,
uint256 nowTime
| 25,628 |
2 | // calculates the senior ratio/seniorAsset the current senior asset value/nav the current NAV/reserve the current reserve/ return seniorRatio the senior ratio | function calcSeniorRatio(uint256 seniorAsset, uint256 nav, uint256 reserve)
public
pure
returns (uint256 seniorRatio)
| function calcSeniorRatio(uint256 seniorAsset, uint256 nav, uint256 reserve)
public
pure
returns (uint256 seniorRatio)
| 10,334 |
224 | // update uniswap | UniswapPair(uniswap_pair).sync();
if (mintAmount > 0) {
buyReserveAndTransfer(
mintAmount,
offPegPerc
);
}
| UniswapPair(uniswap_pair).sync();
if (mintAmount > 0) {
buyReserveAndTransfer(
mintAmount,
offPegPerc
);
}
| 18,527 |
3 | // Pair Fees contract is used as a 1:1 pair relationship to split out fees, this ensures that the curve does not need to be modified for LP shares | contract PairFees {
address internal immutable pair; // The pair it is bonded to
address internal immutable token0; // token0 of pair, saved localy and statically for gas optimization
address internal immutable token1; // Token1 of pair, saved localy and statically for gas optimization
constructor(address _token0, address _token1) {
pair = msg.sender;
token0 = _token0;
token1 = _token1;
}
function _safeTransfer(address token,address to,uint256 value) internal {
require(token.code.length > 0);
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
// Allow the pair to transfer fees to users
function claimFeesFor(address recipient, uint amount0, uint amount1) external {
require(msg.sender == pair);
if (amount0 > 0) _safeTransfer(token0, recipient, amount0);
if (amount1 > 0) _safeTransfer(token1, recipient, amount1);
}
}
| contract PairFees {
address internal immutable pair; // The pair it is bonded to
address internal immutable token0; // token0 of pair, saved localy and statically for gas optimization
address internal immutable token1; // Token1 of pair, saved localy and statically for gas optimization
constructor(address _token0, address _token1) {
pair = msg.sender;
token0 = _token0;
token1 = _token1;
}
function _safeTransfer(address token,address to,uint256 value) internal {
require(token.code.length > 0);
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
// Allow the pair to transfer fees to users
function claimFeesFor(address recipient, uint amount0, uint amount1) external {
require(msg.sender == pair);
if (amount0 > 0) _safeTransfer(token0, recipient, amount0);
if (amount1 > 0) _safeTransfer(token1, recipient, amount1);
}
}
| 15,767 |
16 | // Event emitted when an address authorises an operator (third-party). Emits event that informs of address approving/denying a third-party operator. wallet Address of the wallet configuring it's operator. operator Address of the third-party operator that interacts on behalf of the wallet. approved A boolean indicating whether approval was granted or revoked. / | event ApprovalForAll(address indexed wallet, address indexed operator, bool approved);
| event ApprovalForAll(address indexed wallet, address indexed operator, bool approved);
| 29,356 |
11 | // _name = "Yield Finance Compound";_symbol = "YFIC"; | _name = "Yield Finance Compound";
_symbol = "YFIC";
_decimals = 18;
_totalSupply = 30000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
| _name = "Yield Finance Compound";
_symbol = "YFIC";
_decimals = 18;
_totalSupply = 30000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
| 40,696 |
25 | // do nothing | } catch {
| } catch {
| 45,012 |
134 | // Manager fees | uint256 public tokenPriceAtLastFeeMint;
mapping(address => uint256) public lastDeposit;
| uint256 public tokenPriceAtLastFeeMint;
mapping(address => uint256) public lastDeposit;
| 27,885 |
153 | // Bots call this method to repay for user when conditions are met/If the contract owns gas token it will try and use it for gas price reduction | function repayFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint256 _cdpId,
uint256 _nextPrice,
address _joinAddr,
FLHelper.FLType _flType
| function repayFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint256 _cdpId,
uint256 _nextPrice,
address _joinAddr,
FLHelper.FLType _flType
| 26,841 |
7 | // Fees | lpFee = fees.lpFee;
lpFeeOnSell = fees.lpFeeOnSell;
devFee = fees.devFee;
devFeeOnSell = fees.devFeeOnSell;
mainFee = fees.mainFee;
mainFeeOnSell = fees.mainFeeOnSell;
totalFee = devFee + lpFee + mainFee + proofFee;
totalFeeIfSelling = devFeeOnSell + lpFeeOnSell + mainFeeOnSell + proofFee;
| lpFee = fees.lpFee;
lpFeeOnSell = fees.lpFeeOnSell;
devFee = fees.devFee;
devFeeOnSell = fees.devFeeOnSell;
mainFee = fees.mainFee;
mainFeeOnSell = fees.mainFeeOnSell;
totalFee = devFee + lpFee + mainFee + proofFee;
totalFeeIfSelling = devFeeOnSell + lpFeeOnSell + mainFeeOnSell + proofFee;
| 17,878 |
3,390 | // 1697 | entry "synesthetically" : ENG_ADVERB
| entry "synesthetically" : ENG_ADVERB
| 22,533 |
115 | // As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address.- `tokenId` token must be owned by `from`. Emits a {Transfer} event. Altered to not use the balances map / | function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Cheap.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
| function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Cheap.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
| 11,079 |
6 | // Address of the Voter contract | address public voter;
| address public voter;
| 12,551 |
64 | // Set next pointer of new tail to null | self.nodes[self.tail].nextId = address(0);
| self.nodes[self.tail].nextId = address(0);
| 23,563 |
1 | // Returns the total supply of the token. / | uint public _totalSupply;
| uint public _totalSupply;
| 35,464 |
11 | // Extra (bonus) assets that will be delivered at the end of escrow. | AssetLib.AssetData[] extraAssets;
| AssetLib.AssetData[] extraAssets;
| 25,799 |
87 | // End token offering by set the stage and endTime / | function endOfferingImpl() internal {
endTime = now;
stage = Stages.OfferingEnded;
OfferingCloses(endTime, weiRaised);
}
| function endOfferingImpl() internal {
endTime = now;
stage = Stages.OfferingEnded;
OfferingCloses(endTime, weiRaised);
}
| 42,483 |
15 | // 3 bits type, then 3 bits material. This is repeated 7 times perDiceIdx | uint256 shiftAmount = diceIdx * 6;
| uint256 shiftAmount = diceIdx * 6;
| 5,145 |
20 | // internal function to create a new Battle Card | function _createGameToken(string memory _name) internal returns (GameToken memory) {
uint256 randAttackStrength = _createRandomNum(MAX_ATTACK_DEFEND_STRENGTH, msg.sender);
uint256 randDefenseStrength = MAX_ATTACK_DEFEND_STRENGTH - randAttackStrength;
uint8 randId = uint8(uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 100);
randId = randId % 6;
if (randId == 0) {
randId++;
}
GameToken memory newGameToken = GameToken(
_name,
randId,
randAttackStrength,
randDefenseStrength
);
uint256 _id = gameTokens.length;
gameTokens.push(newGameToken);
playerTokenInfo[msg.sender] = _id;
_mint(msg.sender, randId, 1, '0x0');
totalSupply++;
emit NewGameToken(msg.sender, randId, randAttackStrength, randDefenseStrength);
return newGameToken;
}
| function _createGameToken(string memory _name) internal returns (GameToken memory) {
uint256 randAttackStrength = _createRandomNum(MAX_ATTACK_DEFEND_STRENGTH, msg.sender);
uint256 randDefenseStrength = MAX_ATTACK_DEFEND_STRENGTH - randAttackStrength;
uint8 randId = uint8(uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 100);
randId = randId % 6;
if (randId == 0) {
randId++;
}
GameToken memory newGameToken = GameToken(
_name,
randId,
randAttackStrength,
randDefenseStrength
);
uint256 _id = gameTokens.length;
gameTokens.push(newGameToken);
playerTokenInfo[msg.sender] = _id;
_mint(msg.sender, randId, 1, '0x0');
totalSupply++;
emit NewGameToken(msg.sender, randId, randAttackStrength, randDefenseStrength);
return newGameToken;
}
| 21,192 |
11 | // The amount of GD tokens that was contributed during the conversion | uint256 contributionAmount,
| uint256 contributionAmount,
| 41,016 |
8 | // set min length in unix timestamp length (1 day = 86400) _address address to set the parameter _target parameter / | function setMinDate(address _address, uint256 _target)
external
override
onlyOwner
| function setMinDate(address _address, uint256 _target)
external
override
onlyOwner
| 6,790 |
28 | // Creates locks for the provided _beneficiary with the provided amountThe creation can be peformed only if:- the sender is the owner of the contract;- the _beneficiary and _tokenHolder are valid addresses;- the _amount is greater than 0 and was appoved by the _tokenHolder prior to the transaction.The team members will have two locks with 1 and 2 years lock period, each having half of the amount. _beneficiary Address that will own the lock. _amount the amount of the locked tokens. _start when the lock should start. _tokenHolder the account that approved the amount for this contract. / | function createTeamTokenTimeLock(
address _beneficiary,
uint256 _amount,
uint256 _start,
address _tokenHolder
) external onlyOwner returns (bool)
| function createTeamTokenTimeLock(
address _beneficiary,
uint256 _amount,
uint256 _start,
address _tokenHolder
) external onlyOwner returns (bool)
| 52,919 |
99 | // Mints a policyholder's policy. | function _mint(address policyholder) internal {
uint256 tokenId = _tokenId(policyholder);
ERC721NonTransferableMinimalProxy._mint(policyholder, tokenId);
(uint96 numberOfHolders, uint96 totalQuantity) = roleSupplyCkpts[ALL_HOLDERS_ROLE].latest();
unchecked {
// Safety: Can never overflow a uint96 by incrementing.
roleSupplyCkpts[ALL_HOLDERS_ROLE].push(numberOfHolders + 1, totalQuantity + 1);
}
roleBalanceCkpts[tokenId][ALL_HOLDERS_ROLE].push(1, type(uint64).max);
emit RoleAssigned(policyholder, ALL_HOLDERS_ROLE, type(uint64).max, 1);
}
| function _mint(address policyholder) internal {
uint256 tokenId = _tokenId(policyholder);
ERC721NonTransferableMinimalProxy._mint(policyholder, tokenId);
(uint96 numberOfHolders, uint96 totalQuantity) = roleSupplyCkpts[ALL_HOLDERS_ROLE].latest();
unchecked {
// Safety: Can never overflow a uint96 by incrementing.
roleSupplyCkpts[ALL_HOLDERS_ROLE].push(numberOfHolders + 1, totalQuantity + 1);
}
roleBalanceCkpts[tokenId][ALL_HOLDERS_ROLE].push(1, type(uint64).max);
emit RoleAssigned(policyholder, ALL_HOLDERS_ROLE, type(uint64).max, 1);
}
| 33,864 |
7 | // Here we are loading the last 32 bytes, including 31 bytes of 's'. There is no 'mload8' to do this. 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' | v := and(mload(add(_signatures, add(signaturePos, 0x41))), 0xff)
| v := and(mload(add(_signatures, add(signaturePos, 0x41))), 0xff)
| 29,640 |
13 | // Reads an immutable arg with type uint256/argOffset The offset of the arg in the packed data/ return arg The arg value | function _getArgUint256(uint256 argOffset)
internal
pure
returns (uint256 arg)
| function _getArgUint256(uint256 argOffset)
internal
pure
returns (uint256 arg)
| 14,280 |
60 | // Call StandardToken.transferForm() | return super.transferFrom(_from, _to, _value);
| return super.transferFrom(_from, _to, _value);
| 22,232 |
56 | // | if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
return 0;
}
| if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
return 0;
}
| 31,562 |
32 | // uint amountEth = liquidity.mul(eth) / liquidityTotalSupply;using balances ensures pro-rata distribution | uint amountTokens = (liquidity.mul(tokens)).div(liquidityTotalSupply); // using balances ensures pro-rata distribution
uint months = stakeMonths;
uint baseRate = baseRateLookup[getRewardIndex()];
uint multiplier = multiplierLookup[getpoolLevelsIndex(eth)][getMonthsIndex(months)];
uint reward = (amountTokens.mul(months).mul(baseRate).mul(multiplier)).div(1000000);
return(reward);
| uint amountTokens = (liquidity.mul(tokens)).div(liquidityTotalSupply); // using balances ensures pro-rata distribution
uint months = stakeMonths;
uint baseRate = baseRateLookup[getRewardIndex()];
uint multiplier = multiplierLookup[getpoolLevelsIndex(eth)][getMonthsIndex(months)];
uint reward = (amountTokens.mul(months).mul(baseRate).mul(multiplier)).div(1000000);
return(reward);
| 17,076 |
39 | // rgm cryptum | require((newFeeAddr1 + newFeeAddr2) <= 10, "Fee cannot be set higher than 10%");
_feeAddr1 = newFeeAddr1;
_feeAddr2 = newFeeAddr2;
| require((newFeeAddr1 + newFeeAddr2) <= 10, "Fee cannot be set higher than 10%");
_feeAddr1 = newFeeAddr1;
_feeAddr2 = newFeeAddr2;
| 34,849 |
23 | // if passenger buy insurance !!! | Insurance storage _insurance = insurancesList[insuranceKey];
| Insurance storage _insurance = insurancesList[insuranceKey];
| 34,542 |
10 | // sqrt(1.0001), 96 bit fixpoint number | uint160 public override sqrtRate_96;
| uint160 public override sqrtRate_96;
| 18,823 |
34 | // Reference of Mintable token/Setup in contructor phase and never change in future | IMintableToken public token;
| IMintableToken public token;
| 19,018 |
25 | // Transfer ownership from `founder` to the `_newOwner`. | founder = _newOwner;
| founder = _newOwner;
| 41,501 |
144 | // pool has virtual 0.01 unit of base asset to avoid division by zero and reasonable starting share value calculation UBT has 8 decimal points, so small 1e6 as a starting point should be enough | totalShareAmount = 1e6;
totalAssetAmount = 1e6;
depositsEnabled = true;
profitFee = 0;
inceptionTimestamp = block.timestamp;
| totalShareAmount = 1e6;
totalAssetAmount = 1e6;
depositsEnabled = true;
profitFee = 0;
inceptionTimestamp = block.timestamp;
| 38,774 |
173 | // Counts the number of nonoverlapping occurrences of `needle` in `self`. self The slice to search. needle The text to search for in `self`.return The number of occurrences of `needle` found in `self`. / | function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
| function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
| 12,623 |
33 | // Fees | uint256 sclFees = valueInSCL * 5 / 10**2;
| uint256 sclFees = valueInSCL * 5 / 10**2;
| 35,700 |
79 | // During the ICO, devs get 25% (5% originally, 7% from the dividends fraction,and 13% from the returns), leaving 2% for dividends, and 52% for returnsThis is only during the first round, and later rounds leave the original fractions: 5% for devs, 9% dividends, 65% returns | if(rounds.length == 1){
| if(rounds.length == 1){
| 33,535 |
278 | // Returns the number of checkpoint. / | function length(History storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
| function length(History storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
| 14,484 |
20 | // Poke Weights must be called at regular intervals - so the LBP price gradually changes/Can be called by anyone after LBP start block/Just calling CRP function - for simpler FrontEnd access | function pokeWeights() external {
crp.pokeWeights();
}
| function pokeWeights() external {
crp.pokeWeights();
}
| 8,224 |
69 | // Returns active auctions. / | function fetchAuctions() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onAuction.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && idToMarketItem[i + 1].typeItem == TypeItem.Auction) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
| function fetchAuctions() public view returns (MarketItem[] memory) {
uint currentIndex = 0;
// Initialize array
MarketItem[] memory items = new MarketItem[](_onAuction.current());
// Fill array
for (uint i = 0; i < _itemIds.current(); i++) {
if (idToMarketItem[i + 1].onSale && idToMarketItem[i + 1].typeItem == TypeItem.Auction) {
uint currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
| 25,314 |
175 | // The IPT TOKEN! | IptToken public ipt;
| IptToken public ipt;
| 7,367 |
379 | // This default function can receive Ether or perform queries to modules/using bound methods. | fallback()
external
payable
| fallback()
external
payable
| 15,848 |
30 | // Expose internal function that exchanges components for Set tokens,accepting any owner, to system modules _ownerAddress to use tokens from_recipientAddress to issue Set to_setAddress of the Set to issue_quantity Number of tokens to issue / | function issueModule(
| function issueModule(
| 12,235 |
149 | // Called by token contract after Approval | function receiveApproval(address _from, uint _amountOfTokens, address _token, bytes _data) external senderIsToken notPaused {
uint8 numberOfCoinSides = uint8(_data[31]);
uint8 playerChosenSide = uint8(_data[63]);
require((_amountOfTokens >= minAllowedBetInTokens) && (_amountOfTokens <= maxAllowedBetInTokens), "Invalid tokens amount.");
emit TokenStart(msg.sender, _from, _amountOfTokens);
uint tokensAmountAfterFees = _amountOfTokens.sub(tokenFee);
_checkGeneralRequirements(tokensAmountAfterFees, numberOfCoinSides, playerChosenSide);
// Transfer tokens from sender to this contract
require(token.transferFrom(_from, address(this), _amountOfTokens), "Tokens transfer failed.");
emit TokenTransferExecuted(_from, address(this), _amountOfTokens);
_initializeFlip(_from, BetCurrency.Token, tokensAmountAfterFees, 0, numberOfCoinSides, playerChosenSide, 0);
}
| function receiveApproval(address _from, uint _amountOfTokens, address _token, bytes _data) external senderIsToken notPaused {
uint8 numberOfCoinSides = uint8(_data[31]);
uint8 playerChosenSide = uint8(_data[63]);
require((_amountOfTokens >= minAllowedBetInTokens) && (_amountOfTokens <= maxAllowedBetInTokens), "Invalid tokens amount.");
emit TokenStart(msg.sender, _from, _amountOfTokens);
uint tokensAmountAfterFees = _amountOfTokens.sub(tokenFee);
_checkGeneralRequirements(tokensAmountAfterFees, numberOfCoinSides, playerChosenSide);
// Transfer tokens from sender to this contract
require(token.transferFrom(_from, address(this), _amountOfTokens), "Tokens transfer failed.");
emit TokenTransferExecuted(_from, address(this), _amountOfTokens);
_initializeFlip(_from, BetCurrency.Token, tokensAmountAfterFees, 0, numberOfCoinSides, playerChosenSide, 0);
}
| 10,248 |
1 | // STORAGE // EVENTS // FUNCTION / | function isIUser() public pure returns (bool) {
return true;
}
| function isIUser() public pure returns (bool) {
return true;
}
| 51,045 |
17 | // Lets a direct listing creator cancel their listing. _listingId The unique Id of the lisitng to cancel. / | function cancelDirectListing(uint256 _listingId) external;
| function cancelDirectListing(uint256 _listingId) external;
| 7,258 |
63 | // Helper function for querying an address' balance on a given token. / | function getBalance(
address token,
address owner
)
internal
view
returns (uint _balance)
| function getBalance(
address token,
address owner
)
internal
view
returns (uint _balance)
| 328 |
48 | // for lambda^2 u^2 factor in rounding error in u since lambda could be big Note: lambda^2 is multiplied at the end to be sure the calculation doesn't overflow, but this can lose some precision | val = val + ((d.u + 1).mulXpU(d.u + 1).divXpU(dSq3)).mulUpMagU(p.lambda).mulUpMagU(p.lambda);
| val = val + ((d.u + 1).mulXpU(d.u + 1).divXpU(dSq3)).mulUpMagU(p.lambda).mulUpMagU(p.lambda);
| 17,747 |
21 | // ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name, decimals and totalSupply ---------------------------------------------------------------------------- | contract Bitway is ERC20 {
using SafeMath for uint;
string public name = "Bitway";
string public symbol = "BTWX";
uint public totalSupply = 0;
uint8 public decimals = 18;
uint public RATE = 1000;
uint multiplier = 10 ** uint(decimals);
uint million = 10 ** 6;
uint millionTokens = 1 * million * multiplier;
uint constant stageTotal = 5;
uint stage = 0;
uint [stageTotal] targetSupply = [
1 * millionTokens,
2 * millionTokens,
5 * millionTokens,
10 * millionTokens,
21 * millionTokens
];
address public owner;
bool public completed = true;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
owner = msg.sender;
supplyTokens(millionTokens);
}
// ------------------------------------------------------------------------
// Payable token creation
// ------------------------------------------------------------------------
function () public payable {
createTokens();
}
// ------------------------------------------------------------------------
// Returns currentStage
// ------------------------------------------------------------------------
function currentStage() public constant returns (uint) {
return stage + 1;
}
// ------------------------------------------------------------------------
// Returns maxSupplyReached True / False
// ------------------------------------------------------------------------
function maxSupplyReached() public constant returns (bool) {
return stage >= stageTotal;
}
// ------------------------------------------------------------------------
// Token creation
// ------------------------------------------------------------------------
function createTokens() public payable {
require(!completed);
supplyTokens(msg.value.mul((15 - stage) * RATE / 10));
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Complete token sale
// ------------------------------------------------------------------------
function setComplete(bool _completed) public {
require(msg.sender == owner);
completed = _completed;
}
// ------------------------------------------------------------------------
// Check totalSupply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Create tokens and supply to msg.sender balances
// ------------------------------------------------------------------------
function supplyTokens(uint tokens) private {
require(!maxSupplyReached());
balances[msg.sender] = balances[msg.sender].add(tokens);
totalSupply = totalSupply.add(tokens);
if (totalSupply >= targetSupply[stage]) {
stage += 1;
}
emit Transfer(address(0), msg.sender, tokens);
}
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
} | contract Bitway is ERC20 {
using SafeMath for uint;
string public name = "Bitway";
string public symbol = "BTWX";
uint public totalSupply = 0;
uint8 public decimals = 18;
uint public RATE = 1000;
uint multiplier = 10 ** uint(decimals);
uint million = 10 ** 6;
uint millionTokens = 1 * million * multiplier;
uint constant stageTotal = 5;
uint stage = 0;
uint [stageTotal] targetSupply = [
1 * millionTokens,
2 * millionTokens,
5 * millionTokens,
10 * millionTokens,
21 * millionTokens
];
address public owner;
bool public completed = true;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
owner = msg.sender;
supplyTokens(millionTokens);
}
// ------------------------------------------------------------------------
// Payable token creation
// ------------------------------------------------------------------------
function () public payable {
createTokens();
}
// ------------------------------------------------------------------------
// Returns currentStage
// ------------------------------------------------------------------------
function currentStage() public constant returns (uint) {
return stage + 1;
}
// ------------------------------------------------------------------------
// Returns maxSupplyReached True / False
// ------------------------------------------------------------------------
function maxSupplyReached() public constant returns (bool) {
return stage >= stageTotal;
}
// ------------------------------------------------------------------------
// Token creation
// ------------------------------------------------------------------------
function createTokens() public payable {
require(!completed);
supplyTokens(msg.value.mul((15 - stage) * RATE / 10));
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Complete token sale
// ------------------------------------------------------------------------
function setComplete(bool _completed) public {
require(msg.sender == owner);
completed = _completed;
}
// ------------------------------------------------------------------------
// Check totalSupply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Create tokens and supply to msg.sender balances
// ------------------------------------------------------------------------
function supplyTokens(uint tokens) private {
require(!maxSupplyReached());
balances[msg.sender] = balances[msg.sender].add(tokens);
totalSupply = totalSupply.add(tokens);
if (totalSupply >= targetSupply[stage]) {
stage += 1;
}
emit Transfer(address(0), msg.sender, tokens);
}
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
} | 25,499 |
55 | // This will be the getter function that everyone can call to check the campaign currentDonation.Parameters of this function will include uint campaignId / | function getCampaignCurrentDonation(
uint256 campaignId
)
public
view
returns (uint256)
| function getCampaignCurrentDonation(
uint256 campaignId
)
public
view
returns (uint256)
| 35,789 |
99 | // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero | require(_amount > 0);
| require(_amount > 0);
| 5,775 |
2 | // Defines the student record structure that contains the block number, the timestamp, the student id, student name, the student image, university, and the IPFS hash of his certificate. | struct StudentRecord {
uint blockNumber;
uint timestamp;
uint id;
string name;
string uni;
string image;
string ipfsHash;
}
| struct StudentRecord {
uint blockNumber;
uint timestamp;
uint id;
string name;
string uni;
string image;
string ipfsHash;
}
| 4,123 |
45 | // Event emitted when interestRateModel is changed / | event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
| event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
| 13,552 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.