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 |
|---|---|---|---|---|
8 | // Sets an immutable fixed `size` to `classId` / | function _fixClassSize(uint256 classId, uint256 size)
internal virtual
| function _fixClassSize(uint256 classId, uint256 size)
internal virtual
| 48,678 |
28 | // Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc. | * Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| * Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 519 |
17 | // the constructor of the contract / | constructor() public {
totalSupply = 100000000000000000;
balanceOf[msg.sender] = totalSupply;
name = "QIEX Credit Points";
symbol = "QI";
decimals = 8;
owner = msg.sender;
isOwner[owner] = true;
isRunning = true;
//addOwners(_admins);
}
| constructor() public {
totalSupply = 100000000000000000;
balanceOf[msg.sender] = totalSupply;
name = "QIEX Credit Points";
symbol = "QI";
decimals = 8;
owner = msg.sender;
isOwner[owner] = true;
isRunning = true;
//addOwners(_admins);
}
| 21,780 |
230 | // Invalidates a Data Availability Service keyset ksHash hash of the keyset / | function invalidateKeysetHash(bytes32 ksHash) external;
| function invalidateKeysetHash(bytes32 ksHash) external;
| 36,706 |
141 | // Update the status for the inbox for a given message hash to`Progressed`_messageBox Message Box. _message Message object. _unlockSecret Unlock secret for the hash lock provided while declaration. return messageHash_ Message hash. / | function progressInbox(
MessageBox storage _messageBox,
Message storage _message,
bytes32 _unlockSecret
)
external
returns (bytes32 messageHash_)
| function progressInbox(
MessageBox storage _messageBox,
Message storage _message,
bytes32 _unlockSecret
)
external
returns (bytes32 messageHash_)
| 25,149 |
32 | // Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address / | receive() external payable {
flush();
}
| receive() external payable {
flush();
}
| 24,815 |
17 | // owner一次性获取代币 | function HLWCOIN() public {
balances[msg.sender] = MAX_SUPPLY;
Transfer(0x0, msg.sender, MAX_SUPPLY);
}
| function HLWCOIN() public {
balances[msg.sender] = MAX_SUPPLY;
Transfer(0x0, msg.sender, MAX_SUPPLY);
}
| 73,253 |
19 | // State Getters | function getFixedPercRate() external view returns (uint256) {
return percentageFee;
}
| function getFixedPercRate() external view returns (uint256) {
return percentageFee;
}
| 44,445 |
144 | // TODO Require that amount <= available rewards. | _updateAccrual();
| _updateAccrual();
| 25,315 |
2 | // This contract is used to generate clone contracts from a contract. It is based on the MiniMeTokenFactory contract. In solidity this is the way to create a contract from a contract of the same class / | contract ExpositoProjectFactory {
/**
* @notice Update the DApp by creating a new token with new functionalities
* the msg.sender becomes the controller of this clone token
* @param _parentToken Address of the token being cloned
* @param _snapshotBlock Block of the parent token that will
* determine the initial distribution of the clone token
* @return The address of the new token contract
*/
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
bool _transfersEnabled,
string _projectId
) public returns (ExpositoProject)
{
ExpositoProject newToken = new ExpositoProject(
this,
_parentToken,
_snapshotBlock,
_projectId,
0,
0,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
} | contract ExpositoProjectFactory {
/**
* @notice Update the DApp by creating a new token with new functionalities
* the msg.sender becomes the controller of this clone token
* @param _parentToken Address of the token being cloned
* @param _snapshotBlock Block of the parent token that will
* determine the initial distribution of the clone token
* @return The address of the new token contract
*/
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
bool _transfersEnabled,
string _projectId
) public returns (ExpositoProject)
{
ExpositoProject newToken = new ExpositoProject(
this,
_parentToken,
_snapshotBlock,
_projectId,
0,
0,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
} | 21,584 |
0 | // [[a,b,c,d], [a1,b1,c1,d1]...] where each subarray is a column. since you'd access the subarray-style 2D array like this: col, row that means that in the 1D array, the first grouping is the first col. The second grouping is the second col, etc As such, element 1 is equivalent to 0,1 -- element 2 = 0,2 -- element 33 = 1,0 -- element 34 = 1,1 this is a bit counter intuitive. You might think it would be arranged first row, second row, etc... but you'd be wrong. | address creator;
function MapElevationStorage()
| address creator;
function MapElevationStorage()
| 39,680 |
26 | // perform the actual conversion and optionally send ETH to the network | uint256 targetAmount = network.convertByPath{ value: value }(path, amount, 1, address(this), address(0), 0);
| uint256 targetAmount = network.convertByPath{ value: value }(path, amount, 1, address(this), address(0), 0);
| 22,289 |
28 | // register the agreement proxy | _agreementClasses.push((agreementClass));
_agreementClassIndices[agreementType] = _agreementClasses.length;
emit AgreementClassRegistered(agreementType, address(agreementClassLogic));
| _agreementClasses.push((agreementClass));
_agreementClassIndices[agreementType] = _agreementClasses.length;
emit AgreementClassRegistered(agreementType, address(agreementClassLogic));
| 33,736 |
95 | // Checks if daily and/or monthly cooldown must be reset, then check if _value sent has been exceeded,if not increases user's OnchainID counters. _userAddress, address on which counters will be increased _value, value of transaction)to be increased/ | function _increaseCounters(address _userAddress, uint256 _value) internal {
address identity = _getIdentity(_userAddress);
_resetDailyCooldown(identity);
_resetMonthlyCooldown(identity);
if ((usersCounters[identity].dailyCount + _value) <= dailyLimit) {
usersCounters[identity].dailyCount += _value;
}
if ((usersCounters[identity].monthlyCount + _value) <= monthlyLimit) {
usersCounters[identity].monthlyCount += _value;
}
}
| function _increaseCounters(address _userAddress, uint256 _value) internal {
address identity = _getIdentity(_userAddress);
_resetDailyCooldown(identity);
_resetMonthlyCooldown(identity);
if ((usersCounters[identity].dailyCount + _value) <= dailyLimit) {
usersCounters[identity].dailyCount += _value;
}
if ((usersCounters[identity].monthlyCount + _value) <= monthlyLimit) {
usersCounters[identity].monthlyCount += _value;
}
}
| 18,241 |
13 | // THIS IS AN EXAMPLE CONTRACT WHICH USES HARDCODED VALUES FOR CLARITY.PLEASE DO NOT USE THIS CODE IN PRODUCTION. / | contract FilinkConsumer is ChainlinkClient {
using Chainlink for Chainlink.Request;
mapping(bytes32 => string) private mapRequestDeal;
mapping(string => uint256) private mapDealPrice;
address private oracle;
bytes32 private jobId;
uint256 private fee;
uint256 public price;
/**
* Network: matic test
* Oracle: 0x0bDDCD124709aCBf9BB3F824EbC61C87019888bb (Chainlink Devrel
* Node)
* Chainlink address: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
* post -> bytes32
* Job ID: 35738ec3cf9f4fd296b17bb91fdda32e
* Fee: 0.01 LINK
*/
// function initialize(address admin, address _chainlinkToken, address _oracle, bytes32 _jobId, uint256 _fee) public initializer {
// __Ownable_init();
// __AccessControl_init();
// _setupRole(DEFAULT_ADMIN_ROLE, admin);
// setChainlinkToken(_chainlinkToken);
// oracle = _oracle;
// jobId = _jobId;
// fee = _fee; // (Varies by network and job)
// }
constructor(address _chainlinkToken, address _oracle, uint256 _fee) {
setChainlinkToken(_chainlinkToken);
oracle = _oracle;
jobId = "2bb15c3f9cfc4336b95012872ff05092";
fee = _fee; // (Varies by network and job)
}
function concatenate(
string memory s1,
string memory s2
) private pure returns (string memory) {
return string(abi.encodePacked(s1, s2));
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data, then multiply by 1000000000000000000 (to remove decimal places from data).
*/
// todo: use call back to pay
function requestDealInfo(string calldata deal) public returns (bytes32 requestId)
{
require(mapDealPrice[deal] == 0, "deal price is already on-chain, call getPrice(deal)");
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Set the URL to perform the GET request on
request.add("get", concatenate("https://cxq4eshb10.execute-api.us-east-1.amazonaws.com/default/test2?deal=", deal));
// request.add("deal", deal);
request.add("path", "data.deal.storage_price");
bytes32 id = sendChainlinkRequestTo(oracle, request, fee);
mapRequestDeal[id] = deal;
return id;
}
/**
* Receive the response in the form of uint256
*/
function fulfill( bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId)
{
price = _price;
mapDealPrice[mapRequestDeal[_requestId]] = _price;
}
function getPrice(string calldata deal) public view returns (uint256)
{
return mapDealPrice[deal];
}
// function withdrawLINK(address _to, uint256 _amount) onlyowner public returns (bool)
// {
// return transfer(address(this), _to, _amount);
// }
}
| contract FilinkConsumer is ChainlinkClient {
using Chainlink for Chainlink.Request;
mapping(bytes32 => string) private mapRequestDeal;
mapping(string => uint256) private mapDealPrice;
address private oracle;
bytes32 private jobId;
uint256 private fee;
uint256 public price;
/**
* Network: matic test
* Oracle: 0x0bDDCD124709aCBf9BB3F824EbC61C87019888bb (Chainlink Devrel
* Node)
* Chainlink address: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
* post -> bytes32
* Job ID: 35738ec3cf9f4fd296b17bb91fdda32e
* Fee: 0.01 LINK
*/
// function initialize(address admin, address _chainlinkToken, address _oracle, bytes32 _jobId, uint256 _fee) public initializer {
// __Ownable_init();
// __AccessControl_init();
// _setupRole(DEFAULT_ADMIN_ROLE, admin);
// setChainlinkToken(_chainlinkToken);
// oracle = _oracle;
// jobId = _jobId;
// fee = _fee; // (Varies by network and job)
// }
constructor(address _chainlinkToken, address _oracle, uint256 _fee) {
setChainlinkToken(_chainlinkToken);
oracle = _oracle;
jobId = "2bb15c3f9cfc4336b95012872ff05092";
fee = _fee; // (Varies by network and job)
}
function concatenate(
string memory s1,
string memory s2
) private pure returns (string memory) {
return string(abi.encodePacked(s1, s2));
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data, then multiply by 1000000000000000000 (to remove decimal places from data).
*/
// todo: use call back to pay
function requestDealInfo(string calldata deal) public returns (bytes32 requestId)
{
require(mapDealPrice[deal] == 0, "deal price is already on-chain, call getPrice(deal)");
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Set the URL to perform the GET request on
request.add("get", concatenate("https://cxq4eshb10.execute-api.us-east-1.amazonaws.com/default/test2?deal=", deal));
// request.add("deal", deal);
request.add("path", "data.deal.storage_price");
bytes32 id = sendChainlinkRequestTo(oracle, request, fee);
mapRequestDeal[id] = deal;
return id;
}
/**
* Receive the response in the form of uint256
*/
function fulfill( bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId)
{
price = _price;
mapDealPrice[mapRequestDeal[_requestId]] = _price;
}
function getPrice(string calldata deal) public view returns (uint256)
{
return mapDealPrice[deal];
}
// function withdrawLINK(address _to, uint256 _amount) onlyowner public returns (bool)
// {
// return transfer(address(this), _to, _amount);
// }
}
| 53,443 |
3 | // The maximum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) | uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
| uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
| 34,393 |
41 | // anyone who participated but did not win the auction should be allowed to withdraw the full amount of their funds | withdrawalAccount = payable(msg.sender);
withdrawalAmount = _auctionInfos[auctionID].fundsByBidder[withdrawalAccount];
| withdrawalAccount = payable(msg.sender);
withdrawalAmount = _auctionInfos[auctionID].fundsByBidder[withdrawalAccount];
| 18,641 |
195 | // Verification Holders Timestamp | verificationHoldersTimestampMap[ _from ] = now;
| verificationHoldersTimestampMap[ _from ] = now;
| 6,667 |
6 | // Resolve this ENSSubdomainRegistrar's root node to `_target`_target Ethereum address root node will point to/ | function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) {
_pointToResolverAndResolve(rootNode, _target);
}
| function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) {
_pointToResolverAndResolve(rootNode, _target);
}
| 32,830 |
10 | // bytes32 private constant NAME_HASH = keccak256("Aragon Network Token") | bytes32 private constant NAME_HASH = 0x711a8013284a3c0046af6c0d6ed33e8bbc2c7a11d615cf4fdc8b1ac753bda618;
| bytes32 private constant NAME_HASH = 0x711a8013284a3c0046af6c0d6ed33e8bbc2c7a11d615cf4fdc8b1ac753bda618;
| 38,532 |
49 | // Atomically decreases the allowance granted to `spender` by the caller. | * This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
| * This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
| 9,474 |
315 | // can be set only once | require(m_funds == address(0));
m_funds = FundsRegistry(_funds);
| require(m_funds == address(0));
m_funds = FundsRegistry(_funds);
| 33,100 |
17 | // ------------------------------------------------------------------------ | function BithubCommunityToken() public {
symbol = "BHCx";
name = "Bithubcommunity Token";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[0xbfde0299a76e9437df7242d090c73ba709834ba5] = 734750000000000000000000000;
Transfer(address(0), 0xbfde0299a76e9437df7242d090c73ba709834ba5, 734750000000000000000000000);
bonusEnds = now + 9 weeks;
endDate = now + 14 weeks;
}
| function BithubCommunityToken() public {
symbol = "BHCx";
name = "Bithubcommunity Token";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[0xbfde0299a76e9437df7242d090c73ba709834ba5] = 734750000000000000000000000;
Transfer(address(0), 0xbfde0299a76e9437df7242d090c73ba709834ba5, 734750000000000000000000000);
bonusEnds = now + 9 weeks;
endDate = now + 14 weeks;
}
| 26,628 |
333 | // Swaps two indexes in the withdrawal stack./index1 One index involved in the swap/index2 The other index involved in the swap. | function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth {
// Get the (soon to be) new strategies at each index.
Strategy newStrategy2 = withdrawalStack[index1];
Strategy newStrategy1 = withdrawalStack[index2];
// Swap the strategies at both indexes.
withdrawalStack[index1] = newStrategy1;
withdrawalStack[index2] = newStrategy2;
emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2);
}
| function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth {
// Get the (soon to be) new strategies at each index.
Strategy newStrategy2 = withdrawalStack[index1];
Strategy newStrategy1 = withdrawalStack[index2];
// Swap the strategies at both indexes.
withdrawalStack[index1] = newStrategy1;
withdrawalStack[index2] = newStrategy2;
emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2);
}
| 55,559 |
5 | // Preview the number of points that would be returned for the/ given amount and duration.//amount mav to be staked/duration number of seconds to stake for/ return points staking points that would be returned/ return end staking period end date | function previewPoints(uint256 amount, uint256 duration) external view returns (uint256, uint256);
| function previewPoints(uint256 amount, uint256 duration) external view returns (uint256, uint256);
| 36,011 |
452 | // Service function to calculate and pay pending vault and yield rewards to the senderInternally executes similar function `_processRewards` from the parent smart contract to calculate and pay yield rewards; adds vault rewards processingCan be executed by anyone at any time, but has an effect only when executed by deposit holder and when at least one block passes from the previous reward processing Executed internally when "staking as a pool" (`stakeAsPool`) When timing conditions are not met (executed too frequently, or after factory end block), function doesn't throw and exits silently_useSILV flag has a context of yield rewards only_useSILV flag indicating | function processRewards(bool _useSILV) external override {
_processRewards(msg.sender, _useSILV, true);
}
| function processRewards(bool _useSILV) external override {
_processRewards(msg.sender, _useSILV, true);
}
| 50,800 |
11 | // Transfers tokens using a signed permit messages/permit The permit data signed over by the owner/dataHash The EIP-712 hash of permit data to include when checking signature/owner The owner of the tokens to transfer/signature The signature to verify | function _permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes32 dataHash,
bytes calldata signature
| function _permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes32 dataHash,
bytes calldata signature
| 24,867 |
37 | // List of enabled Modules; Modules extend the functionality of SetTokens | address[] public modules;
| address[] public modules;
| 8,871 |
65 | // WETH -> VaultX -> XWETH -> Bridge -> PXWETH _toAddress need to be little endian and start with 0x fef: https:peterlinx.github.io/DataTransformationTools/ | function lock(bytes memory _toAddress, uint256 _amount) public {
// need approve infinte amount from user then safe transfer from
IERC20(want).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(want).approve(xvault, _amount);
Vault(xvault).deposit(_amount);
// https://github.com/polynetwork/eth-contracts/blob/master/contracts/core/lock_proxy/LockProxy.sol#L64
IERC20(xvault).approve(polyLockProxy, _amount);
// 4 -> neo mainnet 5 -> neo testnet
LockProxy(polyLockProxy).lock(xvault, 4, _toAddress, _amount);
}
| function lock(bytes memory _toAddress, uint256 _amount) public {
// need approve infinte amount from user then safe transfer from
IERC20(want).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(want).approve(xvault, _amount);
Vault(xvault).deposit(_amount);
// https://github.com/polynetwork/eth-contracts/blob/master/contracts/core/lock_proxy/LockProxy.sol#L64
IERC20(xvault).approve(polyLockProxy, _amount);
// 4 -> neo mainnet 5 -> neo testnet
LockProxy(polyLockProxy).lock(xvault, 4, _toAddress, _amount);
}
| 9,973 |
24 | // index da compra per account | accountOrdens[_account].push(index);
if(_batch == WL){
totalSoldWL+= _tokens;
}
| accountOrdens[_account].push(index);
if(_batch == WL){
totalSoldWL+= _tokens;
}
| 16,566 |
188 | // Duplicated affirmations | require(!affirmationsSigned(hashSender));
setAffirmationsSigned(hashSender, true);
uint256 signed = numAffirmationsSigned(hashMsg);
require(!isAlreadyProcessed(signed));
| require(!affirmationsSigned(hashSender));
setAffirmationsSigned(hashSender, true);
uint256 signed = numAffirmationsSigned(hashMsg);
require(!isAlreadyProcessed(signed));
| 7,742 |
40 | // skip for non-kine config, which should have valid underlying address | if(config.underlying != address(0)){
uint reporterPrice = priceData.getPrice(reporter, symbols[i]);
if(config.priceSource != KPriceSource.COMPOUND)
postPriceInternal(symbols[i], ethPrice, config, reporterPrice);
}
| if(config.underlying != address(0)){
uint reporterPrice = priceData.getPrice(reporter, symbols[i]);
if(config.priceSource != KPriceSource.COMPOUND)
postPriceInternal(symbols[i], ethPrice, config, reporterPrice);
}
| 415 |
6 | // Returns the bit at the given '_index' in '_self'. _self Uint to check. _index Index of the bit to get.return The value of the bit at '_index'. / | function getBit(uint _self, uint8 _index)
internal
pure
returns (uint8)
| function getBit(uint _self, uint8 _index)
internal
pure
returns (uint8)
| 8,615 |
250 | // The fish's genetic code - this will never change for any fish. | uint256 genes;
| uint256 genes;
| 3,561 |
12 | // Mint the token(s) | _mint(msg.sender, amount, false, false);
| _mint(msg.sender, amount, false, false);
| 54,244 |
10 | // The ZrxRouter is used by settlement to execute orders through 0x | contract ZrxRouter is BaseAccess, IDexRouter {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
using SafeERC20 for IERC20;
function initialize() public initializer {
BaseAccess.initAccess();
}
// @dev Executes a call to 0x to make fill the order
// @param order - contains the order details from the Smart Order Router
// @param orderCallData - abi encoded swapTarget address and data from 0x API
function fill(Types.Order calldata order, bytes calldata orderCallData)
external override returns (bool success, string memory failReason) {
//call data contains the target address and data to pass to it to execute
(address swapTarget, address allowanceTarget, bytes memory data) = abi.decode(orderCallData, (address,address,bytes));
console.log("Going to swap target", swapTarget);
console.log("Approving allowance for", allowanceTarget);
//Settlement transferred token input amount so we can swap
uint256 balanceBefore = order.output.token.balanceOf(address(this));
console.log("Balance of input token b4", balanceBefore);
//for protocols that require zero-first approvals
require(order.input.token.approve(allowanceTarget, 0));
//make sure 0x target has approval to spend this contract's tokens
require(order.input.token.approve(allowanceTarget, order.input.amount));
//execute the swap
console.log("Swapping with gasleft", gasleft());
(bool _success,) = swapTarget.call{gas: gasleft()}(data);
console.log("Gas after swap", gasleft());
if(!_success) {
console.log("Failed to swap");
return (false, "SWAP_CALL_FAILED");
}
//make sure we received tokens
uint256 balanceAfter = order.output.token.balanceOf(address(this));
console.log("Balance after", balanceAfter);
uint256 diff = balanceAfter.sub(balanceBefore);
console.log("Balance received", diff);
console.log("Min required", order.output.amount);
require(diff >= order.output.amount, "Insufficient output amount");
//SafeERC should revert on this call if there's a problem
order.output.token.safeTransfer(order.trader, diff);
console.log("Transfer to trader complete");
return (true, "");
}
// Payable fallback to allow this contract to receive protocol fee refunds.
receive() external payable {}
}
| contract ZrxRouter is BaseAccess, IDexRouter {
using SafeMath for uint256;
using SafeMath for uint112;
using SafeMath for uint;
using SafeERC20 for IERC20;
function initialize() public initializer {
BaseAccess.initAccess();
}
// @dev Executes a call to 0x to make fill the order
// @param order - contains the order details from the Smart Order Router
// @param orderCallData - abi encoded swapTarget address and data from 0x API
function fill(Types.Order calldata order, bytes calldata orderCallData)
external override returns (bool success, string memory failReason) {
//call data contains the target address and data to pass to it to execute
(address swapTarget, address allowanceTarget, bytes memory data) = abi.decode(orderCallData, (address,address,bytes));
console.log("Going to swap target", swapTarget);
console.log("Approving allowance for", allowanceTarget);
//Settlement transferred token input amount so we can swap
uint256 balanceBefore = order.output.token.balanceOf(address(this));
console.log("Balance of input token b4", balanceBefore);
//for protocols that require zero-first approvals
require(order.input.token.approve(allowanceTarget, 0));
//make sure 0x target has approval to spend this contract's tokens
require(order.input.token.approve(allowanceTarget, order.input.amount));
//execute the swap
console.log("Swapping with gasleft", gasleft());
(bool _success,) = swapTarget.call{gas: gasleft()}(data);
console.log("Gas after swap", gasleft());
if(!_success) {
console.log("Failed to swap");
return (false, "SWAP_CALL_FAILED");
}
//make sure we received tokens
uint256 balanceAfter = order.output.token.balanceOf(address(this));
console.log("Balance after", balanceAfter);
uint256 diff = balanceAfter.sub(balanceBefore);
console.log("Balance received", diff);
console.log("Min required", order.output.amount);
require(diff >= order.output.amount, "Insufficient output amount");
//SafeERC should revert on this call if there's a problem
order.output.token.safeTransfer(order.trader, diff);
console.log("Transfer to trader complete");
return (true, "");
}
// Payable fallback to allow this contract to receive protocol fee refunds.
receive() external payable {}
}
| 19,570 |
62 | // Add a new LP to the pool.Can only be called by the owner./ DO NOT add the same LP token more than once. Rewards will be messed up if you do./allocPoint AP of the new pool./_pid Pid on MCV2 | function add(uint256 allocPoint, uint256 _pid) public onlyOwner {
require(poolInfo[_pid].lastRewardBlock == 0, "Pool already exists");
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolInfo[_pid] = PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardBlock: lastRewardBlock.to64(),
accSushiPerShare: 0
});
poolIds.push(_pid);
emit LogPoolAddition(_pid, allocPoint);
}
| function add(uint256 allocPoint, uint256 _pid) public onlyOwner {
require(poolInfo[_pid].lastRewardBlock == 0, "Pool already exists");
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolInfo[_pid] = PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardBlock: lastRewardBlock.to64(),
accSushiPerShare: 0
});
poolIds.push(_pid);
emit LogPoolAddition(_pid, allocPoint);
}
| 23,500 |
1 | // Should return whether the signature provided is valid for the provided hash hash 32 bytes hash to be signed signature Signature byte array associated with hashreturn magicValue - 0x1626ba7e if valid else 0x00000000 / | function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
| function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
| 17,094 |
4 | // registered relayers | mapping(address => RelayerInfo) private _relayerInfo;
| mapping(address => RelayerInfo) private _relayerInfo;
| 2,916 |
50 | // Get the approved address for a single ELHT/_tokenId The ELHT to find the approved address for/ return The approved address for this ELHT, or the zero address if there is none | function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) {
return cardIdToApprovals[_tokenId];
}
| function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) {
return cardIdToApprovals[_tokenId];
}
| 14,261 |
74 | // For a new target range to be valid:- the pool must currently be between the current targets (meaning no fees are currently pending)- the pool must currently be between the new targets (meaning setting them does not cause for fees to bepending) The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, but being stricter makes analysis easier at little expense. |
(uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets();
_require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE);
_require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE);
_setTargets(_mainToken, newLowerTarget, newUpperTarget);
|
(uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets();
_require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE);
_require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE);
_setTargets(_mainToken, newLowerTarget, newUpperTarget);
| 67,770 |
3 | // Address of CLA contract. | ClaimToken public cla;
| ClaimToken public cla;
| 50,453 |
32 | // Protocol fees are skipped when processing recovery mode exits, since these are pool-agnostic and it is therefore impossible to know how many fees are due. For consistency, all regular joins and exits are processed as if the protocol swap fee percentage was zero. | dueProtocolFeeAmounts = new uint256[](balances.length);
(bptAmountIn, amountsOut) = _doRecoveryModeExit(balances, totalSupply(), userData);
| dueProtocolFeeAmounts = new uint256[](balances.length);
(bptAmountIn, amountsOut) = _doRecoveryModeExit(balances, totalSupply(), userData);
| 15,391 |
172 | // The number of standard deviations (from volatilityOracle) to +/- from mean when choosing/ range for primary Uniswap position | function B() external view returns (uint8);
| function B() external view returns (uint8);
| 57,825 |
136 | // default method when ether is paid to the contract's address used for the WETH withdraw callback | function() external payable {
}
| function() external payable {
}
| 54,068 |
461 | // If the loan was already fully canceled, then just return 0 amount was canceled | if (amountToCancel == 0) {
return 0;
}
| if (amountToCancel == 0) {
return 0;
}
| 35,261 |
6 | // mapping from hashed(tokenTrait) to tokenId | mapping(uint256 => uint256) public existingTraits;
| mapping(uint256 => uint256) public existingTraits;
| 49,705 |
7 | // set the baseTokenURI of an extension.Can only be called by extension.For tokens with no uri configured, tokenURI will return "uri+tokenId" / | function setBaseTokenURIExtension(string calldata uri, bool identical)
| function setBaseTokenURIExtension(string calldata uri, bool identical)
| 24,406 |
6 | // swap directly based on provided inputs | function swap() onlyOwner public{
address[] memory uniswapPairPath = new address[](2);
uniswapPairPath[0] = _wethAddress;
uniswapPairPath[1] = tokenAddress;
(address token0,) = sortTokens(_wethAddress, tokenAddress);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(_uniswapFactory, _wethAddress, tokenAddress)).getReserves();
(uint reserveInput, uint reserveOutput) = _wethAddress == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint ethPurchaseAmount = address(this).balance;
uint tokenOutAmount = _uniswap.getAmountOut(ethPurchaseAmount, reserveInput, reserveOutput);
_uniswap.swapExactETHForTokens{value : ethPurchaseAmount}(tokenOutAmount,uniswapPairPath,receiveAddress,block.timestamp);
}
| function swap() onlyOwner public{
address[] memory uniswapPairPath = new address[](2);
uniswapPairPath[0] = _wethAddress;
uniswapPairPath[1] = tokenAddress;
(address token0,) = sortTokens(_wethAddress, tokenAddress);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(_uniswapFactory, _wethAddress, tokenAddress)).getReserves();
(uint reserveInput, uint reserveOutput) = _wethAddress == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint ethPurchaseAmount = address(this).balance;
uint tokenOutAmount = _uniswap.getAmountOut(ethPurchaseAmount, reserveInput, reserveOutput);
_uniswap.swapExactETHForTokens{value : ethPurchaseAmount}(tokenOutAmount,uniswapPairPath,receiveAddress,block.timestamp);
}
| 11,675 |
13 | // Gets the amount of creator annuities reserved for the creator for the specified NFT/contractAddress The Address to the Contract of the NFT/tokenId The Token ID of the NFT/ return creator The address of the creator/ return annuityPct The percentage amount of annuities reserved for the creator | function getCreatorAnnuities(
address contractAddress,
uint256 tokenId
)
external
view
override
virtual
returns (address creator, uint256 annuityPct)
| function getCreatorAnnuities(
address contractAddress,
uint256 tokenId
)
external
view
override
virtual
returns (address creator, uint256 annuityPct)
| 26,087 |
12 | // Job Id to get > string 7d80a6386ef543a3abb52817f6707e3b | jobId = "7d80a6386ef543a3abb52817f6707e3b";
| jobId = "7d80a6386ef543a3abb52817f6707e3b";
| 36,049 |
11 | // Execute the transaction | _returnValues[i] = _decodeAndExecuteTransaction(_transactions[i], _isMetaTransaction);
| _returnValues[i] = _decodeAndExecuteTransaction(_transactions[i], _isMetaTransaction);
| 47,658 |
242 | // Get the Vault's current total strategy holdings. | uint256 oldTotalStrategyHoldings = totalStrategyHoldings;
| uint256 oldTotalStrategyHoldings = totalStrategyHoldings;
| 21,418 |
23 | // llama a una funcion privada y devuelve el nombre del candidato ganador | function nombre_ganador() public view returns(string memory){
require(!periodo_eleccion, "Las votaciones siguen vigentes");
string memory nombre;
(nombre,) = _ganador_votacion();//con la , ignoramos la cantidad que obtuvo ya que lo utilizaremos en otra funcion
return nombre;
}
| function nombre_ganador() public view returns(string memory){
require(!periodo_eleccion, "Las votaciones siguen vigentes");
string memory nombre;
(nombre,) = _ganador_votacion();//con la , ignoramos la cantidad que obtuvo ya que lo utilizaremos en otra funcion
return nombre;
}
| 10,266 |
14 | // Review section | reviews[productId].push(Review(user, productId, rating, comment, 0));
userReviews[user].push(productId);
products[productId].totalRatings += rating;
products[productId].numReviews++;
emit ReviewAdded(productId, user, rating, comment);
reviewCounter++;
| reviews[productId].push(Review(user, productId, rating, comment, 0));
userReviews[user].push(productId);
products[productId].totalRatings += rating;
products[productId].numReviews++;
emit ReviewAdded(productId, user, rating, comment);
reviewCounter++;
| 31,441 |
72 | // Calculate and create all team share VUPs |
coreTeamShare = CORE_TEAM_PORTION;
uint256 devTeamShare = DEV_TEAM_PORTION;
cofounderShare = CO_FOUNDER_PORTION;
uint256 udfShare = UDF_PORTION;
balances[devVUPDestination] = devTeamShare;
balances[advisoryVUPDestination] = advisoryTeamShare;
balances[udfVUPDestination] = udfShare;
|
coreTeamShare = CORE_TEAM_PORTION;
uint256 devTeamShare = DEV_TEAM_PORTION;
cofounderShare = CO_FOUNDER_PORTION;
uint256 udfShare = UDF_PORTION;
balances[devVUPDestination] = devTeamShare;
balances[advisoryVUPDestination] = advisoryTeamShare;
balances[udfVUPDestination] = udfShare;
| 30,178 |
287 | // Changes the name for tokenId / | function changeArt(
uint256 tokenId,
string memory newRoomOwnerName,
uint256 newTimeStamp
| function changeArt(
uint256 tokenId,
string memory newRoomOwnerName,
uint256 newTimeStamp
| 10,480 |
42 | // fee Code | uint256 fee = transferFee.mul(value).div(10000);
| uint256 fee = transferFee.mul(value).div(10000);
| 7,814 |
10 | // misc | uint256 internal constant EMPTY_BITMAP = 0;
string internal constant WHERE_TO_FIND_TERMS =
"Terms and conditions can be found by calling getTerms() on the Keepers contract.";
| uint256 internal constant EMPTY_BITMAP = 0;
string internal constant WHERE_TO_FIND_TERMS =
"Terms and conditions can be found by calling getTerms() on the Keepers contract.";
| 29,538 |
175 | // Otherwise, use the previously stored number from the matrix. | value = tokenMatrix[random];
| value = tokenMatrix[random];
| 20,331 |
51 | // 返回可提取的ETH数量 | function withdrawETHAmount(uint256 _stepIndex, address _addr) public view returns (uint256) {
return ETHBalance[_stepIndex][_addr]
.add(FissionBalance[_stepIndex][_addr])
.add(FOMOBalance[_stepIndex][_addr])
.add(LuckyBalance[_stepIndex][_addr]);
}
| function withdrawETHAmount(uint256 _stepIndex, address _addr) public view returns (uint256) {
return ETHBalance[_stepIndex][_addr]
.add(FissionBalance[_stepIndex][_addr])
.add(FOMOBalance[_stepIndex][_addr])
.add(LuckyBalance[_stepIndex][_addr]);
}
| 11,104 |
0 | // target contract => calling address => function => permission yes/no TODO: maybe there is a better way to do this | mapping(address => mapping(address => mapping(bytes4 => bool))) authorizations;
| mapping(address => mapping(address => mapping(bytes4 => bool))) authorizations;
| 44,454 |
183 | // Mapping to check if an address has claimed tokens | mapping(address => bool) hasClaimed;
| mapping(address => bool) hasClaimed;
| 70,628 |
17 | // BiFi's safe-math Contract BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) / | library SafeMath {
uint256 internal constant unifiedPoint = 10 ** 18;
/******************** Safe Math********************/
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "a");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "s");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "d");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a* b;
require((c / a) == b, "m");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "d");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "m");
}
}
| library SafeMath {
uint256 internal constant unifiedPoint = 10 ** 18;
/******************** Safe Math********************/
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "a");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "s");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "d");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a* b;
require((c / a) == b, "m");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "d");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "m");
}
}
| 12,531 |
13 | // Add a new liquidity and generate a nft./mintParam params, see MintParam for more/ return lid id of nft/ return liquidity amount of liquidity added/ return amountX amount of tokenX deposited/ return amountY amount of tokenY depsoited | function mint(MintParam calldata mintParam) external payable returns(
uint256 lid,
uint128 liquidity,
uint256 amountX,
uint256 amountY
);
| function mint(MintParam calldata mintParam) external payable returns(
uint256 lid,
uint128 liquidity,
uint256 amountX,
uint256 amountY
);
| 26,727 |
5 | // List of all the registered contracts | address[] public contracts;
| address[] public contracts;
| 40,960 |
22 | // ======================================AXIA EVENTS========================================= |
event NewEpoch(uint epoch, uint emission, uint nextepoch);
event NewDay(uint epoch, uint day, uint nextday);
event BurnEvent(address indexed pool, address indexed burnaddress, uint amount);
event emissions(address indexed root, address indexed pool, uint value);
event TrigRewardEvent(address indexed root, address indexed receiver, uint value);
event BasisPointAdded(uint value);
|
event NewEpoch(uint epoch, uint emission, uint nextepoch);
event NewDay(uint epoch, uint day, uint nextday);
event BurnEvent(address indexed pool, address indexed burnaddress, uint amount);
event emissions(address indexed root, address indexed pool, uint value);
event TrigRewardEvent(address indexed root, address indexed receiver, uint value);
event BasisPointAdded(uint value);
| 34,835 |
80 | // Send to Marketing and Buyback contract | transferToAddressETH(MarketingAddress, transferredBalance.div(SELL_FEE).mul(MarketingDivisor));
transferToAddressETH(BuybackAddress, transferredBalance.div(SELL_FEE).mul(BuybackDivisor));
| transferToAddressETH(MarketingAddress, transferredBalance.div(SELL_FEE).mul(MarketingDivisor));
transferToAddressETH(BuybackAddress, transferredBalance.div(SELL_FEE).mul(BuybackDivisor));
| 43,205 |
15 | // now pay accounts that are constrained by even distribution. we split whatever isleft of the holdover evenly. | uint distAmount = holdoverBalance;
if (totalFundsDistributed < evenDistThresh) {
for (i = 0; i < numAccounts; i++ ) {
if (partnerAccounts[i].evenStart) {
acctDist = distAmount / numEvenSplits;
| uint distAmount = holdoverBalance;
if (totalFundsDistributed < evenDistThresh) {
for (i = 0; i < numAccounts; i++ ) {
if (partnerAccounts[i].evenStart) {
acctDist = distAmount / numEvenSplits;
| 37,135 |
36 | // mark a task a complete and release subcontractor payment.Needs builder,contractor and subcontractor signature. task must be in active state. _data bytes encoded from-- uint256 _taskID the index of task- address _projectAddress the address of this contract. For signature security. _signature bytes representing signature on _data by builder,contractor and subcontractor. / | function setComplete(bytes calldata _data, bytes calldata _signature)
| function setComplete(bytes calldata _data, bytes calldata _signature)
| 6,337 |
0 | // Largest possible fee earned proportion per one second./0.0000001% per second, i.e. 3.1536% per year./0.0000001%(365246060) = 3.1536%/or 3.16224% per year in leap years. | uint256 private constant _MAX_FEE = 10 ** 9;
| uint256 private constant _MAX_FEE = 10 ** 9;
| 12,470 |
148 | // Update the currentLastId with the id in the controller plus the offSet | currentLastId = currentWitnetRequestBoard.postDataRequest{value: msg.value}(_requestAddress) + offset;
| currentLastId = currentWitnetRequestBoard.postDataRequest{value: msg.value}(_requestAddress) + offset;
| 29,106 |
254 | // Clean out ticketExectionHash so the NFT can be reused by ticketeer. | _setnftMetadata(nftIndex, "");
| _setnftMetadata(nftIndex, "");
| 15,015 |
284 | // Checks if a given account holds the Burner role. account The address which is checked for the Burner role.return bool True if the provided account is a Burner. / | function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
| function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
| 17,204 |
112 | // Ensure the previous offer has been removed before refunding | delete tokenIdToOffer[tokenId];
| delete tokenIdToOffer[tokenId];
| 21,010 |
275 | // Returns the current owner of the factory/Can be changed by the current owner via setOwner/ return The address of the factory owner | function owner() external view returns (address);
| function owner() external view returns (address);
| 4,042 |
16 | // Begin of Payment Splitter // this section contains the methods usedto split payment between all collaborators of this project / | contract PaymentSplitter is Ownable{
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
bool private initialized = false;
// @dev attributes for collaborators and investors shares management
uint256 private projectFees;
mapping(address => uint256) private projectInvestments;
address[] private projectInvestors;
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(msg.sender, msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
require(msg.sender == account,"Not authorized");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) /
_totalShares -
_released[account];
require(payment != 0, "Account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
// payable(account).send(payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) internal {
require(
account != address(0),
"Account is the zero address"
);
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(
_shares[account] == 0,
"Account already has shares"
);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
/**
* @dev Return all payees
*/
function getPayees() public view returns (address[] memory) {
return _payees;
}
/**
* @dev Set up all holders shares
* @param payees wallets of holders.
* @param shares_ shares of each holder.
*/
function initializePaymentSplitter(
address[] memory payees,
uint256[] memory shares_
) public onlyOwner {
require(!initialized, "Payment Split Already Initialized!");
require(
payees.length == shares_.length,
"Payees and shares length mismatch"
);
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
initialized = true;
}
/*************** Begin of Collaborators and investors *******************************/
/**
* @dev Add invested fees in the project
* @param investor wallet of investor.
* @param fees share of each holder.
*/
function addProjectFees(address investor, uint256 fees) public onlyOwner {
projectInvestments[investor] = fees;
projectInvestors.push(investor);
projectFees += fees;
}
/**
* @dev if money has been invested in this project, the investment will be reimbursed
* before splitting money between holders
*/
function reimburseProjectFees() public onlyOwner {
require(projectFees != 0, "There are no project fees.");
require(address(this).balance != 0, "Balance is empty");
require(
address(this).balance >= projectFees,
"Balance is not enough to reimburse project fees"
);
for (uint256 i = 0; i < projectInvestors.length; i++) {
require(
payable(projectInvestors[i]).send(
projectInvestments[projectInvestors[i]]
)
);
projectFees -= projectInvestments[projectInvestors[i]];
delete projectInvestments[projectInvestors[i]];
delete projectInvestors[i];
}
}
/*************** End of Collaborators and investors *******************************/
}
| contract PaymentSplitter is Ownable{
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
bool private initialized = false;
// @dev attributes for collaborators and investors shares management
uint256 private projectFees;
mapping(address => uint256) private projectInvestments;
address[] private projectInvestors;
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(msg.sender, msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
require(msg.sender == account,"Not authorized");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) /
_totalShares -
_released[account];
require(payment != 0, "Account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
// payable(account).send(payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) internal {
require(
account != address(0),
"Account is the zero address"
);
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(
_shares[account] == 0,
"Account already has shares"
);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
/**
* @dev Return all payees
*/
function getPayees() public view returns (address[] memory) {
return _payees;
}
/**
* @dev Set up all holders shares
* @param payees wallets of holders.
* @param shares_ shares of each holder.
*/
function initializePaymentSplitter(
address[] memory payees,
uint256[] memory shares_
) public onlyOwner {
require(!initialized, "Payment Split Already Initialized!");
require(
payees.length == shares_.length,
"Payees and shares length mismatch"
);
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
initialized = true;
}
/*************** Begin of Collaborators and investors *******************************/
/**
* @dev Add invested fees in the project
* @param investor wallet of investor.
* @param fees share of each holder.
*/
function addProjectFees(address investor, uint256 fees) public onlyOwner {
projectInvestments[investor] = fees;
projectInvestors.push(investor);
projectFees += fees;
}
/**
* @dev if money has been invested in this project, the investment will be reimbursed
* before splitting money between holders
*/
function reimburseProjectFees() public onlyOwner {
require(projectFees != 0, "There are no project fees.");
require(address(this).balance != 0, "Balance is empty");
require(
address(this).balance >= projectFees,
"Balance is not enough to reimburse project fees"
);
for (uint256 i = 0; i < projectInvestors.length; i++) {
require(
payable(projectInvestors[i]).send(
projectInvestments[projectInvestors[i]]
)
);
projectFees -= projectInvestments[projectInvestors[i]];
delete projectInvestments[projectInvestors[i]];
delete projectInvestors[i];
}
}
/*************** End of Collaborators and investors *******************************/
}
| 24,904 |
92 | // Allows an owner to submit and confirm a token transaction./token address of token SC which supply will b transferred./destination Transaction target address./value Transaction ether value./ return Returns transaction ID. | function submitTokenTransaction(address token, address destination, uint value)
public
ownerExists(msg.sender)
validTokenTransaction(token, destination, value)
returns (uint)
| function submitTokenTransaction(address token, address destination, uint value)
public
ownerExists(msg.sender)
validTokenTransaction(token, destination, value)
returns (uint)
| 34,148 |
125 | // Update reward variables of the given pool to be up-to-date. / | function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (stakedTokenSupply > 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 xbxReward = multiplier.mul(rewardPerBlock);
accTokenPerShare = accTokenPerShare.add(xbxReward.mul(PRECISION_FACTOR).div(stakedTokenSupply));
}
lastRewardBlock = block.number;
}
| function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (stakedTokenSupply > 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 xbxReward = multiplier.mul(rewardPerBlock);
accTokenPerShare = accTokenPerShare.add(xbxReward.mul(PRECISION_FACTOR).div(stakedTokenSupply));
}
lastRewardBlock = block.number;
}
| 19,070 |
25 | // Records amount of AnyswapV3ERC20 token owned by account. | mapping (address => uint256) public override balanceOf;
uint256 private _totalSupply;
| mapping (address => uint256) public override balanceOf;
uint256 private _totalSupply;
| 3,513 |
25 | // Set the price to 0.0003 ETH/CTest1$0.10 per | if (totalSupply < 25000)
{
rate = 3340;
}
| if (totalSupply < 25000)
{
rate = 3340;
}
| 53,507 |
2 | // _paused is used to pause the contract in case of an emergency | bool public _paused;
| bool public _paused;
| 27,227 |
12 | // Update `lastUpdatedEpoch` of `tokenId`. / | function updateNftEpoch(uint256 tokenId) public {
require(msg.sender == masterChef, "invalid address.");
_meta[tokenId].lastUpdatedEpoch = epoch;
}
| function updateNftEpoch(uint256 tokenId) public {
require(msg.sender == masterChef, "invalid address.");
_meta[tokenId].lastUpdatedEpoch = epoch;
}
| 24,278 |
11 | // Community | event TaskCreated(address msgSender, uint _uuid, uint _amount);
event ProjectCreated(address msgSender, uint _uuid, uint _amount, address _address);
| event TaskCreated(address msgSender, uint _uuid, uint _amount);
event ProjectCreated(address msgSender, uint _uuid, uint _amount, address _address);
| 24,230 |
105 | // public method to execute an epoch which required a submission period and the challenge period is over | function executeEpoch() public {
require(block.timestamp >= minChallengePeriodEnd && minChallengePeriodEnd != 0);
_executeEpoch(bestSubmission.seniorRedeem ,bestSubmission.juniorRedeem,
bestSubmission.seniorSupply, bestSubmission.juniorSupply);
}
| function executeEpoch() public {
require(block.timestamp >= minChallengePeriodEnd && minChallengePeriodEnd != 0);
_executeEpoch(bestSubmission.seniorRedeem ,bestSubmission.juniorRedeem,
bestSubmission.seniorSupply, bestSubmission.juniorSupply);
}
| 16,069 |
5 | // vePendle Fees | uint256 public vePendleHarvestCallerFee;
uint256 public protocolFee; // fee charged by penpie team for operation
address public feeCollector; // penpie team fee destination
address public bribeManagerEOA; // An EOA address to later user vePendle harvested reward as bribe
| uint256 public vePendleHarvestCallerFee;
uint256 public protocolFee; // fee charged by penpie team for operation
address public feeCollector; // penpie team fee destination
address public bribeManagerEOA; // An EOA address to later user vePendle harvested reward as bribe
| 24,381 |
50 | // Determine the higher generation number of the two parents | uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
| uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
| 17,782 |
1 | // set expiration to ~4 months from now | _setExpiration(block.timestamp + 124 days);
| _setExpiration(block.timestamp + 124 days);
| 19,530 |
45 | // Checks if a transfer is within the limit. If yes the daily spent is updated._lStorage The storage contract._versionManager The Version Manager._wallet The target wallet._amount The amount for the transfer return true if the transfer is withing the daily limit./ | function checkAndUpdateDailySpent(
ILimitStorage _lStorage,
IVersionManager _versionManager,
address _wallet,
uint256 _amount
)
internal
returns (bool)
| function checkAndUpdateDailySpent(
ILimitStorage _lStorage,
IVersionManager _versionManager,
address _wallet,
uint256 _amount
)
internal
returns (bool)
| 20,267 |
29 | // ``` As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` (`UintSet`) are supported./ | library EnumerableSet {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
| library EnumerableSet {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
| 25,368 |
6 | // check if currentHash hash owner is same and if same then update the value | function updateHash(string memory hashOfIpfs, string memory currentHash, uint16 hashNo) public isHashOwner(currentHash, hashNo) {
_updateHash(hashOfIpfs, hashNo);
}
| function updateHash(string memory hashOfIpfs, string memory currentHash, uint16 hashNo) public isHashOwner(currentHash, hashNo) {
_updateHash(hashOfIpfs, hashNo);
}
| 10,019 |
46 | // ISWswap | address constant MASTERCHEF = 0xEc4fC6599c5e64F6e320d3C098Fb9CAFbA7B9273;
| address constant MASTERCHEF = 0xEc4fC6599c5e64F6e320d3C098Fb9CAFbA7B9273;
| 70,780 |
316 | // Mint crate character | mintToken(crate, characterTypeId);
emit CreatePurchased(keccak256(abi.encodePacked(_crateId)), msg.sender, characterTypeId);
| mintToken(crate, characterTypeId);
emit CreatePurchased(keccak256(abi.encodePacked(_crateId)), msg.sender, characterTypeId);
| 47,251 |
121 | // Function to get the number of ACO creators forbidden for a pool.return The number of ACO creators forbidden. / | function getNumberOfAcoCreatorsForbidden() view external virtual returns(uint256) {
return acoForbiddenCreators.length;
}
| function getNumberOfAcoCreatorsForbidden() view external virtual returns(uint256) {
return acoForbiddenCreators.length;
}
| 35,752 |
104 | // called when a horsey is freed for carrots | event HorseyFreed(uint256 tokenId);
| event HorseyFreed(uint256 tokenId);
| 841 |
5,954 | // 2979 | entry "thermionically" : ENG_ADVERB
| entry "thermionically" : ENG_ADVERB
| 23,815 |
123 | // RULE: Inferred Signature Type (0) must have the correct signature length in the public key RULE: Padded Signature Type (2) must have the correct signature length in the public key RULE: Constant-Time Signature Type (3) must have the correct signature length in the public key | if ( ((signatureType == FALCON_SIG_1_COMPRESSED) && (cbSignatureBuf > FALCON_SIG_COMPRESSED_MAXSIZE[pubKey_bits_nnnn])) ||
((signatureType == FALCON_SIG_2_PADDED ) && (cbSignatureBuf != FALCON_SIG_PADDED_SIZE [pubKey_bits_nnnn])) ||
((signatureType == FALCON_SIG_3_CT ) && (cbSignatureBuf != FALCON_SIG_CT_SIZE [pubKey_bits_nnnn])) )
{
return FALCON_ERR_SIZE + (-120);
}
| if ( ((signatureType == FALCON_SIG_1_COMPRESSED) && (cbSignatureBuf > FALCON_SIG_COMPRESSED_MAXSIZE[pubKey_bits_nnnn])) ||
((signatureType == FALCON_SIG_2_PADDED ) && (cbSignatureBuf != FALCON_SIG_PADDED_SIZE [pubKey_bits_nnnn])) ||
((signatureType == FALCON_SIG_3_CT ) && (cbSignatureBuf != FALCON_SIG_CT_SIZE [pubKey_bits_nnnn])) )
{
return FALCON_ERR_SIZE + (-120);
}
| 47,343 |
169 | // project addresses | address cat1 = 0x1BC73bB97D25657928Dd8cd54E6cD12672bf4523; //Ready_B
address cat2 = 0x6CCE79E7A8cfC0300D45A7587FBf0E07527336D1; //Ready_D
address cat3 = 0x44AFC4bdF2de4e1d6bFC7cad759483d18befa168; //Ready_R
address cat4 = 0x6798EE3EABe1f7045BE7F0dDF958D12F121BA92b; // MAKE THIS THE DEPLOYER WALLET
| address cat1 = 0x1BC73bB97D25657928Dd8cd54E6cD12672bf4523; //Ready_B
address cat2 = 0x6CCE79E7A8cfC0300D45A7587FBf0E07527336D1; //Ready_D
address cat3 = 0x44AFC4bdF2de4e1d6bFC7cad759483d18befa168; //Ready_R
address cat4 = 0x6798EE3EABe1f7045BE7F0dDF958D12F121BA92b; // MAKE THIS THE DEPLOYER WALLET
| 78,386 |
18 | // Get info of a pool | function getPoolInfo(uint8 _orderNumber) public view returns (
address _pool,
address _manager,
address _fundWallet
| function getPoolInfo(uint8 _orderNumber) public view returns (
address _pool,
address _manager,
address _fundWallet
| 30,073 |
292 | // calculates how many keys would exist with given an amount of eth _eth eth "in contract"return number of keys that would exist / | function keys(uint256 _eth)
internal
pure
returns(uint256)
| function keys(uint256 _eth)
internal
pure
returns(uint256)
| 21,208 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.