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 |
|---|---|---|---|---|
68 | // address 0x0 is not valid if pos is 0 is not in the array | if (_stakeHolder != address(0) && stakeHolders[_stakeHolder] > 0) {
return true;
}
| if (_stakeHolder != address(0) && stakeHolders[_stakeHolder] > 0) {
return true;
}
| 17,503 |
236 | // get the values of each point in the tri (flipped as required) | int256 f = (flip) ? int256(-1) : int256(1);
int256 a = f * tri[0][axis];
int256 b = f * tri[1][axis];
int256 c = f * tri[2][axis];
| int256 f = (flip) ? int256(-1) : int256(1);
int256 a = f * tri[0][axis];
int256 b = f * tri[1][axis];
int256 c = f * tri[2][axis];
| 72,039 |
16 | // 15 000 000 tokens on sale during the ICO | uint public constant ICO_TOKEN_SUPPLY_LIMIT = 15000000 * 1 ether;
| uint public constant ICO_TOKEN_SUPPLY_LIMIT = 15000000 * 1 ether;
| 11,107 |
41 | // This is internal function is equivalent to {transfer}, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address.- `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`. / | function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
| function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
| 121 |
0 | // Admiration System:View App for details. / |
function admireNft(
string memory target,
string memory invoker
) external virtual {
Storage storage s = getStorage();
|
function admireNft(
string memory target,
string memory invoker
) external virtual {
Storage storage s = getStorage();
| 1,173 |
50 | // Allows payer or receiver to stop existing payments for a given paymentId paymentId The payment id for a payment stopTime Timestamp to stop payment, if 0 use current block.timestamp / | function stopPayment(uint256 paymentId, uint48 stopTime) external nonReentrant {
Payment storage payment = tokenPayments[paymentId];
require(msg.sender == payment.payer || msg.sender == payment.receiver, "Payments::stopPayment: msg.sender must be payer or receiver");
require(payment.stopTime == 0, "Payments::stopPayment: payment already stopped");
stopTime = stopTime == 0 ? uint48(block.timestamp) : stopTime;
require(stopTime < payment.startTime + payment.paymentDurationInSecs, "Payments::stopPayment: stop time > payment duration");
if(stopTime > payment.startTime) {
payment.stopTime = stopTime;
uint256 newPaymentDuration = stopTime - payment.startTime;
uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs;
uint256 newPaymentAmount = paymentAmountPerSec * newPaymentDuration;
IERC20(payment.token).safeTransfer(payment.payer, payment.amount - newPaymentAmount);
emit PaymentStopped(paymentId, payment.paymentDurationInSecs, stopTime, payment.startTime);
} else {
payment.stopTime = payment.startTime;
IERC20(payment.token).safeTransfer(payment.payer, payment.amount);
emit PaymentStopped(paymentId, payment.paymentDurationInSecs, payment.startTime, payment.startTime);
}
}
| function stopPayment(uint256 paymentId, uint48 stopTime) external nonReentrant {
Payment storage payment = tokenPayments[paymentId];
require(msg.sender == payment.payer || msg.sender == payment.receiver, "Payments::stopPayment: msg.sender must be payer or receiver");
require(payment.stopTime == 0, "Payments::stopPayment: payment already stopped");
stopTime = stopTime == 0 ? uint48(block.timestamp) : stopTime;
require(stopTime < payment.startTime + payment.paymentDurationInSecs, "Payments::stopPayment: stop time > payment duration");
if(stopTime > payment.startTime) {
payment.stopTime = stopTime;
uint256 newPaymentDuration = stopTime - payment.startTime;
uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs;
uint256 newPaymentAmount = paymentAmountPerSec * newPaymentDuration;
IERC20(payment.token).safeTransfer(payment.payer, payment.amount - newPaymentAmount);
emit PaymentStopped(paymentId, payment.paymentDurationInSecs, stopTime, payment.startTime);
} else {
payment.stopTime = payment.startTime;
IERC20(payment.token).safeTransfer(payment.payer, payment.amount);
emit PaymentStopped(paymentId, payment.paymentDurationInSecs, payment.startTime, payment.startTime);
}
}
| 36,268 |
3 | // uint256 _instantBuyout, | uint256 _startBlock,
uint256 _endBlock,
string memory _imgUrl
| uint256 _startBlock,
uint256 _endBlock,
string memory _imgUrl
| 24,348 |
91 | // if mint success, add the share | if(mintRet) {
pool.accChickenPerShare = pool.accChickenPerShare.add(chickenReward.mul(1e12).div(lpSupply));
}
| if(mintRet) {
pool.accChickenPerShare = pool.accChickenPerShare.add(chickenReward.mul(1e12).div(lpSupply));
}
| 9,892 |
18 | // Convert quadruple precision number into signed 64.64 bit fixed pointnumber.Revert on overflow.x quadruple precision numberreturn signed 64.64 bit fixed point number / | function to64x64(bytes16 x) internal pure returns (int128) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446,"ABDK Quad9: Overflow"); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000,"ABDK Quad10");
return -int128(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,"ABDK Quad11");
return int128(result);
}
}
| function to64x64(bytes16 x) internal pure returns (int128) {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446,"ABDK Quad9: Overflow"); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000,"ABDK Quad10");
return -int128(result); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,"ABDK Quad11");
return int128(result);
}
}
| 9,643 |
24 | // For freeupto | ApproveInf(CHITOKEN,CHITOKEN);
| ApproveInf(CHITOKEN,CHITOKEN);
| 5,267 |
26 | // getBountyArbiter(): Returns the arbiter of the bounty/_bountyId the index of the bounty/ return Returns an address for the arbiter of the bounty | function getBountyArbiter(uint _bountyId) public constant returns (address);
| function getBountyArbiter(uint _bountyId) public constant returns (address);
| 47,403 |
140 | // True if epoch has been wound down already | mapping(uint256=>bool) public epoch_wound_down;
uint256 public last_deploy; // Last run of Hourly Deploy
uint256 public deploy_interval; // Hourly deploy interval
| mapping(uint256=>bool) public epoch_wound_down;
uint256 public last_deploy; // Last run of Hourly Deploy
uint256 public deploy_interval; // Hourly deploy interval
| 39,191 |
5,476 | // 2740 | entry "nonthreateningly" : ENG_ADVERB
| entry "nonthreateningly" : ENG_ADVERB
| 23,576 |
573 | // Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds adelay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The{Governor} needs the proposer (and ideally the executor) roles for the {Governor} to work properly.Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus,the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will begrants them powers that they must be trusted or known not to use: 1) {onlyGovernance} functions like {relay} are/ Emitted when the | event TimelockChange(address oldTimelock, address newTimelock);
| event TimelockChange(address oldTimelock, address newTimelock);
| 28,065 |
8 | // Transfer tokens (requires previous approval) | depositToken.safeTransferFrom(msg.sender, address(this), amountToPay);
| depositToken.safeTransferFrom(msg.sender, address(this), amountToPay);
| 48,479 |
82 | // details for the given aggregator round _roundId target aggregator round (NOT OCR round). Must fit in uint32return roundId _roundIdreturn answer median of report from given _roundIdreturn startedAt timestamp of block in which report from given _roundId was transmittedreturn updatedAt timestamp of block in which report from given _roundId was transmittedreturn answeredInRound _roundId / | function getRoundData(uint80 _roundId)
public
override
view
virtual
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
| function getRoundData(uint80 _roundId)
public
override
view
virtual
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
| 11,611 |
254 | // Update position units on index. Emit event. / | function _updatePositionState(
address _sellComponent,
address _buyComponent,
uint256 _preTradeSellComponentAmount,
uint256 _preTradeBuyComponentAmount
)
internal
returns (uint256 sellAmount, uint256 buyAmount)
| function _updatePositionState(
address _sellComponent,
address _buyComponent,
uint256 _preTradeSellComponentAmount,
uint256 _preTradeBuyComponentAmount
)
internal
returns (uint256 sellAmount, uint256 buyAmount)
| 8,056 |
108 | // set buy fees/ marketing - set marketing fees/ ref - set reflection fees/Requirements --/ total buy fees must be less than equal to 5 percent. | function setBuyFee( uint16 marketing, uint16 ref) external onlyOwner {
buyFee.marketingFee = marketing;
buyFee.reflectionFee = ref;
uint256 totalBuyFee = marketing + ref ;
require(totalBuyFee <= 5, "max buy fees limit is 5%");
}
| function setBuyFee( uint16 marketing, uint16 ref) external onlyOwner {
buyFee.marketingFee = marketing;
buyFee.reflectionFee = ref;
uint256 totalBuyFee = marketing + ref ;
require(totalBuyFee <= 5, "max buy fees limit is 5%");
}
| 27,344 |
3 | // burns existing talent tokens | function burn(address _owner, uint256 _amount) external;
| function burn(address _owner, uint256 _amount) external;
| 27,947 |
413 | // Not a system contract | uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72;
| uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72;
| 15,770 |
211 | // bytes4(keccak256("isValidSignature(bytes32,bytes)") | bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
| bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
| 36,742 |
2 | // Get sales partner percent by partner address./ | function getSalesPartnerPercent(address) public view returns (uint8) {}
| function getSalesPartnerPercent(address) public view returns (uint8) {}
| 2,474 |
201 | // Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. | function balanceOf() public virtual view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
| function balanceOf() public virtual view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
| 10,622 |
2 | // Changes Controller contract to a new addressNote: this function is only callable by the Governance contract. _newController is the address of the new Controller contract / | function changeControllerContract(address _newController) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the Controller contract address"
);
require(_isValid(_newController));
| function changeControllerContract(address _newController) external {
require(
msg.sender == addresses[_GOVERNANCE_CONTRACT],
"Only the Governance contract can change the Controller contract address"
);
require(_isValid(_newController));
| 63,256 |
11 | // Emits a {QuorumNumeratorUpdated} event. Requirements: - Must be called through a governance proposal.- New numerator must be smaller or equal to the denominator. / | function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance {
_updateQuorumNumerator(newQuorumNumerator);
}
| function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance {
_updateQuorumNumerator(newQuorumNumerator);
}
| 37,550 |
5 | // destinationChainSelector The destination chain selector/message The cross-chain CCIP message including data and/or tokens/ return fee returns execution fee for the specified message/ delivery to destination chain/returns 0 fee on invalid message. | function getFee(
uint64 destinationChainSelector,
Client.EVM2AnyMessage memory message
) external view returns (uint256 fee);
| function getFee(
uint64 destinationChainSelector,
Client.EVM2AnyMessage memory message
) external view returns (uint256 fee);
| 30,723 |
12 | // default to token resolution but use global if no delegation | Delegation memory _tokenDlgt = tokenDlgts[tokenContract][voter];
if (tokenContract == address(0)) {
_tokenDlgt = globalDlgts[voter];
}
| Delegation memory _tokenDlgt = tokenDlgts[tokenContract][voter];
if (tokenContract == address(0)) {
_tokenDlgt = globalDlgts[voter];
}
| 250 |
28 | // ERC20 compliant transfer | emit Transfer(msg.sender, _to, _value);
return true;
| emit Transfer(msg.sender, _to, _value);
return true;
| 27,985 |
28 | // Delete the order | require(DataInterface(getDataContractAddress()).editOrdersAmount(user, DataInterface(getDataContractAddress()).getUserAmount(user, true) - amount, true));
require(DataInterface(getDataContractAddress()).editOrdersArray(user, false, true, _storeOfValue, _orderId));
require(DataInterface(getDataContractAddress()).removeSpecificOpenOrder(_orderId, _storeOfValue));
require(DataInterface(getDataContractAddress()).editOpenOrder(_orderId, _storeOfValue, 0));
| require(DataInterface(getDataContractAddress()).editOrdersAmount(user, DataInterface(getDataContractAddress()).getUserAmount(user, true) - amount, true));
require(DataInterface(getDataContractAddress()).editOrdersArray(user, false, true, _storeOfValue, _orderId));
require(DataInterface(getDataContractAddress()).removeSpecificOpenOrder(_orderId, _storeOfValue));
require(DataInterface(getDataContractAddress()).editOpenOrder(_orderId, _storeOfValue, 0));
| 16,775 |
131 | // Base URI for computing {tokenURI}. If set, the resulting URI for eachtoken will be the concatenation of the `baseURI` and the `tokenId`. Emptyby default, can be overriden in child contracts. / | function _baseURI() internal view virtual returns (string memory) {
return "";
}
| function _baseURI() internal view virtual returns (string memory) {
return "";
}
| 7,833 |
37 | // Calculating r, the point at which to evaluate the interpolating polynomial | uint256 r = uint256(
keccak256(
abi.encodePacked(
keccak256(poly),
multiRevealProof.interpolationPoly.X,
multiRevealProof.interpolationPoly.Y
)
)
) % MODULUS;
uint256 s = linearPolynomialEvaluation(poly, r);
| uint256 r = uint256(
keccak256(
abi.encodePacked(
keccak256(poly),
multiRevealProof.interpolationPoly.X,
multiRevealProof.interpolationPoly.Y
)
)
) % MODULUS;
uint256 s = linearPolynomialEvaluation(poly, r);
| 1,817 |
136 | // mint shares at current rate | uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(INITIAL_SHARES_PER_TOKEN);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
| uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(INITIAL_SHARES_PER_TOKEN);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
| 1,574 |
23 | // If there are bigger bids than this, remove the link to this one as the next bid | if (prevBidder != address(0)) {
nextBidders[tokenId][prevBidder] = nextBidder;
}
| if (prevBidder != address(0)) {
nextBidders[tokenId][prevBidder] = nextBidder;
}
| 79,982 |
33 | // Changes requirement for minimal amount of signatures to validate on transfer_minConfirmationSignatures Number of signatures to verify/ | function setMinConfirmationSignatures(uint256 _minConfirmationSignatures) external onlyOwner {
require(_minConfirmationSignatures > 0, "swapContract: At least 1 confirmation can be set");
minConfirmationSignatures = _minConfirmationSignatures;
}
| function setMinConfirmationSignatures(uint256 _minConfirmationSignatures) external onlyOwner {
require(_minConfirmationSignatures > 0, "swapContract: At least 1 confirmation can be set");
minConfirmationSignatures = _minConfirmationSignatures;
}
| 5,425 |
30 | // enum of current crowd sale state / | enum Stages {
none,
icoStart,
icoEnd
}
| enum Stages {
none,
icoStart,
icoEnd
}
| 21,210 |
38 | // pays out the players./ | function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
| function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
| 3,274 |
27 | // Sets OST rewards per EC Mint. _ostRewardPerMintOST rewards per EC Mint. / | function setOSTRewardPerMint(uint256 _ostRewardPerMint) external onlyOwner {
ostRewardPerMint = _ostRewardPerMint;
}
| function setOSTRewardPerMint(uint256 _ostRewardPerMint) external onlyOwner {
ostRewardPerMint = _ostRewardPerMint;
}
| 18,730 |
16 | // (9) 거래 내역 갱신 | function updateHistory(address _member, uint256 _value) onlyCoin public {
tradingHistory[_member].times += 1;
tradingHistory[_member].sum += _value;
// 새로운 회원 등급 결정(거래마다 실행)
uint256 index;
int8 tmprate;
for (uint i = 0; i < status.length; i++) {
// 최저 거래 횟수, 최저 거래 금액 충족 시 가장 캐시백 비율이 좋은 등급으로 설정
if (tradingHistory[_member].times >= status[i].times &&
tradingHistory[_member].sum >= status[i].sum &&
tmprate < status[i].rate) {
index = i;
}
}
tradingHistory[_member].statusIndex = index;
}
| function updateHistory(address _member, uint256 _value) onlyCoin public {
tradingHistory[_member].times += 1;
tradingHistory[_member].sum += _value;
// 새로운 회원 등급 결정(거래마다 실행)
uint256 index;
int8 tmprate;
for (uint i = 0; i < status.length; i++) {
// 최저 거래 횟수, 최저 거래 금액 충족 시 가장 캐시백 비율이 좋은 등급으로 설정
if (tradingHistory[_member].times >= status[i].times &&
tradingHistory[_member].sum >= status[i].sum &&
tmprate < status[i].rate) {
index = i;
}
}
tradingHistory[_member].statusIndex = index;
}
| 22,976 |
220 | // Workaround for issue https:github.com/ethereum/solidity/issues/526 CEther | contract IAvatarCEther is IAvatar {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
| contract IAvatarCEther is IAvatar {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
| 28,418 |
42 | // to get the volume bonus amount given the token amount to be collected from contribution and the ether amount contributed_tokenAmount token amount to be collected from contribution_etherAmount ether amount contributed/ | function getVolumeBonusAmount(uint256 _tokenAmount, uint256 _etherAmount) private returns (uint256) {
return _tokenAmount.mul256(getVolumeBonusPercent(_etherAmount)).div256(100);
}
| function getVolumeBonusAmount(uint256 _tokenAmount, uint256 _etherAmount) private returns (uint256) {
return _tokenAmount.mul256(getVolumeBonusPercent(_etherAmount)).div256(100);
}
| 51,069 |
3 | // Validation | mapping(uint16 => mapping(uint16 => address)) public inboundProofLibrary; // chainId => library Id => inboundProofLibrary contract
mapping(uint16 => uint16) public maxInboundProofLibrary; // chainId => inboundProofLibrary
mapping(uint16 => mapping(uint16 => bool)) public supportedOutboundProof; // chainId => outboundProofType => enabled
mapping(uint16 => uint) public chainAddressSizeMap;
mapping(address => mapping(uint16 => mapping(bytes32 => mapping(bytes32 => uint)))) public hashLookup; //[oracle][srcChainId][blockhash][datahash] -> confirmation
mapping(uint16 => bytes32) public ulnLookup; // remote ulns
ILayerZeroEndpoint public immutable endpoint;
uint16 public immutable localChainId;
NonceContract public immutable nonceContract;
| mapping(uint16 => mapping(uint16 => address)) public inboundProofLibrary; // chainId => library Id => inboundProofLibrary contract
mapping(uint16 => uint16) public maxInboundProofLibrary; // chainId => inboundProofLibrary
mapping(uint16 => mapping(uint16 => bool)) public supportedOutboundProof; // chainId => outboundProofType => enabled
mapping(uint16 => uint) public chainAddressSizeMap;
mapping(address => mapping(uint16 => mapping(bytes32 => mapping(bytes32 => uint)))) public hashLookup; //[oracle][srcChainId][blockhash][datahash] -> confirmation
mapping(uint16 => bytes32) public ulnLookup; // remote ulns
ILayerZeroEndpoint public immutable endpoint;
uint16 public immutable localChainId;
NonceContract public immutable nonceContract;
| 17,481 |
43 | // // Transferable tokenStandardToken modified with transfert on/off mechanism. / | contract TransferableToken is StandardToken,Ownable {
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @dev TRANSFERABLE MECANISM SECTION
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/
event Transferable();
event UnTransferable();
bool public transferable = false;
mapping (address => bool) public whitelisted;
/**
CONSTRUCTOR
**/
constructor()
StandardToken()
Ownable()
public
{
whitelisted[msg.sender] = true;
}
/**
MODIFIERS
**/
/**
* @dev Modifier to make a function callable only when the contract is not transferable.
*/
modifier whenNotTransferable() {
require(!transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is transferable.
*/
modifier whenTransferable() {
require(transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the caller can transfert token.
*/
modifier canTransfert() {
if(!transferable){
require (whitelisted[msg.sender]);
}
_;
}
/**
OWNER ONLY FUNCTIONS
**/
/**
* @dev called by the owner to allow transferts, triggers Transferable state
*/
function allowTransfert() onlyOwner whenNotTransferable public {
transferable = true;
emit Transferable();
}
/**
* @dev called by the owner to restrict transferts, returns to untransferable state
*/
function restrictTransfert() onlyOwner whenTransferable public {
transferable = false;
emit UnTransferable();
}
/**
@dev Allows the owner to add addresse that can bypass the transfer lock.
**/
function whitelist(address _address) onlyOwner public {
require(_address != 0x0);
whitelisted[_address] = true;
}
/**
@dev Allows the owner to remove addresse that can bypass the transfer lock.
**/
function restrict(address _address) onlyOwner public {
require(_address != 0x0);
whitelisted[_address] = false;
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @dev Strandard transferts overloaded API
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/
function transfer(address _to, uint256 _value) public canTransfert returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public canTransfert returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. We recommend to use use increaseApproval
* and decreaseApproval functions instead !
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263555598
*/
function approve(address _spender, uint256 _value) public canTransfert returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public canTransfert returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public canTransfert returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
| contract TransferableToken is StandardToken,Ownable {
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @dev TRANSFERABLE MECANISM SECTION
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/
event Transferable();
event UnTransferable();
bool public transferable = false;
mapping (address => bool) public whitelisted;
/**
CONSTRUCTOR
**/
constructor()
StandardToken()
Ownable()
public
{
whitelisted[msg.sender] = true;
}
/**
MODIFIERS
**/
/**
* @dev Modifier to make a function callable only when the contract is not transferable.
*/
modifier whenNotTransferable() {
require(!transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is transferable.
*/
modifier whenTransferable() {
require(transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the caller can transfert token.
*/
modifier canTransfert() {
if(!transferable){
require (whitelisted[msg.sender]);
}
_;
}
/**
OWNER ONLY FUNCTIONS
**/
/**
* @dev called by the owner to allow transferts, triggers Transferable state
*/
function allowTransfert() onlyOwner whenNotTransferable public {
transferable = true;
emit Transferable();
}
/**
* @dev called by the owner to restrict transferts, returns to untransferable state
*/
function restrictTransfert() onlyOwner whenTransferable public {
transferable = false;
emit UnTransferable();
}
/**
@dev Allows the owner to add addresse that can bypass the transfer lock.
**/
function whitelist(address _address) onlyOwner public {
require(_address != 0x0);
whitelisted[_address] = true;
}
/**
@dev Allows the owner to remove addresse that can bypass the transfer lock.
**/
function restrict(address _address) onlyOwner public {
require(_address != 0x0);
whitelisted[_address] = false;
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @dev Strandard transferts overloaded API
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/
function transfer(address _to, uint256 _value) public canTransfert returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public canTransfert returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. We recommend to use use increaseApproval
* and decreaseApproval functions instead !
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263555598
*/
function approve(address _spender, uint256 _value) public canTransfert returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public canTransfert returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public canTransfert returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
| 14,921 |
55 | // view the amount of stake that the sender currently has./ | function viewStake() public
view
| function viewStake() public
view
| 50,050 |
158 | // With `magnitude`, we can properly distribute rewards even if the amount of received ether is small. For more discussion about choosing the value of `magnitude`, see https:github.com/ethereum/EIPs/issues/1726issuecomment-472352728 | uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedRewardPerShare;
| uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedRewardPerShare;
| 68,420 |
1 | // See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)} | function isApprovedForAll(address tokenOwner, address operator) external view override(IERC721, IERC1155) returns (bool);
| function isApprovedForAll(address tokenOwner, address operator) external view override(IERC721, IERC1155) returns (bool);
| 26,977 |
50 | // Checks whether an address is whitelisted in the competition contract and competition is active/x Address/ return Whether the address is whitelisted | function isCompetitionAllowed(
address x
)
view
returns (bool)
| function isCompetitionAllowed(
address x
)
view
returns (bool)
| 35,284 |
43 | // No balance, nothing to do here | if (assetBalance == 0) continue;
| if (assetBalance == 0) continue;
| 15,394 |
116 | // return This TempusPool's Tempus Principal Share (TPS) | function principalShare() external view returns (IPoolShare);
| function principalShare() external view returns (IPoolShare);
| 30,036 |
204 | // Calculates cumulative sum of the holders reward per Property.caution!!!this function is deprecated!!!use calculateRewardAmount / | function calculateCumulativeHoldersRewardAmount(address _property)
external
view
returns (uint256)
| function calculateCumulativeHoldersRewardAmount(address _property)
external
view
returns (uint256)
| 10,617 |
100 | // A long string contains all of the key allKeysInString/ string public allKeysInString; / | {
setData(offset, buffer);
}
| {
setData(offset, buffer);
}
| 22,974 |
24 | // Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _spender address The address which will spend the funds. / | function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| 8,078 |
6 | // valid account | uint256 private VALID_ACCOUNT_VALUE = 5 ether;
| uint256 private VALID_ACCOUNT_VALUE = 5 ether;
| 40,216 |
176 | // (omnuum contract address => (bytes32 topic => hasRole)) | mapping(address => mapping(string => bool)) public roles;
| mapping(address => mapping(string => bool)) public roles;
| 67,008 |
106 | // Fallback function for the contract. Used by proxies to read the implementation address and usedby the proxy manager to set the implementation address. If called by the owner, reads the implementation address fromcalldata (must be abi-encoded) and stores it to the first slot. Otherwise, returns the stored implementation address. / | fallback() external payable {
if (msg.sender != _manager) {
assembly {
mstore(0, sload(0))
return(0, 32)
}
}
assembly { sstore(0, calldataload(0)) }
}
| fallback() external payable {
if (msg.sender != _manager) {
assembly {
mstore(0, sload(0))
return(0, 32)
}
}
assembly { sstore(0, calldataload(0)) }
}
| 42,549 |
235 | // If there is a connector, check the balance and settle to the specified fraction % | IConnector connector_ = connector;
if (address(connector_) != address(0)) {
| IConnector connector_ = connector;
if (address(connector_) != address(0)) {
| 29,696 |
22 | // Get bit at position 0 | uint32 sign = bytesValue & 0x8000;
| uint32 sign = bytesValue & 0x8000;
| 47,481 |
14 | // only after the waiting period, can/proposed protocol complete the transfer | function completeProtocolTransfer()
public
onlyProposedProtocol
afterWait
returns (bool)
| function completeProtocolTransfer()
public
onlyProposedProtocol
afterWait
returns (bool)
| 43,123 |
5 | // Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend)./ | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| 29,970 |
250 | // Check the on-chain authorization | S.requireAuthorizedTx(update.owner, auxData.signature, txHash);
| S.requireAuthorizedTx(update.owner, auxData.signature, txHash);
| 36,758 |
485 | // Delegate all of `account`'s voting units to `delegatee`. | * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address account, address delegatee) internal virtual {
address oldDelegate = delegates(account);
_delegatee[account] = delegatee;
emit DelegateChanged(account, oldDelegate, delegatee);
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
}
| * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address account, address delegatee) internal virtual {
address oldDelegate = delegates(account);
_delegatee[account] = delegatee;
emit DelegateChanged(account, oldDelegate, delegatee);
_moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
}
| 36,548 |
102 | // Convert a standard decimal representation to a high precision one. / | function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
| function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
| 2,235 |
519 | // Accepts the role as governance.// This function reverts if the caller is not the new pending governance. | function acceptGovernance() external {
require(msg.sender == pendingGovernance,"!pendingGovernance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
| function acceptGovernance() external {
require(msg.sender == pendingGovernance,"!pendingGovernance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
| 15,882 |
273 | // repay debt if iron bank wants it back | if(remainingCredit < outstandingDebt){
borrowMore = false;
amount = outstandingDebt - remainingCredit;
}
| if(remainingCredit < outstandingDebt){
borrowMore = false;
amount = outstandingDebt - remainingCredit;
}
| 20,546 |
12 | // Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) | function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
| function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
| 21,409 |
177 | // ``` As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) aresupported. / | library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
| library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
| 23,019 |
45 | // Performs a call to purchase an ERC1155, then transfers the ERC1155 to a specified recipient/inputs The inputs for the protocol and ERC1155 transfer, encoded/protocol The protocol to pass the calldata to/ return success True on success of the command, false on failure/ return output The outputs or error messages, if any, from the command | function callAndTransfer1155(bytes calldata inputs, address protocol)
internal
returns (bool success, bytes memory output)
| function callAndTransfer1155(bytes calldata inputs, address protocol)
internal
returns (bool success, bytes memory output)
| 105 |
7 | // Set the contract address | metadataContractAddress = _address;
| metadataContractAddress = _address;
| 11,461 |
42 | // Assemble input data into structs so we can pass them to other functions. This method also calculates ringHash, therefore it must be called before calling `verifyRingSignatures`. | TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress);
OrderState[] memory orders = assembleOrders(
params,
delegate,
addressList,
uintArgsList,
uint8ArgsList,
buyNoMoreThanAmountBList
);
verifyRingSignatures(params, orders);
| TokenTransferDelegate delegate = TokenTransferDelegate(delegateAddress);
OrderState[] memory orders = assembleOrders(
params,
delegate,
addressList,
uintArgsList,
uint8ArgsList,
buyNoMoreThanAmountBList
);
verifyRingSignatures(params, orders);
| 47,543 |
23 | // The withdraw function is a function with which investors can withdraw their funds in a tradingContract. Theapplicable fees will be calculated in this function. | function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
// Check for equity in pairedToken, and swap the investor fraction into ETH.
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
// Check for equity in baseToken, and swap the investor fraction into ETH.
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
//calculate the total equity of the investor.
uint256 _equity = _swappedAmountBase.add(_swappedAmountPaired);
//In case of positive revenue, calculate and transfer the developer and the platform fee.
//Notice that revenue will be calculated in ETH (invested amount in ETH subtracted by final equity in ETH)
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
//Send remaining equity to the investor.
msg.sender.transfer(_equity);
//Update all fractions of all the investors.
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
| function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
// Check for equity in pairedToken, and swap the investor fraction into ETH.
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
// Check for equity in baseToken, and swap the investor fraction into ETH.
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
//calculate the total equity of the investor.
uint256 _equity = _swappedAmountBase.add(_swappedAmountPaired);
//In case of positive revenue, calculate and transfer the developer and the platform fee.
//Notice that revenue will be calculated in ETH (invested amount in ETH subtracted by final equity in ETH)
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
//Send remaining equity to the investor.
msg.sender.transfer(_equity);
//Update all fractions of all the investors.
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
| 25,333 |
85 | // Check for cancellation | bytes32 hash = hashOffer(offer);
require(cancelledOffers[hash] == false, "Trade offer was cancelled.");
| bytes32 hash = hashOffer(offer);
require(cancelledOffers[hash] == false, "Trade offer was cancelled.");
| 34,077 |
8 | // 指定の id の TODO をアップデートする | todos[_id].is_opened = _is_opened;
| todos[_id].is_opened = _is_opened;
| 28,541 |
65 | // Function to allow curator to redeem accumulated curator fee./_to the address where curator fee will be sent/can only be called by curator | function redeemCuratorFee(address payable _to) external override onlyCurator returns(uint256 _feeAccruedCurator) {
_feeAccruedCurator = feeAccruedCurator;
feeAccruedCurator = 0;
safeTransferETH(_to, _feeAccruedCurator);
}
| function redeemCuratorFee(address payable _to) external override onlyCurator returns(uint256 _feeAccruedCurator) {
_feeAccruedCurator = feeAccruedCurator;
feeAccruedCurator = 0;
safeTransferETH(_to, _feeAccruedCurator);
}
| 8,721 |
13 | // Query linked list for specified days of data. Will revert if number of dayspassed exceeds amount of days collected. Will revert if not enough days ofdata logged. _numDataPointsNumber of datapoints to queryreturnsArray of datapoints of length _numDataPoints from most recent to oldest/ | function read(
uint256 _numDataPoints
)
external
view
returns (uint256[] memory)
| function read(
uint256 _numDataPoints
)
external
view
returns (uint256[] memory)
| 38,675 |
1 | // use mapping to get or fetch the contestant details | mapping(uint => Contestant) public contestants;
| mapping(uint => Contestant) public contestants;
| 6,888 |
157 | // Get the hero&39;s entire infomation. | function getHeroInfo(uint256 _tokenId)
external view
returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp)
| function getHeroInfo(uint256 _tokenId)
external view
returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp)
| 38,559 |
6 | // Creator royalty Fee is fixed to be 1% of sales, org fee to be 1% and black unicorn to 0.5%Multiply all the three % variables by 100, to kepe it uniform | orgFee = 100;
creatorFee = 100;
blackUniFee = 50;
sellerFee = 10000 - orgFee - creatorFee - blackUniFee;
| orgFee = 100;
creatorFee = 100;
blackUniFee = 50;
sellerFee = 10000 - orgFee - creatorFee - blackUniFee;
| 34,567 |
254 | // Retrieve reward slippage slotsreturn Reward slippage slots / | function _getRewardSlippageSlots() internal view virtual returns(uint256) {
return rewardSlippageSlots;
}
| function _getRewardSlippageSlots() internal view virtual returns(uint256) {
return rewardSlippageSlots;
}
| 34,271 |
31 | // Allows the developer to shut down everything except withdrawals in emergencies. | function activate_kill_switch() {
// Only allow the developer to activate the kill switch.
if (msg.sender != developer_address) throw;
// Irreversibly activate the kill switch.
kill_switch = true;
}
| function activate_kill_switch() {
// Only allow the developer to activate the kill switch.
if (msg.sender != developer_address) throw;
// Irreversibly activate the kill switch.
kill_switch = true;
}
| 47,632 |
10 | // Transfer the partial ownership shares | transferPartialOwnership(assetId, msg.sender, shares);
emit AssetPurchased(msg.sender, assetId, shares, totalPrice);
| transferPartialOwnership(assetId, msg.sender, shares);
emit AssetPurchased(msg.sender, assetId, shares, totalPrice);
| 9,841 |
19 | // function to buy tokens._amount how much tokens can be bought. / | function buyBatch(uint _amount) external payable {
require(block.timestamp >= START_TIME, "sale is not started yet");
require(tokensSold + _amount <= MAX_NFT_TO_SELL, "exceed sell limit");
require(_amount > 0, "empty input");
require(_amount <= MAX_UNITS_PER_TRANSACTION, "exceed MAX_UNITS_PER_TRANSACTION");
uint currentPrice = getCurrentPrice() * _amount;
require(msg.value >= currentPrice, "too low value");
if(msg.value > currentPrice) {
//send the rest back
(bool sent, ) = payable(msg.sender).call{value: msg.value - currentPrice}("");
require(sent, "Failed to send Ether");
}
tokensSold += _amount;
nft.mintBatch(msg.sender, _amount);
(bool sent, ) = receiver.call{value: address(this).balance}("");
require(sent, "Something wrong with receiver");
}
| function buyBatch(uint _amount) external payable {
require(block.timestamp >= START_TIME, "sale is not started yet");
require(tokensSold + _amount <= MAX_NFT_TO_SELL, "exceed sell limit");
require(_amount > 0, "empty input");
require(_amount <= MAX_UNITS_PER_TRANSACTION, "exceed MAX_UNITS_PER_TRANSACTION");
uint currentPrice = getCurrentPrice() * _amount;
require(msg.value >= currentPrice, "too low value");
if(msg.value > currentPrice) {
//send the rest back
(bool sent, ) = payable(msg.sender).call{value: msg.value - currentPrice}("");
require(sent, "Failed to send Ether");
}
tokensSold += _amount;
nft.mintBatch(msg.sender, _amount);
(bool sent, ) = receiver.call{value: address(this).balance}("");
require(sent, "Something wrong with receiver");
}
| 65,523 |
20 | // Set `_newManager` as the manager of `_role` in `_app`_newManager Address for the new manager_app Address of the app in which the permission management is being transferred_role Identifier for the group of actions being transferred/ | function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
| function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
| 11,438 |
128 | // Check if the pool is initialized | if (localTotalSupply == 0) {
| if (localTotalSupply == 0) {
| 60,266 |
33 | // Data that is needed for the operator to simulate priority queue offchain | emit NewPriorityRequest(
_priorityOpParams.txId,
canonicalTxHash,
_priorityOpParams.expirationTimestamp,
transaction,
_factoryDeps
);
| emit NewPriorityRequest(
_priorityOpParams.txId,
canonicalTxHash,
_priorityOpParams.expirationTimestamp,
transaction,
_factoryDeps
);
| 27,810 |
5 | // @custom:legacy/Initiates a withdrawal from L2 to L1./ This function only works with OptimismMintableERC20 tokens or ether. Use the/ `bridgeERC20` function to bridge native L2 tokens to L1./_l2Token Address of the L2 token to withdraw./_amountAmount of the L2 token to withdraw./_minGasLimit Minimum gas limit to use for the transaction./_extraData Extra data attached to the withdrawal. | function withdraw(
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
| function withdraw(
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _extraData
| 12,255 |
7 | // Get number of decimals for the token. return number of decimals for the token / | function decimals () public pure returns (uint8) {
return 2;
}
| function decimals () public pure returns (uint8) {
return 2;
}
| 15,893 |
130 | // on early sell. Replace the previous early sell logic which was poorly written | if(enableEarlySellTax && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)){
fees = amount.mul(earlySellTotalFees).div(100);
tokensForLiquidity += fees * earlySellLiquidityFee / earlySellTotalFees;
tokensForDev += fees * earlySellDevFee / earlySellTotalFees;
tokensForMarketing += fees * earlySellMarketingFee / earlySellTotalFees;
}
| if(enableEarlySellTax && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)){
fees = amount.mul(earlySellTotalFees).div(100);
tokensForLiquidity += fees * earlySellLiquidityFee / earlySellTotalFees;
tokensForDev += fees * earlySellDevFee / earlySellTotalFees;
tokensForMarketing += fees * earlySellMarketingFee / earlySellTotalFees;
}
| 5,329 |
22 | // Actually mint the NFT to the sender using msg.sender. | _safeMint(msg.sender, newItemId);
emit NewEpicNFTMinted(msg.sender, newItemId);
| _safeMint(msg.sender, newItemId);
emit NewEpicNFTMinted(msg.sender, newItemId);
| 13,002 |
13 | // ------------------------------------------------------------------------ Get the token balance for account `tokenOwner` ------------------------------------------------------------------------ | function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
| function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
| 77,345 |
23 | // Indicator that this is a PToken contract (for inspection) / | bool public constant isPToken = true;
| bool public constant isPToken = true;
| 42,894 |
25 | // ========================================iERC20========================================= | function name() public view override returns (string memory) {
return _name;
}
| function name() public view override returns (string memory) {
return _name;
}
| 24,131 |
41 | // ERC20 Inteface methods | function name() public view returns (string) {
return token.name();
}
| function name() public view returns (string) {
return token.name();
}
| 57,619 |
175 | // MODIFIERS / | modifier onlyWithdrawal {
if (msg.sender != withdrawal) {
revert();
}
_;
}
| modifier onlyWithdrawal {
if (msg.sender != withdrawal) {
revert();
}
_;
}
| 17,033 |
3 | // burn money market coin from an address. Can only be called by holder _amount amount to burn/ | function burn(uint256 _amount) external;
| function burn(uint256 _amount) external;
| 27,266 |
8 | // Fee Collector address. | address public override feeCollector;
| address public override feeCollector;
| 24,472 |
51 | // Making modified tick with liquidity times 296 | ModTick memory modTick;
modTick.tick = tickList[i].tick;
modTick.liquidityNet = int256(tickList[i].liquidityNet)*2**96;
modTick.liquidityGross = tickList[i].liquidityGross;
return modTick;
| ModTick memory modTick;
modTick.tick = tickList[i].tick;
modTick.liquidityNet = int256(tickList[i].liquidityNet)*2**96;
modTick.liquidityGross = tickList[i].liquidityGross;
return modTick;
| 6,932 |
63 | // Updates the balances_bonus too | balances_bonus[msg.sender] = 0;
| balances_bonus[msg.sender] = 0;
| 46,931 |
72 | // internal function for resetting user share / pool share, and user LP balance | function resetUser(uint256 _poolID, address _user) internal {
UserInfo storage user = userInfo[_poolID][_user];
user.amount = 0;
user.shareBalance = 0;
}
| function resetUser(uint256 _poolID, address _user) internal {
UserInfo storage user = userInfo[_poolID][_user];
user.amount = 0;
user.shareBalance = 0;
}
| 6,684 |
4 | // define log event when change value of"bestInvestor" or "bestPromoter" changed | event LogBestInvestorChanged(address indexed addr, uint when, uint invested);
event LogBestPromoterChanged(address indexed addr, uint when, uint refs);
| event LogBestInvestorChanged(address indexed addr, uint when, uint invested);
event LogBestPromoterChanged(address indexed addr, uint when, uint refs);
| 15,012 |
26 | // 9 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT |
string inCCH_edit_9 = " une première phrase " ;
|
string inCCH_edit_9 = " une première phrase " ;
| 53,618 |
209 | // Disinvest Mooniswap pools | for (
uint256 b = 0;
b < availableBaskets[_basketIndex].mooniswapPools.length;
b++
) {
require(
userBalance[msg.sender].basketBalances[_basketIndex]
.mooniswapPools[b] > 0,
"balance must be positive"
);
| for (
uint256 b = 0;
b < availableBaskets[_basketIndex].mooniswapPools.length;
b++
) {
require(
userBalance[msg.sender].basketBalances[_basketIndex]
.mooniswapPools[b] > 0,
"balance must be positive"
);
| 54,817 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.