comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
// note this will always return 0 before update has been called successfully for the first time. | function consult(address token, uint amountIn) internal view returns (uint amountOut) {
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'ExampleOracleSimple: INVALID_TOKEN');
amountOut = price1Average.... | 0.6.6 |
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid signature from `ow... | function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override onlyOnDeployedNetwork whenNotPaused {
// solhint-disable-next-line
require(deadline >= block.timestamp, "ERC20Wi... | 0.6.6 |
// ------------------------------------------------------------------------
// Accepts ETH and transfers ZAN tokens based on exchage rate and state
// ------------------------------------------------------------------------ | function () public payable {
uint eth_sent = msg.value;
uint tokens_amount = eth_sent.mul(exchangeRate);
require(eth_sent > 0);
require(exchangeRate > 0);
require(stateStartDate < now && now < stateEndDate);
require(balances[owner] >= tokens_amount);
... | 0.4.21 |
// ------------------------------------------------------------------------
// Switches crowdsale stages: PreSale -> Round One -> Round Two
// ------------------------------------------------------------------------ | function switchCrowdSaleStage() external onlyOwner {
require(!isInFinalState && !isInRoundTwoState);
if (!isInPreSaleState) {
isInPreSaleState = true;
exchangeRate = 1500;
saleCap = (3 * 10**6) * (uint(10) ** decimals);
emit SwitchCrowdSale... | 0.4.21 |
/// @dev Transfers tokens to a specified address with additional data if the recipient is a contact.
/// @param to The address to transfer tokens to.
/// @param value The amount of tokens to be transferred.
/// @param data The extra data to be passed to the receiving contract.
/// @return A boolean that indicates if th... | function transferAndCall(address to, uint256 value, bytes data) external canTransfer returns (bool) {
require(to != address(this));
require(super.transfer(to, value));
emit Transfer(msg.sender, to, value, data);
if (isContract(to)) {
require(contractFallback(msg.sender, ... | 0.4.26 |
/// @dev Transfers tokens from one address to another.
/// @param from The address to transfer tokens from.
/// @param to The address to transfer tokens to.
/// @param value The amount of tokens to be transferred.
/// @return A boolean that indicates if the operation was successful. | function transferFrom(address from, address to, uint256 value) public canTransfer returns (bool) {
require(super.transferFrom(from, to, value));
if (isContract(to) && !contractFallback(from, to, value, new bytes(0))) {
if (to == _bridgeContract) {
revert();
}... | 0.4.26 |
/// @dev Transfers tokens to a specified addresses (optimized version for initial sending tokens).
/// @param recipients Addresses to transfer tokens to.
/// @param values Amounts of tokens to be transferred.
/// @return A boolean that indicates if the operation was successful. | function airdrop(address[] recipients, uint256[] values) public canTransfer returns (bool) {
require(recipients.length == values.length);
uint256 senderBalance = _balances[msg.sender];
for (uint256 i = 0; i < values.length; i++) {
uint256 value = values[i];
address t... | 0.4.26 |
/// @dev Transfers funds stored on the token contract to specified recipient (required by token bridge). | function claimTokens(address token, address to) public onlyOwnerOrBridgeContract {
require(to != address(0));
if (token == address(0)) {
to.transfer(address(this).balance);
} else {
ERC20 erc20 = ERC20(token);
uint256 balance = erc20.balanceOf(address(th... | 0.4.26 |
// --- administration --- | function file(bytes32 what, address data) external auth {
if (what == "outputConduit") { outputConduit = data; }
else if (what == "jug") { jug = JugAbstract(data); }
else revert("RwaUrn/unrecognised-param");
emit File(what, data);
} | 0.5.12 |
// --- cdp operation ---
// n.b. that the operator must bring the gem | function lock(uint256 wad) external operator {
require(wad <= 2**255 - 1, "RwaUrn/overflow");
DSTokenAbstract(gemJoin.gem()).transferFrom(msg.sender, address(this), wad);
// join with address this
gemJoin.join(address(this), wad);
vat.frob(gemJoin.ilk(), address(this), addre... | 0.5.12 |
// n.b. DAI can only go to the output conduit | function draw(uint256 wad) external operator {
require(outputConduit != address(0));
bytes32 ilk = gemJoin.ilk();
jug.drip(ilk);
(,uint256 rate,,,) = vat.ilks(ilk);
uint256 dart = divup(mul(RAY, wad), rate);
require(dart <= 2**255 - 1, "RwaUrn/overflow");
v... | 0.5.12 |
// n.b. anyone can wipe | function wipe(uint256 wad) external {
daiJoin.join(address(this), wad);
bytes32 ilk = gemJoin.ilk();
jug.drip(ilk);
(,uint256 rate,,,) = vat.ilks(ilk);
uint256 dart = mul(RAY, wad) / rate;
require(dart <= 2 ** 255, "RwaUrn/overflow");
vat.frob(ilk, address(... | 0.5.12 |
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/ | function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregato... | 0.5.17 |
// This function allows governance to take unsupported tokens out of the
// contract, since this one exists longer than the other pools.
// This is in an effort to make someone whole, should they seriously
// mess up. There is no guarantee governance will vote to return these.
// It also allows for removal of airdroppe... | function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to)
external
{
// only gov
require(msg.sender == owner(), "!governance");
// cant take staked asset
require(_token != uni_lp, "uni_lp");
// cant take reward asset
require(_tok... | 0.5.17 |
/**
@dev constructor
@param _token smart token governed by the converter
@param _registry address of a contract registry contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the firs... | function BancorConverter(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee,
IERC20Token _connectorToken,
uint32 _connectorWeight
)
public
SmartTokenController(_token)
validAddress(_registry)
validMaxConversion... | 0.4.21 |
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable ... | function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorW... | 0.4.21 |
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector,... | function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
... | 0.4.21 |
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/ | function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromTo... | 0.4.21 |
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/ | function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled); // v... | 0.4.21 |
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/ | function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 tokenSupply = token.totalSupply();
... | 0.4.21 |
/**
@dev returns the expected return for selling one of the connector tokens for another connector token
@param _fromConnectorToken contract address of the connector token to convert from
@param _toConnectorToken contract address of the connector token to convert to
@param _sellAmount amount to ... | function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount)
public
view
active
validConnector(_fromConnectorToken)
validConnector(_toConnectorToken)
returns (uint256)
{
Connector storage fromCon... | 0.4.21 |
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must ... | function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {
uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && a... | 0.4.21 |
/**
@dev helper, dispatches the Conversion event
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
*/ | function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {
// fee amount is converted to 255 bits -
// negative amount means the fee is taken from the source token, positive amount means its taken from the target... | 0.4.21 |
/**
* @dev get '_account' stakes by page
*/ | function getStakes(address _account, uint _index, uint _offset) external view returns (StakeSet.Item[] memory items) {
uint totalSize = userOrders(_account);
require(0 < totalSize && totalSize > _index, "getStakes: 0 < totalSize && totalSize > _index");
uint offset = _offset;
if (tot... | 0.5.17 |
// todo: get token usdt price from swap | function getUSDTPrice(address _token) public view returns (uint) {
if (payToken == _token) {return 1 ether;}
(bool success, bytes memory returnData) = lpAddress[_token].staticcall(abi.encodeWithSignature("getReserves()"));
if (success) {
(uint112 reserve0, uint112 reserve1, ) =... | 0.5.17 |
// function getHashrate(uint256 staticHashrate,uint m) private pure returns (uint256 hashrate) {
// if(m==0){
// hashrate = staticHashrate.mul(18).div(100);
// }else if(m==1){
// hashrate = staticHashrate.mul(16).div(100);
// }else if(m==2){
// hashrate = sta... | function levelCostU(uint256 value,uint256 vip) public pure returns(uint256 u) {
require(value<=6&&value>vip, "levelCostU: vip false");
if(value==1){
u=100;
}else if(value==2){
if(vip==0){
u=300;
}else{
... | 0.5.17 |
// https://uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/ | function _pairFor(address _factory, address tokenA, address tokenB) internal pure returns (address pair) {
// sort tokens
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != token1, "TWAP: identical addresses");
require(token0 != address(0), "TWA... | 0.5.17 |
/* update */ | function update(address[] calldata pairs) external {
for (uint i = 0; i < pairs.length; i++) {
// note: not reusing canUpdate() because we need the bucket variable
address pair = pairs[i];
uint index = timestampToIndex(block.timestamp);
Bucket storage bucket = buckets[pair][index];
... | 0.5.17 |
/* consult */ | function _getCumulativePrices(
address tokenIn,
address tokenOut
) internal view returns (uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed) {
uint currentIndex = timestampToIndex(block.timestamp);
uint firstBucketIndex = (currentIndex + 1) % periodsPerWindow;
address pair = _... | 0.5.17 |
/**
* @dev Returns the amount out corresponding to the amount in for a given token using the
* @dev moving average over the time range [now - [windowSize, windowSize - periodSize * 2], now]
* @dev update must have been called for the bucket corresponding to timestamp `now - windowSize`
*/ | function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) {
uint pastPriceCumulative;
uint currentPriceCumulative;
uint timeElapsed;
(pastPriceCumulative, currentPriceCumulative, timeElapsed) = _getCumulativePrices(tokenIn, tokenOut);
return _comput... | 0.5.17 |
/** @dev Calls createDispute function of the specified arbitrator to create a dispute.
* @param _arbitrator The arbitrator of prospective dispute.
* @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
* @param _metaevidenceURI Link to metaevidence of prospective dispute.
*/ | function createDispute(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI) external payable {
uint arbitrationCost = _arbitrator.arbitrationCost(_arbitratorExtraData);
require(msg.value >= arbitrationCost, "Insufficient message value.");
uint dispute... | 0.5.11 |
/** @dev Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _party The side to which the caller wants to contribute.
*/ | function appeal(uint _localDisputeID, Party _party) external payable {
require(_party != Party.RefuseToArbitrate, "You can't fund an appeal in favor of refusing to arbitrate.");
uint8 side = uint8(_party);
DisputeStruct storage dispute = disputes[_localDisputeID];
(uint appealPerio... | 0.5.11 |
/** @dev To be called by the arbitrator of the dispute, to declare winning side.
* @param _externalDisputeID ID of the dispute in arbitrator contract.
* @param _ruling The side to which the caller wants to contribute.
*/ | function rule(uint _externalDisputeID, uint _ruling) external {
uint _localDisputeID = arbitratorExternalIDtoLocalID[msg.sender][_externalDisputeID];
DisputeStruct storage dispute = disputes[_localDisputeID];
require(msg.sender == address(dispute.arbitrator), "Unauthorized call.");
r... | 0.5.11 |
/* Initializes the contract */ | function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {
balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens.
totalSupply = initialSupply; // Update total supply.
name = tokenName; // S... | 0.4.23 |
/// @notice Send `_value` tokens to `_to` in behalf of `_from`.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The amount to send. | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _v... | 0.4.23 |
/// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf.
/// @param _spender The address authorized to spend.
/// @param _value The max amount they can spend. | function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens.
return true;
} | 0.4.23 |
/* Overrides basic transfer function due to comision value */ | function transfer(address _to, uint256 _value) public {
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
... | 0.4.23 |
/* Internal, updates the profit value */ | function _updateProfit(uint256 _increment, bool add) internal{
if (add){
// Increase the profit value
profit = profit + _increment;
}else{
// Decrease the profit value
if(_increment > profit){ profit = 0; }
else{ profit = profit - _incre... | 0.4.23 |
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens.
/// @param target Address to be frozen.
/// @param freeze Either to freeze target or not. | function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not.
FrozenFunds(target, freeze); // Notifies the blockchain about the change of state.
} | 0.4.23 |
/// @notice Deposits Ether to the contract | function deposit() payable public returns(bool success) {
require((this.balance + msg.value) > this.balance); // Checks for overflows.
//Contract has already received the Ether when this function is executed.
_updateSolvency(this.balance); // Updates the solvency value of the contract.
... | 0.4.23 |
/// @notice The owner withdraws Ether from the contract.
/// @param amountInWeis Amount of ETH in WEI which will be withdrawed. | function withdraw(uint amountInWeis) onlyOwner public {
LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
_updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
_updateProfit(amountInWeis, true); ... | 0.4.23 |
// For pushing pre-ICO records | function push(address buyer, uint256 amount) public onlyOwner { //b753a98c
require(balances[wallet] >= amount);
require(now < startDate);
require(buyer != wallet);
preICO_address[ buyer ] = true;
// Transfer
balances[wallet] = balances[wallet].sub(amount);
... | 0.4.18 |
/// @dev Mature the fyToken by recording the chi. | function _mature()
private
returns (uint256 _chiAtMaturity)
{
(_chiAtMaturity,) = oracle.get(underlyingId, CHI, 0); // The value returned is an accumulator, it doesn't need an input amount
chiAtMaturity = _chiAtMaturity;
emit SeriesMatured(_chiAtMaturity);
} | 0.8.6 |
/// @dev Retrieve the chi accrual since maturity, maturing if necessary.
/// Note: Call only after checking we are past maturity | function _accrual()
private
returns (uint256 accrual_)
{
if (chiAtMaturity == CHI_NOT_SET) { // After maturity, but chi not yet recorded. Let's record it, and accrual is then 1.
_mature();
} else {
(uint256 chi,) = oracle.get(underlyingId, CHI, 0); // The v... | 0.8.6 |
/// @dev Burn fyToken after maturity for an amount that increases according to `chi`
/// If `amount` is 0, the contract will redeem instead the fyToken balance of this contract. Useful for batches. | function redeem(address to, uint256 amount)
external override
afterMaturity
returns (uint256 redeemed)
{
uint256 amount_ = (amount == 0) ? _balanceOf[address(this)] : amount;
_burn(msg.sender, amount_);
redeemed = amount_.wmul(_accrual());
join.exit(to, redeem... | 0.8.6 |
/// @dev Burn fyTokens.
/// Any tokens locked in this contract will be burned first and subtracted from the amount to burn from the user's wallet.
/// This feature allows someone to transfer fyToken to this contract to enable a `burn`, potentially saving the cost of `approve` or `permit`. | function _burn(address from, uint256 amount)
internal override
returns (bool)
{
// First use any tokens locked in this contract
uint256 available = _balanceOf[address(this)];
if (available >= amount) {
return super._burn(address(this), amount);
} else {
... | 0.8.6 |
/**
* @dev From ERC-3156. Loan `amount` fyDai to `receiver`, which needs to return them plus fee to this contract within the same transaction.
* Note that if the initiator and the borrower are the same address, no approval is needed for this contract to take the principal + fee from the borrower.
* If the borrower t... | function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes memory data)
external override
beforeMaturity
returns(bool)
{
require(token == address(this), "Unsupported currency");
_mint(address(receiver), amount);
require(receiver.onFlashLoa... | 0.8.6 |
// public (Early Bird Mint) 150 to mint | function earlyBirdMint() public payable {
uint256 supply = totalSupply();
require(
earlyBirdMinting,
"Error: Early Bird minting is not active yet."
);
require(supply < 250, "Error: Maximum limit surpassed"); // max total mints is 100 marketing, 150 earlybird... | 0.8.7 |
// public marketing mint 100 | function marketingMint() public payable onlyOwnerOrDev {
uint256 supply = totalSupply();
require(
marketingMinting,
"Error: Marketing minting is not active yet."
);
require(supply < 100, "Error you may only mint 100 NFTs"); // max total mints is 100 marketin... | 0.8.7 |
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/ | function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (... | 0.5.17 |
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/ | function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
dAppToken.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true... | 0.5.17 |
/**
* @dev Called by user to pay joining membership fee
*/ | function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
dAppToken.addToWhit... | 0.5.17 |
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/ | function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligi... | 0.5.17 |
/**
* @dev Called by existed member if wish to Withdraw membership.
*/ | function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(dAppToken.totalLockedBalance(msg.sender, now) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardO... | 0.5.17 |
/**
* @dev Called by existed member if wish to switch membership to other address.
* @param _add address of user to forward membership.
*/ | function switchMembership(address _add) external {
require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add));
require(dAppToken.totalLockedBalance(msg.sender, now) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
... | 0.5.17 |
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id | function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length... | 0.5.17 |
/// @dev Get All role ids array that has been assigned to a member so far. | function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
... | 0.5.17 |
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/ | function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].me... | 0.5.17 |
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/ | function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
} | 0.5.17 |
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/ | function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of do... | 0.5.17 |
/**
* @dev Stake rPEPE-ETH LP tokens
*
* Requirement
*
* - In this pool, don't care about 2.5% fee for stake/unstake
*
* @param amount: Amount of LP tokens to deposit
*/ | function stake(uint256 amount) public {
require(amount > 0, "Staking amount must be more than zero");
// Transfer tokens from staker to the contract amount
require(IUniswapV2Pair(_UniswapV2Pair).transferFrom(_msgSender(), address(this), uint(amount)), "It has failed to transfer tokens from stake... | 0.6.6 |
/**
* @dev count and return pepe amount from lp token amount in uniswap v2 pool
*
* Formula
*
* - rPEPE = (staked LP / total LP in uniswap pool) * rPEPE in uniswap pool
*/ | function _getStakedPepeAmount(uint256 amount) internal view returns (uint256) {
(uint112 pepeAmount,,) = IUniswapV2Pair(_UniswapV2Pair).getReserves();
// get the total amount of LP token in uniswap v2 pool
uint totalAmount = IUniswapV2Pair(_UniswapV2Pair).totalSupply();
return amount.mu... | 0.6.6 |
// Standard mint function | function mint(uint256 _amount) public payable {
uint256 supply = totalSupply();
require( saleIsActive, "Sale isn't active" );
require( _amount > 0 && _amount < 16, "Can only mint between 1 and 15 tokens at once" );
require( (supply + _amount) <= (MAX_SUPPLY - ... | 0.8.7 |
/**
* @notice withdraw any Dai accumulated as dividends, and any tokens that might have been erroneously sent to this contract
* @param token address of token to withdraw
* @param amount amount of token to withdraw
* @return true if success
*/ | function withdrawERC20(address token, uint256 amount) external returns (bool) {
require(msg.sender == _poolSource, "Only designated source can withdraw any token");
require(token != address(_wToken), "Cannot withdraw asset token this way");
IERC20(token).safeTransfer(_poolSource, amount);
... | 0.6.8 |
/**
* @notice deposit Dai and get back wTokens
* @param amount amount of Dai to deposit
* @return true if success
*/ | function swapWithDai(uint256 amount) external returns (bool) {
require(amount > 0, "Dai amount must be greater than 0");
uint256 tokenAmount = daiToToken(amount);
// through not strictly needed, useful to have a clear message for this error case
require(_wToken.balanceOf(address(... | 0.6.8 |
/**
* @notice deposit USDT and get back wTokens
* @param amount amount of USDT to deposit
* @return true if success
*/ | function swapWithUSDT(uint256 amount) external returns (bool) {
require(amount > 0, "USDT amount must be greater than 0");
uint256 tokenAmount = usdtToToken(amount);
require(_wToken.balanceOf(address(this)) >= tokenAmount, "Insufficient token supply in the pool");
// safeTransf... | 0.6.8 |
/// @notice A public call to increase the peg by 4%. Can only be called once every 12 hours, and only if
/// there is there is <= 2% as much Ether value in the contract as there is Dai value.
/// Example: with a peg of 100, and 10000 total Dai in the vault, the ether balance of the
/// vault mus... | function increasePeg() external {
// check that the total value of eth in contract is <= 2% the total value of dai in the contract
require (address(this).balance.mul(etherPeg) <= daiContract.balanceOf(address(this)).div(50));
// check that peg hasn't been changed in last 12 hours
re... | 0.5.10 |
/// @notice All units are minimum denomination, ie base unit *10**-18
/// Use this payable function to buy INCH from the contract with Wei. Rates are based on premium
/// and etherPeg. For every Wei deposited, msg.sender recieves etherPeg/(0.000001*premium) INCH.
/// Example: If the peg is 100, ... | function __buyInchWithWei() external payable {
// Calculate the amount of inch give to msg.sender
uint _inchToBuy = msg.value.mul(etherPeg).mul(premiumDigits).div(premium);
// Require that INCH returned is not 0
require(_inchToBuy > 0);
// Transfer INCH to Purchaser
... | 0.5.10 |
/// @param _inchToBuy: amount of INCH (in mininum denomination) msg.sender wishes to purchase
/// @notice All units are in minimum denomination, ie base unit *10**-18
/// Use this payable to buy INCH from the contract using Dai. Rates are based on premium.
/// For every Dai deposited, msg.sender reciev... | function __buyInchWithDai(uint _inchToBuy) external {
// Calculate the amount of Dai to extract from the purchaser's wallet based on the premium
uint _daiOwed = _inchToBuy.mul(premium).div(premiumDigits);
// Take Dai from the purchaser and transfer to vault contract
daiContract.trans... | 0.5.10 |
// join presale - just send ETH to contract,
// remember to check GAS LIMIT > 70000! | receive() external payable {
// only if not ended
require(!presaleEnded, "Presale ended");
// only if within time limit
require(block.timestamp < presaleEnd, "Presale time's up");
// record new user balance if possible
uint256 amount = msg.value + balances[msg.sen... | 0.8.2 |
// withdraw ETH from contract
// can be used by user and owner
// return false if nothing to do | function withdraw() external returns (bool) {
if (!presaleEnded) {
// end and fail presale if failsafe time passed
if (block.timestamp > presaleEnd + failSafeTime) {
presaleEnded = true;
presaleFailed = true;
// don't return true, you... | 0.8.2 |
// Send {tokens} amount of tokens from address {from} to address {to}
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require( allowed[from][msg.sender] >= tokens && balances[from] >= tokens && tokens > 0 );
balances[from] -= tokens;
allowed[from][msg.sender] -= tokens;
balances[to] += tokens;
emit ... | 0.5.1 |
// automated buyback | function autoBuyBack(uint256 amountInWei) internal {
lastAutoBuyBackTime = block.timestamp;
address[] memory path = new address[](2);
path[0] = dexRouter.WETH();
path[1] = address(this);
// make the swap
dexRouter.swapExactETHForTokensSupportin... | 0.8.11 |
/* ------------- Traits ------------- */ | function encode(string[] memory strs) internal pure returns (bytes memory) {
bytes memory a;
for (uint256 i; i < strs.length; i++) {
if (i < strs.length - 1) a = abi.encodePacked(a, strs[i], bytes1(0));
else a = abi.encodePacked(a, strs[i]);
}
return a;
} | 0.8.12 |
/**
@notice Zap out in a single token
@param _ToTokenContractAddress The ERC20 token to zapout in (address(0x00) if ether)
@param _FromUniPoolAddress The uniswap pair address to zapout from
@param _IncomingLP The amount of LP to remove.
@param _minTokensRec indicates the minimum amount of tokens to receive
... | function ZapOut(
address _ToTokenContractAddress,
address _FromUniPoolAddress,
uint256 _IncomingLP,
uint256 _minTokensRec,
address[] memory _swapTarget,
bytes memory swap1Data,
bytes memory swap2Data,
address affiliate
) public nonReentrant st... | 0.5.17 |
/**
@notice Zap out in a pair of tokens with permit
@param _FromUniPoolAddress indicates the liquidity pool
@param _IncomingLP indicates the amount of LP to remove from pool
@param affiliate Affiliate address to share fees
@param _permitData indicates the encoded permit data, which contains owner, spender, va... | function ZapOut2PairTokenWithPermit(
address _FromUniPoolAddress,
uint256 _IncomingLP,
address affiliate,
bytes calldata _permitData
) external stopInEmergency returns (uint256 amountA, uint256 amountB) {
// permit
(bool success, ) = _FromUniPoolAddress.call(_p... | 0.5.17 |
/**
@notice Zap out in a signle token with permit
@param _ToTokenContractAddress indicates the toToken address to which tokens to convert.
@param _FromUniPoolAddress indicates the liquidity pool
@param _IncomingLP indicates the amount of LP to remove from pool
@param _minTokensRec indicatest the minimum amoun... | function ZapOutWithPermit(
address _ToTokenContractAddress,
address _FromUniPoolAddress,
uint256 _IncomingLP,
uint256 _minTokensRec,
bytes memory _permitData,
address[] memory _swapTarget,
bytes memory swap1Data,
bytes memory swap2Data,
ad... | 0.5.17 |
/**
@notice this method returns the amount of tokens received in underlying tokens after removal of liquidity.
@param _FromUniPoolAddress indicates the liquidity pool.
@param _tokenA indicates the tokenA of pool
@param _tokenB indicates the tokenB of pool
@param _liquidity indicates the amount of liquidity to... | function removeLiquidityReturn(
address _FromUniPoolAddress,
address _tokenA,
address _tokenB,
uint256 _liquidity
) external view returns (uint256 amountA, uint256 amountB) {
IUniswapV2Pair pair = IUniswapV2Pair(_FromUniPoolAddress);
(uint256 amount0, uint256... | 0.5.17 |
/**
* @dev given a wolf token supply, reserve token balance, reserve ratio, and a deposit amount (in the reserve token),
* calculates the return for a given conversion (in the wolf token)
*
* Formula:
* Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / MAX_RESERVE_RATIO) - 1)
*
... | function calculatePurchaseReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _depositAmount) public view returns (uint256)
{
// validate input
require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_R... | 0.4.25 |
/**
* @dev given a wolf token supply, reserve token balance, reserve ratio and a sell amount (in the wolf token),
* calculates the return for a given conversion (in the reserve token)
*
* Formula:
* Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / MAX_RESERVE_RATIO)))
*
... | function calculateSaleReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _sellAmount) public view returns (uint256)
{
// validate input
require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_... | 0.4.25 |
// Preminting 20 for marketing and community initatives | function _mintReservedTokens() internal onlyOwner {
uint256 supply = totalSupply();
uint256 _mintAmount = 20;
require(supply == 0);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(owner(), supply + i);
}
} | 0.8.0 |
/* ------------- External ------------- */ | function burnForBoost(IERC20 token) external payable {
uint256 userData = _claimReward();
uint256 boostCost = tokenBoostCosts[token];
if (boostCost == 0) revert InvalidBoostToken();
bool success = token.transferFrom(msg.sender, burnAddress, boostCost);
if (!success) revert Tran... | 0.8.12 |
// calculates momentary totalBonus for display instead of effective bonus | function getUserStakeInfo(address user) external view returns (StakeInfo memory info) {
unchecked {
uint256 userData = _userData[user];
info.numStaked = userData.numStaked();
info.roleCount = userData.uniqueRoleCount();
info.roleBonus = roleBonus(userData) / 10... | 0.8.12 |
// O(N) read-only functions | function tokenIdsOf(address user, uint256 type_) external view returns (uint256[] memory) {
unchecked {
uint256 numTotal = type_ == 0 ? this.balanceOf(user) : type_ == 1
? this.numStaked(user)
: this.numOwned(user);
uint256[] memory ids = new uint256[](nu... | 0.8.12 |
// low level token Pledge function | function procureTokens(address beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
uint256 backAmount;
require(beneficiary != address(0));
//minimum/maximum amount in ETH
require(weiAmount >= minNumbPerSubscr && weiAmount <= maxNumbPerSubscr);
if (now >= start... | 0.4.22 |
// trait counts are set through hook in madmouse contract (MadMouse::_beforeStakeDataTransform) | function uniqueRoleCount(uint256 userData) internal pure returns (uint256) {
unchecked {
return (toUInt256((userData >> (128)) & 0xFF > 0) +
toUInt256((userData >> (128 + 8)) & 0xFF > 0) +
toUInt256((userData >> (128 + 16)) & 0xFF > 0) +
toUInt256((use... | 0.8.12 |
// depends on the levels of the staked tokens (also set in hook MadMouse::_beforeStakeDataTransform)
// counts the base reward, depending on the levels of staked ids | function baseReward(uint256 userData) internal pure returns (uint256) {
unchecked {
return (((userData >> (168)) & 0xFF) +
(((userData >> (168 + 8)) & 0xFF) << 1) +
(((userData >> (168 + 16)) & 0xFF) << 2));
}
} | 0.8.12 |
// (should start at 128, 168; but role/level start at 1...) | function updateUserDataStake(uint256 userData, uint256 tokenData) internal pure returns (uint256) {
unchecked {
uint256 role = TokenDataOps.role(tokenData);
if (role > 0) {
userData += uint256(1) << (120 + (role << 3)); // roleBalances
userData += TokenDat... | 0.8.12 |
// signatures will be created dynamically | function mint(
uint256 amount,
bytes calldata signature,
bool stake
) external payable noContract {
if (!publicSaleActive) revert PublicSaleNotActive();
if (PURCHASE_LIMIT < amount) revert ExceedsLimit();
if (msg.value != price * amount) revert IncorrectValue();
... | 0.8.12 |
// update role, level information when staking | function _beforeStakeDataTransform(
uint256 tokenId,
uint256 userData,
uint256 tokenData
) internal view override returns (uint256, uint256) {
// assumption that mint&stake won't have revealed yet
if (!tokenData.mintAndStake() && tokenData.role() == 0 && revealed)
... | 0.8.12 |
// note: must be guarded by check for revealed | function updateDataWhileStaked(
uint256 userData,
uint256 tokenId,
uint256 oldTokenData,
uint256 newTokenData
) private view returns (uint256, uint256) {
uint256 userDataX;
// add in the role and rarity data if not already
uint256 tokenDataX = newTokenData.rol... | 0.8.12 |
// simulates a token update and only returns ids != 0 if
// the user gets a bonus increase upon updating staked data | function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) {
if (!revealed) return new uint256[](0);
uint256[] memory stakedIds = this.tokenIdsOf(user, 1);
uint256 userData = _userData[user];
uint256 oldTotalBonus = totalBonus(user, userData);
uint25... | 0.8.12 |
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
The value of... | function power(
uint256 _baseN,
uint256 _baseD,
uint32 _expN,
uint32 _expD
) internal view returns (uint256, uint8)
{
require(_baseN < MAX_NUM, "baseN exceeds max value.");
require(_baseN >= _baseD, "Bases < 1 are not supported.");
uint256 baseL... | 0.4.25 |
/**
Compute log(x / FIXED_1) * FIXED_1.
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/ | function generalLog(uint256 _x) internal pure returns (uint256) {
uint256 res = 0;
uint256 x = _x;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // ... | 0.4.25 |
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/ | function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
uint256 n = _n;
if (n < 256) {
// At most 8 iterations
while (n > 1) {
n >>= 1;
res += 1;
}
} else {
// Exactly 8 iter... | 0.4.25 |
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to... | function findPositionInMaxExpArray(uint256 _x)
internal view returns (uint8)
{
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
... | 0.4.25 |
/**
* @dev Investments
*/ | function () external payable {
require(msg.value >= minimum);
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] =... | 0.4.25 |
//transforms HEX to HXB @ uniswap rate | function transformHEX(uint hearts, address ref)//Approval needed
public
synchronized
{
require(roomActive, "transform room not active");
require(hearts >= 100, "value too low");
require(hexInterface.transferFrom(msg.sender, address(this), hearts), "Transfer failed");//s... | 0.6.4 |
//unlock referral HXB tokens from contract | function UnlockRefTokens()
public
synchronized
{
require(refLockedBalances[msg.sender] > 0,"Error: unsufficient locked balance");//ensure user has enough locked funds
require(isLockFinished(), "tokens cannot be unlocked yet. hxb maxsupply not yet reached");
uint amt = r... | 0.6.4 |
//unlock transformed HXB tokens from contract | function UnlockTransformTokens()
public
synchronized
{
require(transformLockedBalances[msg.sender] > 0,"Error: unsufficient locked balance");//ensure user has enough locked funds
require(isLockFinished(), "tokens cannot be unlocked yet. hxb maxsupply not yet reached");
... | 0.6.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.