comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/ | function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155... | 0.6.12 |
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/ | function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
... | 0.6.12 |
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/ | function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
/... | 0.6.12 |
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/ | function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset... | 0.6.12 |
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/ | function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
} | 0.6.12 |
/**
* @dev External Function to call updateState in F1155
*/ | function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.b... | 0.6.12 |
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/ | function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for N... | 0.6.12 |
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/ | function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFact... | 0.6.12 |
// The nft value & risk group is to be updated by authenticated oracles | function update(bytes32 nftID_, uint value, uint risk_) public auth {
// the risk group has to exist
require(thresholdRatio[risk_] != 0, "threshold for risk group not defined");
// switch of collateral risk group results in new: ceiling, threshold and interest rate for existing loan
// ... | 0.5.15 |
// function checks if the borrow amount does not exceed the max allowed borrow amount (=ceiling) | function borrow(uint loan, uint amount) external auth returns (uint) {
// increase borrowed amount -> note: max allowed borrow amount does not include accrued interest
borrowed[loan] = safeAdd(borrowed[loan], amount);
require(currentCeiling(loan) >= borrowed[loan], "borrow-amount-too-high");
... | 0.5.15 |
// borrowEvent is called by the shelf in the borrow method | function borrowEvent(uint loan) public auth {
uint risk_ = risk[nftID(loan)];
// when issued every loan has per default interest rate of risk group 0.
// correct interest rate has to be set on first borrow event
if(pile.loanRates(loan) != risk_) {
// set loan interest rate t... | 0.5.15 |
/// maturityDate is a unix timestamp | function file(bytes32 name, bytes32 nftID_, uint maturityDate_) public auth {
// maturity date only can be changed when there is no debt on the collateral -> futureValue == 0
if (name == "maturityDate") {
require((futureValue[nftID_] == 0), "can-not-change-maturityDate-outstanding-debt");
... | 0.5.15 |
// On borrow: the discounted future value of the asset is computed based on the loan amount and addeed to the bucket with the according maturity Date | function _borrow(uint loan, uint amount) internal returns(uint navIncrease) {
// ceiling check uses existing loan debt
require(ceiling(loan) >= safeAdd(borrowed[loan], amount), "borrow-amount-too-high");
bytes32 nftID_ = nftID(loan);
uint maturityDate_ = maturityDate[nftID_];
//... | 0.5.15 |
// calculate the future value based on the amount, maturityDate interestRate and recoveryRate | function calcFutureValue(uint loan, uint amount, uint maturityDate_, uint recoveryRatePD_) public returns(uint) {
// retrieve interest rate from the pile
(, ,uint loanInterestRate, ,) = pile.rates(pile.loanRates(loan));
return rmul(rmul(rpow(loanInterestRate, safeSub(maturityDate_, uniqueDayTime... | 0.5.15 |
/// update the nft value and change the risk group | function update(bytes32 nftID_, uint value, uint risk_) public auth {
nftValues[nftID_] = value;
// no change in risk group
if (risk_ == risk[nftID_]) {
return;
}
// nfts can only be added to risk groups that are part of the score card
require(thresholdRatio... | 0.5.15 |
// In case of successful repayment the approximatedNAV is decreased by the repaid amount | function repay(uint loan, uint amount) external auth returns (uint navDecrease) {
navDecrease = _repay(loan, amount);
if (navDecrease > approximatedNAV) {
approximatedNAV = 0;
}
if(navDecrease < approximatedNAV) {
approximatedNAV = safeSub(approximatedNAV, navDec... | 0.5.15 |
/// calculates the total discount of all buckets with a timestamp > block.timestamp | function calcTotalDiscount() public view returns(uint) {
uint normalizedBlockTimestamp = uniqueDayTimestamp(block.timestamp);
uint sum = 0;
uint currDate = normalizedBlockTimestamp;
if (currDate > lastBucket) {
return 0;
}
// only buckets after the block.ti... | 0.5.15 |
/// returns the NAV (net asset value) of the pool | function currentNAV() public view returns(uint) {
// calculates the NAV for ongoing loans with a maturityDate date in the future
uint nav_ = calcTotalDiscount();
// include ovedue assets to the current NAV calculation
for (uint i = 0; i < writeOffs.length; i++) {
// multiply ... | 0.5.15 |
//Claim tokens for first/second reserve wallets | function claimTokenReserve() onlyTokenReserve locked public {
address reserveWallet = msg.sender;
// Can't claim before Lock ends
require(block.timestamp > timeLocks[reserveWallet]);
// Must Only claim once
require(claimed[reserveWallet] == 0);
uint25... | 0.4.26 |
//Claim tokens for Libra team reserve wallet | function claimTeamReserve() onlyTeamReserve locked public {
uint256 vestingStage = teamVestingStage();
//Amount of tokens the team should have at this vesting stage
uint256 totalUnlocked = vestingStage.mul(allocations[teamReserveWallet]).div(teamVestingStages); // 总的解锁量
requ... | 0.4.26 |
// ------------------------------------------------------------------------
// 1,000 REKT Tokens per 1 ETH
// ------------------------------------------------------------------------ | function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 1200;
} else {
tokens = msg.value * 1000;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
... | 0.4.24 |
/**
* Mints Fuego NFTs
*/ | function mintFuego(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Flames");
require(numberOfTokens <= maxFuegoPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_FUEGO, "Purchase would exceed max supply of ... | 0.7.0 |
/**
* @notice Creates a proposal to replace, remove or add an adapter.
* @dev If the adapterAddress is equal to 0x0, the adapterId is removed from the registry if available.
* @dev If the adapterAddress is a reserved address, it reverts.
* @dev keys and value must have the same length.
* @dev proposalId can not be... | function submitProposal(
DaoRegistry dao,
bytes32 proposalId,
ProposalDetails calldata proposal,
Configuration[] memory configs,
bytes calldata data
) external override onlyMember(dao) reentrancyGuard(dao) {
require(
proposal.keys.length == proposal.values... | 0.8.10 |
/**
* @notice Processes a proposal that was sponsored.
* @dev Only members can process a proposal.
* @dev Only if the voting pass the proposal is processed.
* @dev Reverts when the adapter address is already in use and it is an adapter addition.
* @dev Reverts when the extension address is already in use and it is... | function processProposal(DaoRegistry dao, bytes32 proposalId)
external
override
reentrancyGuard(dao)
{
ProposalDetails memory proposal = proposals[address(dao)][proposalId];
IVoting votingContract = IVoting(dao.votingAdapter(proposalId));
require(address(votingContra... | 0.8.10 |
/**
* @notice If the extension is already registered, it removes the extension from the DAO Registry.
* @notice If the adapterOrExtensionAddr is provided, the new address is added as a new extension to the DAO Registry.
*/ | function _replaceExtension(DaoRegistry dao, ProposalDetails memory proposal)
internal
{
if (dao.extensions(proposal.adapterOrExtensionId) != address(0x0)) {
dao.removeExtension(proposal.adapterOrExtensionId);
}
if (proposal.adapterOrExtensionAddr != address(0x0)) {
... | 0.8.10 |
/**
* @notice Saves to the DAO Registry the ACL Flag that grants the access to the given `extensionAddresses`
*/ | function _grantExtensionAccess(
DaoRegistry dao,
ProposalDetails memory proposal
) internal {
for (uint256 i = 0; i < proposal.extensionAclFlags.length; i++) {
dao.setAclToExtensionForAdapter(
// It needs to be registered as extension
proposal.exte... | 0.8.10 |
/**
* @notice Saves the numeric/address configurations to the DAO registry
*/ | function _saveDaoConfigurations(DaoRegistry dao, bytes32 proposalId)
internal
{
Configuration[] memory configs = configurations[address(dao)][
proposalId
];
for (uint256 i = 0; i < configs.length; i++) {
Configuration memory config = configs[i];
i... | 0.8.10 |
/// @return the negation of p, i.e. p.add(p.negate()) should be zero. | function negate(G1Point memory p) internal pure returns (G1Point memory) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p... | 0.5.0 |
/// @return the sum of two points of G1 | function pointAdd(G1Point memory p1, G1Point memory p2)
internal view returns (G1Point memory r)
{
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
assembly {
success := stati... | 0.5.0 |
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.mul(1) and p.add(p) == p.mul(2) for all points p. | function pointMul(G1Point memory p, uint s)
internal view returns (G1Point memory r)
{
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x... | 0.5.0 |
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true. | function pairing(G1Point[] memory p1, G2Point[] memory p2)
internal view returns (bool)
{
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)... | 0.5.0 |
/// Convenience method for a pairing check for two pairs. | function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2)
internal view returns (bool)
{
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] =... | 0.5.0 |
/// Convenience method for a pairing check for four pairs. | function pairingProd4(
G1Point memory a1, G2Point memory a2,
G1Point memory b1, G2Point memory b2,
G1Point memory c1, G2Point memory c2,
G1Point memory d1, G2Point memory d2
)
internal view returns (bool)
{
G1Point[] memory p1 = new G1Point... | 0.5.0 |
/**
* MiMC-p/p with exponent of 7
*
* Recommended at least 46 rounds, for a polynomial degree of 2^126
*/ | function MiMCpe7( uint256 in_x, uint256 in_k, uint256 in_seed, uint256 round_count )
internal pure returns(uint256 out_x)
{
assembly {
if lt(round_count, 1) { revert(0, 0) }
// Initialise round constants, k will be hashed
let c := mload(0x40)
... | 0.5.0 |
/**
* Returns calculated merkle root
*/ | function verifyPath(uint256 leaf, uint256[15] memory in_path, bool[15] memory address_bits)
internal
pure
returns (uint256 merkleRoot)
{
uint256[15] memory IVs;
fillLevelIVs(IVs);
merkleRoot = leaf;
for (uint depth = 0; depth < TREE_DEPTH; depth+... | 0.5.0 |
// should not be used in production otherwise nullifier_secret would be shared with node! | function makeLeafHash(uint256 nullifier_secret, address wallet_address)
external
pure
returns (uint256)
{
// return MiMC.Hash([nullifier_secret, uint256(wallet_address)], 0);
bytes32 digest = sha256(abi.encodePacked(nullifier_secret, uint256(wallet_address)));
... | 0.5.0 |
/**
* @notice Deploys a new pool and LP token.
* @dev Decimals is an argument as not all ERC20 tokens implement the ERC20Detailed interface.
* An implementation where `getUnderlying()` returns the zero address is for ETH pools.
* @param poolName Name of the pool.
* @param underlying Address of the pool's... | function deployPool(
string calldata poolName,
uint256 depositCap,
address underlying,
LpTokenArgs calldata lpTokenArgs,
VaultArgs calldata vaultArgs,
ImplementationNames calldata implementationNames
) external onlyGovernance returns (Addresses memory addrs) {
... | 0.8.9 |
/**
* @notice Add a new implementation of type `name` to the factory.
* @param key of the implementation to add.
* @param name of the implementation to add.
* @param implementation of lp token implementation to add.
*/ | function _addImplementation(
bytes32 key,
bytes32 name,
address implementation
) internal returns (bool) {
mapping(bytes32 => address) storage currentImplementations = implementations[key];
if (currentImplementations[name] != address(0)) {
return false;
... | 0.8.9 |
/**
* @dev Crowdsale in the constructor takes addresses of
* the just deployed VLBToken and VLBRefundVault contracts
* @param _tokenAddress address of the VLBToken deployed contract
*/ | function VLBCrowdsale(address _tokenAddress, address _wallet, address _escrow, uint rate) public {
require(_tokenAddress != address(0));
require(_wallet != address(0));
require(_escrow != address(0));
escrow = _escrow;
// Set initial exchange rate
ETHUSD = rate;... | 0.4.18 |
/**
* @dev main function to buy tokens
* @param beneficiary target wallet for tokens can vary from the sender one
*/ | function buyTokens(address beneficiary) whenNotPaused public payable {
require(beneficiary != address(0));
require(validPurchase(msg.value));
uint256 weiAmount = msg.value;
// buyer and beneficiary could be two different wallets
address buyer = msg.sender;
wei... | 0.4.18 |
/**
* @dev check if the current purchase valid based on time and amount of passed ether
* @param _value amount of passed ether
* @return true if investors can buy at the moment
*/ | function validPurchase(uint256 _value) internal constant returns (bool) {
bool nonZeroPurchase = _value != 0;
bool withinPeriod = now >= startTime && now <= endTime;
bool withinCap = !capReached(weiRaised.add(_value));
// For presale we want to decline all payments less then minPre... | 0.4.18 |
/**
* @dev returns current token price based on current presale time frame
*/ | function getConversionRate() public constant returns (uint256) {
if (now >= startTime + 106 days) {
return 650;
} else if (now >= startTime + 99 days) {
return 676;
} else if (now >= startTime + 92 days) {
return 715;
} else if (now >= startTime... | 0.4.18 |
/**
* ERC677 transferandcall support
*/ | function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external {
// make sure that only chainlink transferandcalls are supported
require(msg.sender == tokenAddress);
// convert _data to address
bytes memory x = _data;
address _referredBy;
... | 0.5.17 |
/// @dev Liquifies tokens to link. | function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _link = tokensTo... | 0.5.17 |
// @dev Function for find if premine | function jackPotInfo() public view returns (uint256 jackPot, uint256 timer, address jackPotPretender) {
jackPot = jackPot_;
if (jackPot > totalLinkBalance()) {
jackPot = totalLinkBalance();
}
jackPot = SafeMath.div(jackPot,2);
timer = now - jackPotStartTime_;
jackPotPretender = jackPotPretende... | 0.5.17 |
/**
* @dev Calculate Referrers reward
* Level 1: 35%, Level 2: 20%, Level 3: 15%, Level 4: 10%, Level 5: 10%, Level 6: 5%, Level 7: 5%
*/ | function calculateReferrers(address _customerAddress, uint256 _referralBonus, uint8 _level) internal {
address _referredBy = referrers_[_customerAddress];
uint256 _percent = 35;
if (_referredBy != address(0x0)) {
if (_level == 2) _percent = 20;
if (_level == 3) _percent = 15;
if (_level == 4 || _le... | 0.5.17 |
/**
* @dev Calculate JackPot
* 40% from entryFee is going to JackPot
* The last investor (with 0.2 link) will receive the jackpot in 12 hours
*/ | function calculateJackPot(uint256 _incomingLink, address _customerAddress) internal {
uint256 timer = SafeMath.div(SafeMath.sub(now, jackPotStartTime_), 12 hours);
if (timer > 0 && jackPotPretender_ != address(0x0) && jackPot_ > 0) {
//pay jackPot
if (totalLinkBalance() < jackPot_) {
jackPot_ = total... | 0.5.17 |
// Anyone can usurpation the kingship | function usurpation() {
// Add more money for king usurpation cost
if (msg.sender == madKing) {
investInTheSystem(msg.value);
kingCost += msg.value;
} else {
if (onThrone + PEACE_PERIOD <= block.timestamp && msg.value >= kingCost * 110 / 100) {
... | 0.3.1 |
/**
* Event emitting fallback.
*
* Can be and only called by authorized caller.
* Delegate calls back with provided msg.data to emit an event.
*
* Throws if call failed.
*/ | function () {
if (!isAuthorized[msg.sender]) {
return;
}
// Internal Out Of Gas/Throw: revert this transaction too;
// Recursive Call: safe, all changes already made.
if (!msg.sender.delegatecall(msg.data)) {
throw;
}
} | 0.4.15 |
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/ | function transfer(address _to, uint256 _value) public {
require(_to != address(0), "Cannot use zero address");
require(_value > 0, "Cannot use zero value");
require (balanceOf[msg.sender] >= _value, "Balance not enough"); // Check if the sender has enough
require (balanceOf... | 0.5.9 |
// get today current max investment | function getMaxInvestmentToday(data storage control) internal view returns (uint)
{
if (control.startAt == 0) {
return 10000 ether; // disabled controlling, allow 10000 eth
}
if (control.startAt > now) {
return 10000 ether; // not started, allow 10000 eth
... | 0.4.24 |
// remove all investors and prepare data for the new round! | function doRestart() private {
uint txs;
for (uint i = addresses.length - 1; i > 0; i--) {
delete investors[addresses[i]]; // remove investor
addresses.length -= 1; // decrease addr length
if (txs++ == 150) { // stop on 150 investors (to prevent out of gas exce... | 0.4.24 |
// Thunderstorm!
// make the biggest investment today - and receive ref-commissions from ALL investors who not have a referrer in the next 10 days | function considerThunderstorm(uint amount) internal {
// if current Thunderstorm dead, delete him
if (thunderstorm.addr > 0x0 && thunderstorm.from + 10 days < now) {
thunderstorm.addr = 0x0;
thunderstorm.deposit = 0;
emit ThunderstormUpdate(msg.sender, "expired")... | 0.4.24 |
// Deposit LP tokens to MasterChef for Pud allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.shares > 0) {
uint256 pending =
user.shares.mul(pool.accPudPerShare).div(1e12).sub(... | 0.6.7 |
// Returns true iff the specified name is available for registration. | function available(uint256 id) public view returns(bool) {
// Not available if it's registered here or in its grace period.
if(expiries[id] + GRACE_PERIOD >= now) {
return false;
}
// Available if we're past the transfer period, or the name isn't
// registered i... | 0.5.16 |
/**
* @dev Register a name.
*/ | function _register(uint256 id, address owner, uint duration, bool updateRegistry) internal live onlyController returns(uint) {
require(available(id));
require(now + duration + GRACE_PERIOD > now + GRACE_PERIOD); // Prevent future overflow
expiries[id] = now + duration;
if(_exists(i... | 0.5.16 |
/**
* @dev Transfers a registration from the initial registrar.
* This function is called by the initial registrar when a user calls `transferRegistrars`.
*/ | function acceptRegistrarTransfer(bytes32 label, Deed deed, uint) external live {
uint256 id = uint256(label);
require(msg.sender == address(previousRegistrar));
require(expiries[id] == 0);
require(transferPeriodEnds > now);
uint registrationDate;
(,,registration... | 0.5.16 |
/**
* to update an split holder ratio at the index
* index ranges from 0..totalHolders -1
*/ | function setMintSplitHolder(uint256 index, address _wallet, uint256 _ratio) public onlyOwner returns (bool) {
if (index > totalHolders - 1)
return false;
holders[ index ] = _wallet;
MintSplitHolderRatios[ index ] = _ratio;
return true;
} | 0.4.26 |
/// @dev checks if required parameters are set for the contract | function _checkFee(uint256 _fee) internal view returns(bool) {
if(_fee > 0) {
require( msg.value >= _fee, "Value less than fee" );
}
return(true);
//return ( (_fee == 0 && msg.value == 0) || (registratorAddress != address(0) && msg.value >= _fee ));
} | 0.8.1 |
// @dev New Word register. | function memorialize(
string memory _words,
string memory _author,
uint64 _dob
)
external
payable
returns (uint256)
{
require( _checkFee(fee) );
Word memory _word = Word({
id: 0,
words: _words,
author: _author... | 0.8.1 |
/**
* Construct the token.
*
* This token must be created through a team multisig wallet, so that it is owned by that wallet.
*
* @param _name Token name
* @param _symbol Token symbol - should be all caps
* @param _initialSupply How many tokens we start with
* @param _decimals Number of decimal places
... | function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap)
UpgradeableToken(msg.sender) {
// Create any address, can be transferred
// to team multisig via changeOwner(),
// also remember to call setUpgradeMaster()
owner = m... | 0.4.11 |
/**
* This is an internal function, and it is the real operator to mint NFT to user,
* it will return an array of tokenID after minting.
*/ | function mintSpeficiedAmount(address owner, uint256 amount) internal returns (uint256[] memory) {
uint256[] memory minted_ = new uint256[](amount);
for(uint256 i = 0; i < amount; i ++) {
uint256 tokenIdToMint = _currentTokenId_ + i + 1;
_safeMint(owner, tokenIdToMint);
... | 0.8.7 |
/**
* This function overrides the function defined in ERC721 contract,
* before revealing or baseURI has not been set, it will always return the placeholder.
* otherwise, the sequenceId will be calculated and combined to tokenURI.
*/ | function tokenURI(uint256 tokenId_) public view override returns (string memory) {
require(_exists(tokenId_), "ERC721Metadata: URI query for nonexistent token");
if (!_isRevealed_) {
return bytes(_placeholderBaseURI_).length > 0 ?
string(abi.encodePacked(_placeholderBa... | 0.8.7 |
/// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller
/// as long as it is qualified.
/// @dev We burn the lotSize of the Deposit in order to maintain
/// the TBTC supply peg in the Vending Machine. VendingMachine must be approved
/// by the caller to burn the required amo... | function tbtcToTdt(uint256 _tdtId) public {
require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist");
require(isQualified(address(_tdtId)), "Deposit must be qualified");
uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc();
require(tbtcToken.balanc... | 0.5.17 |
/// @notice Transfer the tBTC Deposit Token and mint TBTC.
/// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller.
/// Vending Machine must be approved to transfer TDT by the caller.
/// @param _tdtId ID of tBTC Deposit Token to sell. | function tdtToTbtc(uint256 _tdtId) public {
require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist");
require(isQualified(address(_tdtId)), "Deposit must be qualified");
tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId);
// If the backing Deposit doe... | 0.5.17 |
/// @notice Qualifies a deposit and mints TBTC.
/// @dev User must allow VendingManchine to transfer TDT. | function unqualifiedDepositToTbtc(
address payable _depositAddress,
bytes4 _txVersion,
bytes memory _txInputVector,
bytes memory _txOutputVector,
bytes4 _txLocktime,
uint8 _fundingOutputIndex,
bytes memory _merkleProof,
uint256 _txIndexInBlock,
byt... | 0.5.17 |
/// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient,
/// and using the TDT to redeem corresponding Deposit as _finalRecipient.
/// This function will revert if the Deposit is not in ACTIVE state.
/// @dev Vending Machine transfers TBTC allowance to Deposit.
/// @param _depos... | function tbtcToBtc(
address payable _depositAddress,
bytes8 _outputValueBytes,
bytes memory _redeemerOutputScript,
address payable _finalRecipient
) public {
require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist");
Deposit _d = ... | 0.5.17 |
/**
* @notice Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing an all permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @de... | function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, us... | 0.8.4 |
/**
* @notice Determines the permission bitmask an operator can set on the
* target permission set
* @notice Used to calculate the permission bitmask to be set when requested
* in `updateRole` and `updateFeatures` functions
*
* @dev Calculated based on:
* 1) operator's own permission set read from ... | function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) {
// read operator's permissions
uint256 p = userRoles[operator];
// taking into account operator's permissions,
// 1) enable the permissions desired on the `target`
target |= p & desired;
// 2) ... | 0.8.4 |
// for swap form | function GetCurrentPriceForETH() public view returns (uint256) {
uint256 tokens;
int ethusd;
uint256 ethprice;
ethusd = getLatestPrice();
ethprice = uint256(ethusd) / priceZero;
if (now <= bonusEnds) {tokens = ethp... | 0.6.12 |
// for swap form (/10) | function GetCurrentPrice() public view returns (uint256) {
uint256 tokens;
if (now <= bonusEnds) {tokens = 25;} // PHASE 1: 1ADR = 2.5$
else if (now > bonusEnds && now < bonusEnds1) {tokens = 27;} // PHASE 2: 1ADR = 2.7$
else if (now > bonusEnds1 &&... | 0.6.12 |
// Only Dev. Pre-sale info. | function PreSale(uint _bonusEnds, uint _bonusEnds1, uint _bonusEnds2, uint _bonusEnds3, uint _endDate, uint _priceZero) public {
require(msg.sender == devaddr, "dev: wtf?");
bonusEnds = _bonusEnds;
bonusEnds1 = _bonusEnds1;
bonusEnds2 = _bonusEnds2;
bonusEnds3 = _bonusEnds3;... | 0.6.12 |
/**
* @dev XRT emission value for utilized gas
*/ | function wnFromGas(uint256 _gas) view returns (uint256) {
// Just return wn=gas when auction isn't finish
if (auction.finalPrice() == 0)
return _gas;
// Current gas utilization epoch
uint256 epoch = totalGasUtilizing / gasEpoch;
// XRT emission with addition... | 0.4.24 |
/**
* @dev Create robot liability smart contract
* @param _demand ABI-encoded demand message
* @param _offer ABI-encoded offer message
*/ | function createLiability(
bytes _demand,
bytes _offer
)
external
onlyLighthouse
gasPriceEstimated
returns (RobotLiability liability) { // Store in memory available gas
uint256 gasinit = gasleft();
// Create liability
liability = ne... | 0.4.24 |
/**
* @dev Create lighthouse smart contract
* @param _minimalFreeze Minimal freeze value of XRT token
* @param _timeoutBlocks Max time of lighthouse silence in blocks
* @param _name Lighthouse subdomain,
* example: for 'my-name' will created 'my-name.lighthouse.1.robonomics.eth' domain
*/ | function createLighthouse(
uint256 _minimalFreeze,
uint256 _timeoutBlocks,
string _name
)
external
returns (address lighthouse)
{
bytes32 lighthouseNode
// lighthouse.3.robonomics.eth
= 0x87bd923a85f096b00a4a347fb56cef68e95319b3d... | 0.4.24 |
/**
* @dev Is called whan after liability finalization
* @param _gas Liability finalization gas expenses
*/ | function liabilityFinalized(
uint256 _gas
)
external
gasPriceEstimated
returns (bool)
{
require(gasUtilizing[msg.sender] > 0);
uint256 gas = _gas - gasleft();
require(_gas > gas);
totalGasUtilizing += gas;
gasUtilizing... | 0.4.24 |
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}. Note that
* a contract cannot be deployed twice using the same salt.
*/ | function deploy(bytes32 salt, bytes memory bytecode) internal returns (address) {
address addr;
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Fail... | 0.6.6 |
/**
* @dev Tokens transfer will not work if sender or recipient has dividends
*/ | function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
require(_value <= accounts[_from].balance);
require(accounts[_to].balance + _value >= accounts[_to].balance);
uint256 fromOwing = dividendBalanceOf(_from);
uint256 toO... | 0.4.24 |
/// @dev Get All Official Vaults List | function getAllVaultAddress() external view returns(address[] memory workingVaults) {
address[] memory vaults = vaultLists;
uint256 length = vaults.length;
bool[] memory status = new bool[](length);
// get abandon Vaults status
uint256 workNumber;
for (uint256 i; i < leng... | 0.7.6 |
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)`
*
* @dev Called by token owner on his own or approved address,
* an address appro... | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
// or unsafe transfer
// if `FEATURE_UNSAFE_TRANSFERS` is enabled
// or receiver has `ROLE_ERC20_RECEIVER` permission
// or se... | 0.8.4 |
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev Inspired by ERC721 safeTransferFrom, this function allows to
* send arbitrary data to the receiver on successful token transfer
* @dev Called by token owner on his own or approved addres... | function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public {
// first delegate call to `unsafeTransferFrom`
// to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC20... | 0.8.4 |
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner
*
* @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)`
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @param _spender an ad... | function approve(address _spender, uint256 _value) public returns (bool success) {
// non-zero spender address check - Zeppelin
// obviously, zero spender address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
require(_spender != address(0), "ERC20: approve to th... | 0.8.4 |
/**
* @notice Increases the allowance granted to `spender` by the transaction sender
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to increase by is zero or too big and causes arithmetic overflow
*
* @param _spender an address approved by... | function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value and arithmetic overflow check on the allowance
require(currentVal + _value > currentVal, "zero v... | 0.8.4 |
/**
* @notice Decreases the allowance granted to `spender` by the caller.
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to decrease by is zero or is bigger than currently allowed value
*
* @param _spender an address approved by the caller... | function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value check on the allowance
require(_value > 0, "zero value approval decrease");
// verify allow... | 0.8.4 |
/**
* @notice Gets current voting power of the account `_of`
* @param _of the address of account to get voting power of
* @return current cumulative voting power of the account,
* sum of token balances of all its voting delegators
*/ | function getVotingPower(address _of) public view returns (uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// lookup the history and return latest element
return history.length == 0? 0: history[h... | 0.8.4 |
/**
* @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`
* @dev Writes to `votingDelegates` and `votingPowerHistory` mappings
*
* @param _from delegator who delegates his voting power
* @param _to delegate who receives the voting power
*/ | function __delegate(address _from, address _to) private {
// read current delegate to be replaced by a new one
address _fromDelegate = votingDelegates[_from];
// read current voting power (it is equal to token balance)
uint256 _value = tokenBalances[_from];
// reassign voting delegate to `_to`
... | 0.8.4 |
/**
* @dev Auxiliary function to update voting power of the delegate `_of`
* from value `_fromVal` to value `_toVal`
*
* @param _of delegate to update its voting power
* @param _fromVal old voting power of the delegate
* @param _toVal new voting power of the delegate
*/ | function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if there is an existing voting power value stored for current block
... | 0.8.4 |
//Anyone can pay the gas to create their very own Tester token | function create() public returns (uint256 _tokenId) {
bytes32 sudoRandomButTotallyPredictable = keccak256(abi.encodePacked(totalSupply(),blockhash(block.number - 1)));
uint8 body = (uint8(sudoRandomButTotallyPredictable[0])%5)+1;
uint8 feet = (uint8(sudoRandomButTotallyPredictable[1])%5)+1;
uint8 ... | 0.4.24 |
// --- 'require' functions --- | function _requireValidRecipient(address _recipient) internal view {
require(
_recipient != address(0) &&
_recipient != address(this),
"LQTY: Cannot transfer tokens directly to the LQTY token contract or the zero address"
);
// require(
// _recipie... | 0.6.11 |
/** requires an encrypted bidToken (generated on marsmaiers.com)
======================================
== DO NOT CALL THIS METHOD DIRECTLY ==
======================================
if you call this method directly (through etherscan or by hand), your bid
will NOT be counted. your funds will be unrefundable, a... | function bid(string calldata bidToken) public payable {
// validate input
bytes memory bidTokenCheck = bytes(bidToken);
require(bidTokenCheck.length > 0, 'invalid input');
// ensure project is still ongoing
require(!projectConcluded, 'project has concluded');
// ensure bid meets min
requir... | 0.8.9 |
/// @notice chooses a winner, and moves value ofbidToken to winnings
/// @param tokenId day of year to mint
/// @param bidToken winning bid token | function settle(uint256 tokenId, string memory bidToken) public onlyRole(SETTLER_ROLE) {
// validate input
bytes memory bidTokenCheck = bytes(bidToken);
require(tokenId >= 1 && tokenId <= 365 && bidTokenCheck.length > 0, 'invalid input');
// no more winners allowed
require(!projectConcluded, 'proje... | 0.8.9 |
/// @notice allows owner to cash out, from the designated winnings only
/// @param amount value in wei to transfer
/// @param to address to transfer funds to | function withdraw(uint256 amount, address to) external onlyRole(MANAGER_ROLE) {
require(amount > 0, 'invalid input');
require(amount <= winnings, 'amount exceeds winnings');
// subtract amount
winnings = winnings - amount;
// send funds to destination
payable(to).sendValue(amount);
} | 0.8.9 |
/// @notice transfers funds for a lost bid back to original bidder. requires a signed signature generated on marsmaiers.com
/// @param bidToken bid token representing the lost bid you are refunding
/// @param nonce nonce string, generated along with signature
/// @param signature signature containing bidToken and nonce... | function signedRefund(
string memory bidToken,
string memory nonce,
bytes memory signature
) public nonReentrant {
// infer message by hashing input params. signature must contain a hash with the same message
bytes32 message = keccak256(abi.encode(bidToken, nonce));
// validate inferred messa... | 0.8.9 |
/// @notice generic mechanism to return the value of a list of bidTokens to their original bidder. only enabled once project has concluded.
/// @param bidTokens array of bid tokens to refund | function refund(string[] memory bidTokens) public nonReentrant {
// only allow unsigned refunds once project is concluded
require(projectConcluded, 'project has not concluded');
// execute refund for each bidToken
for (uint256 i = 0; i < bidTokens.length; i++) {
_refund(bidTokens[i]);
}
} | 0.8.9 |
/// allows *anyone* to mark the project as concluded, if the entire year has elapsed.
/// this should normally never be needed, as minting the final piece also marks
/// the project as concluded. in the unlikely event the final piece is never minted,
/// this gives the community a way to release all pending bids. | function concludeProject() public {
// require block time to be after January 2, 2023 1:00:00 AM GMT (one day of buffer)
require(block.timestamp > 1672621200, 'year is not over');
// mark project as concluded
projectConcluded = true;
} | 0.8.9 |
// === PRIVATE ===
// internal method to validate and process return a bid, using bidder and amount keyed to bidToken | function _refund(string memory bidToken) private {
// ensure bidToken exists with a balance, and was placed by _msgSender
require(bids[bidToken] > 0, 'bid does not exist');
// stash and zero bid
uint256 amount = bids[bidToken];
bids[bidToken] = 0;
// don't zero bidder (prevents future reuse of... | 0.8.9 |
/**
@notice This function adds liquidity to a Yearn vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Yearn vault address
@param superVault Super vault to depoist toVault tokens into (address(0) if n... | function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
address superVault,
bool isAaveUnderlying,
uint256 minYVTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate
)... | 0.5.17 |
/* checks if it's time to make payouts. if so, send the ether */ | function performPayouts()
{
uint paidPeriods = 0;
uint investorsPayout;
uint beneficiariesPayout = 0;
while(m_latestPaidTime + PAYOUT_INTERVAL < now)
{
uint idx;
/* pay the beneficiaries */
if(m_beneficiaries.length > 0)
{
beneficiariesPayout = (this.balance * BENEFICI... | 0.4.8 |
/// @notice Moves all tokens to a new reserve contract | function migrateReserves(
address newReserve,
address[] memory tokens
)
public
onlyGov
{
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 token = IERC20(tokens[i]);
uint256 bal = token.balanceOf(address(this));
SafeERC20.... | 0.5.17 |
/// @notice Prizes mints by owner | function mintPrizes(uint amount) public onlyOwner {
uint currentTotalSupply = totalSupply();
/// @notice Prize mints must mint first, and cannot be minted after the maximum has been reached
require(currentTotalSupply < MAX_PRIZE_MINTS, "DeadFellazToken: Max prize mint limit reached");
if (currentTotal... | 0.8.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.