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
|
|---|---|---|---|---|
539
|
// transfers to the protocol fees of a flashloan to the fees collection address_token the address of the token being transferred_amount the amount being transferred/
|
function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal {
address payable receiver = address(uint160(addressesProvider.getTokenDistributor()));
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(receiver, _amount);
} else {
//solium-disable-next-line
(bool result, ) = receiver.call.value(_amount)("");
require(result, "Transfer to token distributor failed");
}
}
|
function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal {
address payable receiver = address(uint160(addressesProvider.getTokenDistributor()));
if (_token != EthAddressLib.ethAddress()) {
ERC20(_token).safeTransfer(receiver, _amount);
} else {
//solium-disable-next-line
(bool result, ) = receiver.call.value(_amount)("");
require(result, "Transfer to token distributor failed");
}
}
| 35,120
|
35
|
// Called after oracle has updated flight status/
|
function processFlightStatus
(
address airlines,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
|
function processFlightStatus
(
address airlines,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
| 10,989
|
117
|
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. if the call returned error data, forward it
|
switch result case 0 { revert(ptr, size) }
|
switch result case 0 { revert(ptr, size) }
| 6,222
|
344
|
// Set play record datetime.
|
addressToPlayRecordDateTime[msg.sender] = now;
|
addressToPlayRecordDateTime[msg.sender] = now;
| 73,719
|
3
|
// 建構子/將IoT的位址設為引數
|
constructor(address _iot){
owner = msg.sender;
iot = _iot;
numPaid = 0;
}
|
constructor(address _iot){
owner = msg.sender;
iot = _iot;
numPaid = 0;
}
| 1,427
|
79
|
// on sell
|
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 100;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment +=
(fees * sellDevelopmentFee) /
sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
|
else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = (amount * sellTotalFees) / 100;
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDevelopment +=
(fees * sellDevelopmentFee) /
sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
| 11,778
|
61
|
// Transfer tokens from sender to DeFi protocol token Address of token amount Value of token to depositreturn new balances of each token /
|
function handleDeposit(address token, uint256 amount) external;
function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external;
|
function handleDeposit(address token, uint256 amount) external;
function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external;
| 68,426
|
4
|
// Mapping from token id to token uri
|
mapping(uint256 => string) private _tokenUris;
|
mapping(uint256 => string) private _tokenUris;
| 28,146
|
84
|
// return length (bytes)
|
uint32 returnSize = 32;
|
uint32 returnSize = 32;
| 24,461
|
31
|
// Update Esusu Cycle State, total cycle duration, total sharesandcycle start time,
|
_esusuStorage.UpdateEsusuCycleSharesDuringJoin(CycleId, sharesForMember);
|
_esusuStorage.UpdateEsusuCycleSharesDuringJoin(CycleId, sharesForMember);
| 5,684
|
199
|
// Transfer amount, including fees if takeFee is true
|
_tokenTransfer(from, to, amount, takeFee, antiBotStatus);
|
_tokenTransfer(from, to, amount, takeFee, antiBotStatus);
| 5,314
|
214
|
// Sets the stored oracle contract with the address resolved by ENS This may be called on its own as long as `useChainlinkWithENS` has been called previously /
|
function updateChainlinkOracleWithENS()
internal
|
function updateChainlinkOracleWithENS()
internal
| 22,523
|
55
|
// Set max number of tickets Only callable by owner /
|
function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
|
function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
| 27,554
|
9
|
// Mints the supplied value of the tokens to the destination address.Minting cannot be performed any further once the maximum supply is reached.This function cannot be used by anyone except for this contract./ _to The address which will receive the minted tokens./ _value The amount of tokens to mint.
|
function mintTokens(address _to, uint _value) internal returns(bool) {
require(_to != address(0), "Invalid address.");
require(totalSupply_.add(_value) <= MAX_SUPPLY, "Sorry but the total supply can't exceed the maximum supply.");
balances[_to] = balances[_to].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Transfer(address(0), _to, _value);
emit Mint(_to, _value);
return true;
}
|
function mintTokens(address _to, uint _value) internal returns(bool) {
require(_to != address(0), "Invalid address.");
require(totalSupply_.add(_value) <= MAX_SUPPLY, "Sorry but the total supply can't exceed the maximum supply.");
balances[_to] = balances[_to].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Transfer(address(0), _to, _value);
emit Mint(_to, _value);
return true;
}
| 39,200
|
194
|
// If there are no tokens minted: exchangeRate = initialExchangeRate /
|
return (MathError.NO_ERROR, initialExchangeRateMantissa);
|
return (MathError.NO_ERROR, initialExchangeRateMantissa);
| 574
|
10
|
// tell the associated proxy to upgrade to the new implementation
|
IUUPSImplementation(proxy).upgradeTo(impl);
_setAssociatedSystem(id, AssociatedSystem.KIND_ERC20, proxy, impl);
|
IUUPSImplementation(proxy).upgradeTo(impl);
_setAssociatedSystem(id, AssociatedSystem.KIND_ERC20, proxy, impl);
| 26,255
|
1
|
// Always round to negative infinity
|
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0))
arithmeticMeanTick--;
|
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0))
arithmeticMeanTick--;
| 16,771
|
24
|
// MODIFIERS /
|
modifier onlySystem() {
require((msg.sender == gameAddress) || (msg.sender == manager));
_;
}
|
modifier onlySystem() {
require((msg.sender == gameAddress) || (msg.sender == manager));
_;
}
| 25,080
|
2
|
// Fallback function, don't accept any ETH /
|
function() public payable {
revert("ERC20Utilities does not accept payments");
}
|
function() public payable {
revert("ERC20Utilities does not accept payments");
}
| 28,067
|
46
|
// Check that the drop stage is active.
|
_checkActive(mintParams.startTime, mintParams.endTime);
|
_checkActive(mintParams.startTime, mintParams.endTime);
| 30,200
|
195
|
// overrideadd Enumerable info
|
function _transferFrom(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
// not allown to transfer when only one avatar
super._transferFrom(_from, _to, _tokenId);
_addTokenTo(_to,_tokenId);
_removeTokenFrom(_from, _tokenId);
}
|
function _transferFrom(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
// not allown to transfer when only one avatar
super._transferFrom(_from, _to, _tokenId);
_addTokenTo(_to,_tokenId);
_removeTokenFrom(_from, _tokenId);
}
| 35,571
|
66
|
// Used to remove assets from the allowlistWhen you are removing an asset, `xcall` will fail but `handle` and `execute` will not toallow for inflight transfers to be addressed. Similarly, the `repayAavePortal` function willwork._key - The hash of the canonical id and domain to remove (mapping key) _adoptedAssetId - Corresponding adopted asset to remove _representation - Corresponding representation asset (i.e. bridged asset) to remove. _canonical - The TokenId (canonical ID and domain) of the asset. /
|
function _removeAssetId(
bytes32 _key,
address _adoptedAssetId,
address _representation,
TokenId memory _canonical
|
function _removeAssetId(
bytes32 _key,
address _adoptedAssetId,
address _representation,
TokenId memory _canonical
| 23,585
|
8
|
// The timestamp from the block when this video is generated in the block.
|
uint64 birthTime;
|
uint64 birthTime;
| 794
|
1,015
|
// for each byte (starting from the lowest byte), populate the result with two characters
|
for (uint256 i = 0; i < 20; i++) {
|
for (uint256 i = 0; i < 20; i++) {
| 621
|
71
|
// governance address for the governance contract
|
address public governance;
address public pendingGovernance;
|
address public governance;
address public pendingGovernance;
| 9,922
|
79
|
// Emit these for backwards compatability with offchain consumers that only support legacy events
|
emit NewRound(
r.hotVars.latestAggregatorRoundId,
address(0x0), // use zero address since we don't have anybody "starting" the round here
block.timestamp
);
emit AnswerUpdated(
median,
r.hotVars.latestAggregatorRoundId,
block.timestamp
);
|
emit NewRound(
r.hotVars.latestAggregatorRoundId,
address(0x0), // use zero address since we don't have anybody "starting" the round here
block.timestamp
);
emit AnswerUpdated(
median,
r.hotVars.latestAggregatorRoundId,
block.timestamp
);
| 2,713
|
79
|
// Validate input. Only the original deployer can update an application -
|
require(_exec_id != 0 && msg.sender == deployed_by[_exec_id], 'invalid sender or input');
|
require(_exec_id != 0 && msg.sender == deployed_by[_exec_id], 'invalid sender or input');
| 11,104
|
11
|
// Returns a random (deterministic) seed between 0-range based on an arbitrary set of inputs
|
uint256 output = uint256(keccak256(abi.encodePacked(input))) % (max-min) + min;
return output;
|
uint256 output = uint256(keccak256(abi.encodePacked(input))) % (max-min) + min;
return output;
| 44,719
|
145
|
// Signals that the worker associated with the staker made a commitment to next periodstaker Staker addressperiod Period committed tovalue Amount of tokens staked for the committed period/
|
event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value);
|
event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value);
| 50,002
|
123
|
// TODO: GDA deposit should be considered here too
|
int256 signedTotalCFADeposit = senderAccountState.deposit.toInt256();
bytes memory liquidationTypeData;
bool isCurrentlyPatricianPeriod;
|
int256 signedTotalCFADeposit = senderAccountState.deposit.toInt256();
bytes memory liquidationTypeData;
bool isCurrentlyPatricianPeriod;
| 21,590
|
420
|
// lpTokenAmount the amount in the same units as Curve LP token (18 decimals) virtualPrice the "price", in 18 decimals, per big token unit of the LP token decimals the number of decimals for underlyer tokenreturn required minimum amount of underlyer (in token wei) /
|
function _calcMinAmountUnderlyer(
uint256 lpTokenAmount,
uint256 virtualPrice,
uint8 decimals
|
function _calcMinAmountUnderlyer(
uint256 lpTokenAmount,
uint256 virtualPrice,
uint8 decimals
| 44,041
|
9
|
// marketId=>isSuspend
|
mapping(uint => bool) public marketSuspend;
|
mapping(uint => bool) public marketSuspend;
| 20,741
|
4
|
// Public array of all Trusts
|
Trust[] public trusts;
|
Trust[] public trusts;
| 18,562
|
7
|
// Approves the address as the whitelisted address. /
|
function approve(address addr) onlyOwner external {
whitelist[addr] = true;
}
|
function approve(address addr) onlyOwner external {
whitelist[addr] = true;
}
| 30,876
|
80
|
// -------------------staking--------------------/
|
function stake(uint amount) public {
uint cur = block.timestamp;
require((amount != 0) && (msg.sender != owner));
if (!isHolder(msg.sender)) addHolder(msg.sender);
transferForStaking(msg.sender, address(this), amount);
_staking[msg.sender] = _staking[msg.sender].add(amount);
Transaction memory t = Transaction(msg.sender, cur, amount);
stakingTrans.push(t);
}
|
function stake(uint amount) public {
uint cur = block.timestamp;
require((amount != 0) && (msg.sender != owner));
if (!isHolder(msg.sender)) addHolder(msg.sender);
transferForStaking(msg.sender, address(this), amount);
_staking[msg.sender] = _staking[msg.sender].add(amount);
Transaction memory t = Transaction(msg.sender, cur, amount);
stakingTrans.push(t);
}
| 29,933
|
4
|
// Get the account `balance` of another account with address `_owner`
|
function balanceOf(address _owner) constant returns (uint256 balance);
|
function balanceOf(address _owner) constant returns (uint256 balance);
| 659
|
55
|
// Change the fee percentage _feePercentage New fee percentage. 10000 = 100% /
|
function changeFeePercentage(uint256 _feePercentage) external onlyOwner {
feePercentage = _feePercentage;
}
|
function changeFeePercentage(uint256 _feePercentage) external onlyOwner {
feePercentage = _feePercentage;
}
| 1,184
|
111
|
// Assign active game variables
|
uint256 id = gameNumber;
address host = msg.sender;
uint256 value = msg.value;
bool outcome = addGame(id, host, value, _tokenId);
return outcome;
|
uint256 id = gameNumber;
address host = msg.sender;
uint256 value = msg.value;
bool outcome = addGame(id, host, value, _tokenId);
return outcome;
| 21,564
|
229
|
// Users borrow assets from the protocol to their own addressborrowAmount The amount of the underlying asset to borrow return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.interestBalancePrior) = borrowInterestBalancePriorInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_INTEREST_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
|
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.interestBalancePrior) = borrowInterestBalancePriorInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_INTEREST_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
| 13,633
|
77
|
// Get all fixed deposit durations and their interest rates.Get all fixed deposit durations and their interest rates. return _duration Fixed deposit duration.return _interest Interest rate for fixed deposit. /
|
function getFDDurationAndInterest() external view returns (uint256[] memory _duration, uint256[] memory _interest) {
for(uint256 i = 0; i < fdTfId.length; i++){
_duration[i] = fdTariffIdToInfo[fdTfId[i]].duration;
_interest[i] = fdTariffIdToInfo[fdTfId[i]].interest;
}
}
|
function getFDDurationAndInterest() external view returns (uint256[] memory _duration, uint256[] memory _interest) {
for(uint256 i = 0; i < fdTfId.length; i++){
_duration[i] = fdTariffIdToInfo[fdTfId[i]].duration;
_interest[i] = fdTariffIdToInfo[fdTfId[i]].interest;
}
}
| 36,644
|
132
|
// The timestamp on and after which the transfer restriction must be lifted.
|
uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN;
|
uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN;
| 31,310
|
125
|
// Sends an outgoing message from the source domain, with a specified caller on thedestination domain. Increment nonce, format the message, and emit `MessageSent` event with message information.WARNING: if the `destinationCaller` does not represent a valid address as bytes32, then it will not be possibleto broadcast the message on the destination domain. This is an advanced feature, and the standardsendMessage() should be preferred for use cases where a specific destination caller is not required. destinationDomain Domain of destination chain recipient Address of message recipient on destination domain as bytes32 destinationCaller caller on the destination domain, as bytes32 messageBody Raw bytes content
|
function sendMessageWithCaller(
uint32 destinationDomain,
bytes32 recipient,
bytes32 destinationCaller,
|
function sendMessageWithCaller(
uint32 destinationDomain,
bytes32 recipient,
bytes32 destinationCaller,
| 16,903
|
98
|
// Payable function to purchase kwh with eth at current crowdsale price and reward rate
|
function buyKwh() public payable returns (bool) {
address client = msg.sender;
uint256 kwhToSend = msg.value * ethToKwh;
forwardAddress.transfer(msg.value);
kwh.mint(client, kwhToSend);
if (kwhToSend > 10000 && carbonixReward > 0) {
car.mint(client, (kwhToSend * carbonixReward) / 10000);
}
return true;
}
|
function buyKwh() public payable returns (bool) {
address client = msg.sender;
uint256 kwhToSend = msg.value * ethToKwh;
forwardAddress.transfer(msg.value);
kwh.mint(client, kwhToSend);
if (kwhToSend > 10000 && carbonixReward > 0) {
car.mint(client, (kwhToSend * carbonixReward) / 10000);
}
return true;
}
| 23,741
|
78
|
// Borrows are repaid by another user (possibly the borrower). payer the account paying off the borrow borrower the account with the debt being payed off repayAmount the amount of undelrying tokens being returnedreturn (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. /
|
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
|
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
| 11,772
|
89
|
// Allows to any owner of the contract withdraw needed ERC20 token from this contract (promo or bounties for example).ERC20Token Address of ERC20 token.recipient Account to receive tokens./
|
function withdrawERC20(address ERC20Token, address recipient) external onlyAdmin {
uint256 amount = IBTALToken(ERC20Token).balanceOf(address(this));
require(amount > 0);
IBTALToken(ERC20Token).transfer(recipient, amount);
}
|
function withdrawERC20(address ERC20Token, address recipient) external onlyAdmin {
uint256 amount = IBTALToken(ERC20Token).balanceOf(address(this));
require(amount > 0);
IBTALToken(ERC20Token).transfer(recipient, amount);
}
| 31,014
|
51
|
// Change current token price/newTokenPrice New token unit price in wei
|
function changeTokenPrice(uint newTokenPrice) public onlyOwner {
require(newTokenPrice > 0);
tokenPrice = newTokenPrice;
TokenPriceChanged(newTokenPrice);
}
|
function changeTokenPrice(uint newTokenPrice) public onlyOwner {
require(newTokenPrice > 0);
tokenPrice = newTokenPrice;
TokenPriceChanged(newTokenPrice);
}
| 25,910
|
22
|
// approve should be called when allowed[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol /
|
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
|
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 15,305
|
397
|
// High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,for x close to one. Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. /
|
function ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
|
function ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
| 24,662
|
81
|
// MUST fully redeem a past stake, CD gets destroyed
|
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSecCalculated);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
if(lastStake.stakingShares > sharesLeftToBurn){
sharesLeftToBurn = 0;
} else {
|
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSecCalculated);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
if(lastStake.stakingShares > sharesLeftToBurn){
sharesLeftToBurn = 0;
} else {
| 48,153
|
59
|
// data for analytics
|
uint internal totalETHProvided;
uint internal totalTokenProvided;
uint internal totalProviders;
|
uint internal totalETHProvided;
uint internal totalTokenProvided;
uint internal totalProviders;
| 22,270
|
144
|
// only the contract owner can burn tokens
|
require(msg.sender == contractOwner);
|
require(msg.sender == contractOwner);
| 18,641
|
4
|
// return The total supply of the token /
|
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
|
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
| 33,812
|
1
|
// About dividendCorrection: If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: `dividendOf(_user) = dividendPerSharebalanceOf(_user)`. When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), `dividendOf(_user)` should not be changed, but the computed value of `dividendPerSharebalanceOf(_user)` is changed. To keep the `dividendOf(_user)` unchanged, we add a correction term: `dividendOf(_user) = dividendPerSharebalanceOf(_user) + dividendCorrectionOf(_user)`, where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: `dividendCorrectionOf(_user) = dividendPerShare(old balanceOf(_user)) - (new balanceOf(_user))`. So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
|
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
|
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
| 13,970
|
7
|
// Inspired by OraclizeAPI's implementation - MIT license https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
|
if (value == 0) {
return "0";
}
|
if (value == 0) {
return "0";
}
| 5,369
|
34
|
// fallback function can be used to buytokens /
|
function() public payable {
payETH(msg.sender);
}
|
function() public payable {
payETH(msg.sender);
}
| 47,447
|
72
|
// See {BEP20-balanceOf}. /
|
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
|
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
| 7,581
|
46
|
// Finish a campaign by returning the pledge BCH back to its owner and removing its records.If it succeeds, send the raised coins to its owner as well. The donator list's length must be zeroor smaller than DonatorLastClearCount, such that it can be cleared in this function call. Requirements: - The donators' records must be no more than `DonatorLastClearCount` - This campaign is finalized, or the creater wants to finish it because of no donator at all (zero donation value)
|
function finish(bytes32 campaignName) external {
CampaignInfo memory info = loadCampaignInfo(campaignName);
uint donatedAmount = getCampaignAmount(campaignName);
if(donatedAmount == 0) {
if(block.timestamp < info.deadline) {
require(msg.sender == info.receiver, "not-creater");
}
} else {
require(isFinalized(info, donatedAmount), "not-finalized");
bool succeed = donatedAmount >= info.softTarget;
address[] storage donatorList = campDonatorList[campaignName];
if(donatorList.length > DonatorLastClearCount) {
require(false, "too-many-remained-donator-records");
} else if(donatorList.length != 0) {
_clearDonators(campaignName, donatorList.length, donatorList, !succeed, info.coinType);
}
if(succeed) {
safeTransfer(info.coinType, info.receiver, donatedAmount);
}
}
removeCampaign(campaignName);
safeTransfer(SEP206Contract, info.receiver, info.pledgeU32*PledgeUnit);
emit Finish(campaignName);
}
|
function finish(bytes32 campaignName) external {
CampaignInfo memory info = loadCampaignInfo(campaignName);
uint donatedAmount = getCampaignAmount(campaignName);
if(donatedAmount == 0) {
if(block.timestamp < info.deadline) {
require(msg.sender == info.receiver, "not-creater");
}
} else {
require(isFinalized(info, donatedAmount), "not-finalized");
bool succeed = donatedAmount >= info.softTarget;
address[] storage donatorList = campDonatorList[campaignName];
if(donatorList.length > DonatorLastClearCount) {
require(false, "too-many-remained-donator-records");
} else if(donatorList.length != 0) {
_clearDonators(campaignName, donatorList.length, donatorList, !succeed, info.coinType);
}
if(succeed) {
safeTransfer(info.coinType, info.receiver, donatedAmount);
}
}
removeCampaign(campaignName);
safeTransfer(SEP206Contract, info.receiver, info.pledgeU32*PledgeUnit);
emit Finish(campaignName);
}
| 4,138
|
280
|
// burns tokens equivalent to the amount requested
|
_burn(msg.sender, amountToRedeem);
bool userIndexReset = false;
|
_burn(msg.sender, amountToRedeem);
bool userIndexReset = false;
| 6,925
|
3
|
// Most of this contract's functionality requires an authorized contract to call it
|
mapping (address => uint256) authorizedContracts;
|
mapping (address => uint256) authorizedContracts;
| 40,012
|
105
|
// This should always be true. If not, something is very wrong
|
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
|
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
| 45,907
|
4
|
// Remove a minter to the list of addresses that can fuse cards_minter is the address of the minter to remove /
|
function removeMinter(
address _minter
)
public
onlyOwner
|
function removeMinter(
address _minter
)
public
onlyOwner
| 25,233
|
8
|
// Priority 3: EIP-2981 royalty standard via Royalty Registry
|
if (
nftContractAddress.supportsERC165InterfaceUnchecked(
type(IRoyaltyInfo).interfaceId
)
) {
|
if (
nftContractAddress.supportsERC165InterfaceUnchecked(
type(IRoyaltyInfo).interfaceId
)
) {
| 18,376
|
13
|
// For metapools: 0 = the token (i.e. Frax, MIC, etc), 1 = DAI, 2 = USDC, 3 = USDT_receiver = msg.sender, so tokens are sent to the user
|
ICurveMeta2(pool).exchange_underlying(0, j, transferToAmount, min_dy, msg.sender);
|
ICurveMeta2(pool).exchange_underlying(0, j, transferToAmount, min_dy, msg.sender);
| 49,375
|
191
|
// Initializes access controls. _admin Admins address. /
|
function initAccessControls(address _admin) public {
require(!initAccess, "Already initialised");
require(_admin != address(0), "Incorrect input");
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
initAccess = true;
}
|
function initAccessControls(address _admin) public {
require(!initAccess, "Already initialised");
require(_admin != address(0), "Incorrect input");
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
initAccess = true;
}
| 32,065
|
19
|
// Exchange Wallet/Set the Exchange Wallet Address. This Address receives all wETHPayments but must also be the owner of the NFTs on Salewallet - Address of Exchange Wallet /
|
function setExchangeWallet(address wallet) external onlyOwner {
exchangeWallet = wallet;
emit ExchangeWalletSet(wallet);
}
|
function setExchangeWallet(address wallet) external onlyOwner {
exchangeWallet = wallet;
emit ExchangeWalletSet(wallet);
}
| 84,735
|
21
|
// tradable
|
bool public tradable = false;
|
bool public tradable = false;
| 13,447
|
51
|
// BACKGROUND
|
string[] private backgrounds = ["Light Blue","Orange","Grey","Purple",
"Army","Teal","Mint",
"Stadium","LSD"];
|
string[] private backgrounds = ["Light Blue","Orange","Grey","Purple",
"Army","Teal","Mint",
"Stadium","LSD"];
| 42,034
|
3
|
// Returns the features for the specific crew member _crewId The ERC721 tokenId for the crew member _mod A modifier between 0 and 10,000 /
|
function getFeatures(uint _crewId, uint _mod) public view returns (uint) {
require(generatorSeed != "", "ArvadCitizenGenerator: seed not yet set");
uint features = 0;
uint mod = _mod;
bytes32 crewSeed = getCrewSeed(_crewId);
uint sex = generateSex(crewSeed);
features |= sex << 8; // 2 bytes
features |= generateBody(crewSeed, sex) << 10; // 16 bytes
uint class = generateClass(crewSeed);
features |= class << 26; // 8 bytes
features |= generateArvadJob(crewSeed, class, mod) << 34; // 16 bytes
features |= generateClothes(crewSeed, class) << 50; // 16 bytes to account for color variation
features |= generateHair(crewSeed, sex) << 66; // 16 bytes
features |= generateFacialFeatures(crewSeed, sex) << 82; // 16 bytes
features |= generateHairColor(crewSeed) << 98; // 8 bytes
features |= generateHeadPiece(crewSeed, class, mod) << 106; // 8 bytes
return features;
}
|
function getFeatures(uint _crewId, uint _mod) public view returns (uint) {
require(generatorSeed != "", "ArvadCitizenGenerator: seed not yet set");
uint features = 0;
uint mod = _mod;
bytes32 crewSeed = getCrewSeed(_crewId);
uint sex = generateSex(crewSeed);
features |= sex << 8; // 2 bytes
features |= generateBody(crewSeed, sex) << 10; // 16 bytes
uint class = generateClass(crewSeed);
features |= class << 26; // 8 bytes
features |= generateArvadJob(crewSeed, class, mod) << 34; // 16 bytes
features |= generateClothes(crewSeed, class) << 50; // 16 bytes to account for color variation
features |= generateHair(crewSeed, sex) << 66; // 16 bytes
features |= generateFacialFeatures(crewSeed, sex) << 82; // 16 bytes
features |= generateHairColor(crewSeed) << 98; // 8 bytes
features |= generateHeadPiece(crewSeed, class, mod) << 106; // 8 bytes
return features;
}
| 7,986
|
8
|
// Minimum amount that must be redeemed for a withdraw request
|
uint256 public minimumRedemptionAmount;
|
uint256 public minimumRedemptionAmount;
| 3,991
|
57
|
// Bonus Stage Three state. /
|
function PriceThreeEnable() onlyOwner() {
stageThree = true;
}
|
function PriceThreeEnable() onlyOwner() {
stageThree = true;
}
| 20,147
|
229
|
// _maxTokensAtOnce get and set
|
function getMaxMintAmount() public view returns (uint256) {
return _maxMintAmount;
}
|
function getMaxMintAmount() public view returns (uint256) {
return _maxMintAmount;
}
| 20,195
|
125
|
// Interface for the ERC20 contracts created for reputation /
|
interface ReputationToken {
function balanceOf(address account) external view returns (uint256);
function mint(address _member, uint _amount) external;
function burn(address _member, uint _amount) external;
function setMerkleRoot(uint _type, uint _id, bytes32 _merkleRoot) external;
}
|
interface ReputationToken {
function balanceOf(address account) external view returns (uint256);
function mint(address _member, uint _amount) external;
function burn(address _member, uint _amount) external;
function setMerkleRoot(uint _type, uint _id, bytes32 _merkleRoot) external;
}
| 17,364
|
385
|
// Check if proposal was made
|
require(proposalTime != 0, "Didn't proposed yet");
|
require(proposalTime != 0, "Didn't proposed yet");
| 34,388
|
148
|
// a generic LzReceiver implementation /
|
abstract contract LzApp is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
using BytesLib for bytes;
// ua can not send payload larger than this by default, but it can be changed by the ua owner
uint constant public DEFAULT_PAYLOAD_SIZE_LIMIT = 10000;
ILayerZeroEndpoint public immutable lzEndpoint;
mapping(uint16 => bytes) public trustedRemoteLookup;
mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup;
mapping(uint16 => uint) public payloadSizeLimitLookup;
address public precrime;
address public developer;
event SetPrecrime(address precrime);
event SetTrustedRemote(uint16 _remoteChainId, bytes _path);
event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);
event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas);
constructor(address _endpoint,address _dev) {
lzEndpoint = ILayerZeroEndpoint(_endpoint);
developer = _dev;
}
|
abstract contract LzApp is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
using BytesLib for bytes;
// ua can not send payload larger than this by default, but it can be changed by the ua owner
uint constant public DEFAULT_PAYLOAD_SIZE_LIMIT = 10000;
ILayerZeroEndpoint public immutable lzEndpoint;
mapping(uint16 => bytes) public trustedRemoteLookup;
mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup;
mapping(uint16 => uint) public payloadSizeLimitLookup;
address public precrime;
address public developer;
event SetPrecrime(address precrime);
event SetTrustedRemote(uint16 _remoteChainId, bytes _path);
event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);
event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas);
constructor(address _endpoint,address _dev) {
lzEndpoint = ILayerZeroEndpoint(_endpoint);
developer = _dev;
}
| 14,825
|
110
|
// Hash(current computed hash + current element of the proof)
|
computedHash = _efficientHash(computedHash, proofElement);
|
computedHash = _efficientHash(computedHash, proofElement);
| 15,728
|
10
|
// Now let's hit the other token's contract... transfer money to us.
|
bool success = otherToken.transferFrom(msg.sender, address(this), _otherTokenAmount);
require(success, "other token transfer failed");
|
bool success = otherToken.transferFrom(msg.sender, address(this), _otherTokenAmount);
require(success, "other token transfer failed");
| 49,333
|
105
|
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. This is to verify that the computed args match with the ones specified in the query.
|
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
|
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
| 25,362
|
58
|
// See {recover}. /
|
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
|
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
| 38,926
|
124
|
// Bid Function which call the interncal bid function/ after doing all the pre-checks required to initiate a bid
|
function bid(uint256 _collectibleType, uint256 _collectibleClass) external payable {
require(msg.sender != address(0));
require(msg.sender != address(this));
require(_collectibleType >= 0 && _collectibleType <= 1);
require(_isActive(_assetId));
bytes32 collectibleName;
if(_collectibleType == 0){
collectibleName = bytes32("NoNameForVoucher");
if(_collectibleClass == 1){
require(prometheusVouchersMinted < PROMETHEUS_VOUCHER_LIMIT);
collectibleName = stringToBytes32(prometheusShipName);
prometheusVouchersMinted++;
}
if(_collectibleClass == 2){
require(crosairVouchersMinted < CROSAIR_VOUCHER_LIMIT);
crosairVouchersMinted++;
}
if(_collectibleClass == 3){
require(intrepidVoucherSoldCount < INTREPID_VOUCHER_LIMIT);
intrepidVouchersMinted++;
}
}
if(_collectibleType == 1){
if(_collectibleClass == 1){
require(prometheusShipMinted < PROMETHEUS_SHIP_LIMIT);
collectibleName = stringToBytes32(prometheusShipName);
prometheusShipMinted++;
}
if(_collectibleClass == 2){
require(crosairShipMinted < CROSAIR_VOUCHER_LIMIT);
collectibleName = stringToBytes32(crosairShipName);
crosairShipMinted++;
}
if(_collectibleClass == 3){
require(intrepidShipMinted < INTREPID_SHIP_LIMIT);
collectibleName = stringToBytes32(intrepidShipName);
intrepidShipMinted++;
}
}
uint256 _assetId = _createCollectible(collectibleName, _collectibleType, _collectibleClass);
CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId];
_bid(_assetId, msg.value, _Obj.collectibleType, _Obj.collectibleClass, msg.sender);
_transfer(address(this), msg.sender, _assetId);
}
|
function bid(uint256 _collectibleType, uint256 _collectibleClass) external payable {
require(msg.sender != address(0));
require(msg.sender != address(this));
require(_collectibleType >= 0 && _collectibleType <= 1);
require(_isActive(_assetId));
bytes32 collectibleName;
if(_collectibleType == 0){
collectibleName = bytes32("NoNameForVoucher");
if(_collectibleClass == 1){
require(prometheusVouchersMinted < PROMETHEUS_VOUCHER_LIMIT);
collectibleName = stringToBytes32(prometheusShipName);
prometheusVouchersMinted++;
}
if(_collectibleClass == 2){
require(crosairVouchersMinted < CROSAIR_VOUCHER_LIMIT);
crosairVouchersMinted++;
}
if(_collectibleClass == 3){
require(intrepidVoucherSoldCount < INTREPID_VOUCHER_LIMIT);
intrepidVouchersMinted++;
}
}
if(_collectibleType == 1){
if(_collectibleClass == 1){
require(prometheusShipMinted < PROMETHEUS_SHIP_LIMIT);
collectibleName = stringToBytes32(prometheusShipName);
prometheusShipMinted++;
}
if(_collectibleClass == 2){
require(crosairShipMinted < CROSAIR_VOUCHER_LIMIT);
collectibleName = stringToBytes32(crosairShipName);
crosairShipMinted++;
}
if(_collectibleClass == 3){
require(intrepidShipMinted < INTREPID_SHIP_LIMIT);
collectibleName = stringToBytes32(intrepidShipName);
intrepidShipMinted++;
}
}
uint256 _assetId = _createCollectible(collectibleName, _collectibleType, _collectibleClass);
CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId];
_bid(_assetId, msg.value, _Obj.collectibleType, _Obj.collectibleClass, msg.sender);
_transfer(address(this), msg.sender, _assetId);
}
| 31,562
|
24
|
// Calculate the rewards the player is owed since last time they were paid out The rewards rate is 20,000,000 per block. This is calculated using block.timestamp and the playerLastUpdate. If playerLastUpdate or playerSword is not set, then the player has no rewards.
|
function calculateRewards(
address _player
|
function calculateRewards(
address _player
| 20,609
|
266
|
// Mints `tokenId` and transfers it to `to`.
|
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
|
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
| 3,117
|
19
|
// @inheritdoc IRelayRecipient
|
string public override versionRecipient = "2.2.4";
|
string public override versionRecipient = "2.2.4";
| 12,889
|
22
|
// Modifier
|
modifier onlyMember {
require(acmMembers[msg.sender], "ACM:0:Access denied");
_;
}
|
modifier onlyMember {
require(acmMembers[msg.sender], "ACM:0:Access denied");
_;
}
| 29,748
|
176
|
// File: contracts\interfaces\IWitnetRequestBoardAdmin.sol/Witnet Request Board basic administration interface./The Witnet Foundation.
|
interface IWitnetRequestBoardAdmin {
event OwnershipTransferred(address indexed from, address indexed to);
/// Gets admin/owner address.
function owner() external view returns (address);
/// Transfers ownership.
function transferOwnership(address) external;
}
|
interface IWitnetRequestBoardAdmin {
event OwnershipTransferred(address indexed from, address indexed to);
/// Gets admin/owner address.
function owner() external view returns (address);
/// Transfers ownership.
function transferOwnership(address) external;
}
| 19,869
|
230
|
// If we can liquidate, it also implies that the current price is valid, and that the account being liquidated has a position.
|
Position storage position = positions[account];
require(_canLiquidate(position, liquidationFee, fundingIndex), "Position cannot be liquidated");
|
Position storage position = positions[account];
require(_canLiquidate(position, liquidationFee, fundingIndex), "Position cannot be liquidated");
| 14,557
|
97
|
// REFERRAL BONUSES - automatic payouts
|
if(msg.data.length == 20) {
address referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
uint refererTokens = tokens / 100 * 5; // 5% UDONS ref. bonus
_beforeTokenTransfer(address(0), referer, refererTokens);
_balances[referer] = _balances[referer].add(refererTokens);
_totalSupply = _totalSupply.add(refererTokens);
emit Transfer(address(0), referer, refererTokens);// automatic ref. payouts
}
|
if(msg.data.length == 20) {
address referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
uint refererTokens = tokens / 100 * 5; // 5% UDONS ref. bonus
_beforeTokenTransfer(address(0), referer, refererTokens);
_balances[referer] = _balances[referer].add(refererTokens);
_totalSupply = _totalSupply.add(refererTokens);
emit Transfer(address(0), referer, refererTokens);// automatic ref. payouts
}
| 10,772
|
20
|
// =============================================================================================================================================================================================================================================================================================================================================
| 7,462
|
||
224
|
// returns player info based on address.if no address is given, it willuse msg.sender _playerAddr address of the player you want to lookupreturn gold boxes owned (current round)return winnings vaultreturn dividends vaultreturn referral vaultreturn player round eth /
|
function getPlayerInfoByAddress(address _playerAddr)
public
view
returns( uint256, uint256, uint256, uint256, uint256)
|
function getPlayerInfoByAddress(address _playerAddr)
public
view
returns( uint256, uint256, uint256, uint256, uint256)
| 11,458
|
24
|
// 1Token = net_asset_value / total_Token_liquidity net_asset_value = (rate of 1(cToken || iToken) in underlying_Token)balanceOf((cToken || iToken))
|
uint256 navPool;
uint256 price;
|
uint256 navPool;
uint256 price;
| 30,231
|
156
|
// if there is any balance left over in the contract
|
uint days_since_end = (now - end_date) / DAY_IN_SECONDS;
if(days_since_end > 30) {
owner.transfer(this.balance);
}
|
uint days_since_end = (now - end_date) / DAY_IN_SECONDS;
if(days_since_end > 30) {
owner.transfer(this.balance);
}
| 21,778
|
13
|
// public functionplayer submit betonly if game is active & bet is valid can query and set player vars/
|
function playerRollDice() public
payable
gameIsActive
betIsValid(msg.value, underNumber)
|
function playerRollDice() public
payable
gameIsActive
betIsValid(msg.value, underNumber)
| 12,389
|
114
|
// Mapping owner address to token count
|
mapping(address => uint256) private _balances;
|
mapping(address => uint256) private _balances;
| 7,823
|
2
|
// ----- Callback Function ----- / only accept ETH from WETH or whitelisted external swaps.
|
assert(msg.sender == WETH || isWhitelisted[msg.sender]);
|
assert(msg.sender == WETH || isWhitelisted[msg.sender]);
| 2,152
|
353
|
// pull payment
|
TransferHelper.safeTransferFrom(token, payer, recipient, value);
|
TransferHelper.safeTransferFrom(token, payer, recipient, value);
| 13,211
|
1
|
// retrieve the size of the code, this needs assembly
|
let size := extcodesize(addr)
|
let size := extcodesize(addr)
| 22,840
|
14
|
// Mints 1 NBG to contract creator for initial pool setup
|
require(_taxRate < 10000, "tax equal or bigger to 100%");
require(_taxCollectorAddress != address(0), "tax collector address must be non-zero address");
excludeAddress(address(this));
_mint(msg.sender, 1 ether);
taxRate = _taxRate;
taxCollectorAddress = _taxCollectorAddress;
|
require(_taxRate < 10000, "tax equal or bigger to 100%");
require(_taxCollectorAddress != address(0), "tax collector address must be non-zero address");
excludeAddress(address(this));
_mint(msg.sender, 1 ether);
taxRate = _taxRate;
taxCollectorAddress = _taxCollectorAddress;
| 13,660
|
40
|
// New winner Cancel the other bid, refund 99.5%
|
if (address(h.deed) != address(0x0)) {
Deed previousWinner = h.deed;
previousWinner.closeDeed(995);
}
|
if (address(h.deed) != address(0x0)) {
Deed previousWinner = h.deed;
previousWinner.closeDeed(995);
}
| 12,422
|
197
|
// Deploy a new StakeDiceGame contract
|
StakeDiceGame newGame = new StakeDiceGame(this, _winningChance);
|
StakeDiceGame newGame = new StakeDiceGame(this, _winningChance);
| 7,195
|
86
|
// Update the liklihood foxes will get stolen by hunters. /
|
function setHunterStealFoxPropabilityMod(uint8 mod) external onlyOwner {
hunterStealFoxProbabilityMod = mod;
}
|
function setHunterStealFoxPropabilityMod(uint8 mod) external onlyOwner {
hunterStealFoxProbabilityMod = mod;
}
| 79,437
|
17
|
// Specify a token role Id that this extension requires. For exampleif an extension needs to mint tokens then it should require TOKEN_MINTER_ROLE.Can only be called within the constructor. roleId the role id. /
|
function _requireRole(bytes32 roleId) internal {
require(
_isInsideConstructorCall(),
"Function must be called inside the constructor"
);
_requiredRoles.push(roleId);
}
|
function _requireRole(bytes32 roleId) internal {
require(
_isInsideConstructorCall(),
"Function must be called inside the constructor"
);
_requiredRoles.push(roleId);
}
| 29,332
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.