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
|
|---|---|---|---|---|
72
|
// SUPPORT
|
function getCurrentDay() public view returns (uint256) {
return _getCurrentDay();
}
|
function getCurrentDay() public view returns (uint256) {
return _getCurrentDay();
}
| 15,103
|
82
|
// We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)repFactor to gain efficiency
|
if (vrf <= ((~uint256(0)/uint256(abs.activeIdentities))*repFactor)) {
return true;
}
|
if (vrf <= ((~uint256(0)/uint256(abs.activeIdentities))*repFactor)) {
return true;
}
| 35,993
|
334
|
// Not enough want in DyDx. So we take all we can
|
uint256 amountInSolo = want.balanceOf(SOLO);
if (amountInSolo < amount) {
amount = amountInSolo;
}
|
uint256 amountInSolo = want.balanceOf(SOLO);
if (amountInSolo < amount) {
amount = amountInSolo;
}
| 38,199
|
151
|
// UNIAPP Token Distribution =============================
|
uint256 public totalUNIAPPTokensForSale = 4500*(1e18); // 4500 UNIAPP will be sold during the whole Crowdsale
|
uint256 public totalUNIAPPTokensForSale = 4500*(1e18); // 4500 UNIAPP will be sold during the whole Crowdsale
| 20,091
|
52
|
// Withdraw loan tokens in exchange for pool tokens amount The amount of loan tokens to withdraw If amount is type(uint).max, withdraws all loan tokens /
|
function withdraw(uint amount) external {
require(lastDepositTimestamp[msg.sender] + MIN_LOCKUP_DURATION <= block.timestamp, "Pool: cannot transfer within lockup duration");
(address _feeRecipient, uint _feePoleis) = FACTORY.getFee();
(
uint _currentTotalSupply,
uint _accruedFeeShares,
uint _currentCollateralRatioPoleis,
uint _currentTotalDebt
) = getCurrentState(
lastLoanTokenBalance,
_feePoleis,
lastCollateralRatioPoleis,
totalSupply,
lastAccrueInterestTime,
lastTotalDebt
);
uint _shares;
if (amount == type(uint).max) {
amount = balanceOf[msg.sender] * (_currentTotalDebt + lastLoanTokenBalance) / _currentTotalSupply;
_shares = balanceOf[msg.sender];
} else {
_shares = tokenToShares(amount, (_currentTotalDebt + lastLoanTokenBalance), _currentTotalSupply, true);
}
_currentTotalSupply -= _shares;
// commit current state
balanceOf[msg.sender] -= _shares;
totalSupply = _currentTotalSupply;
// avoid recording accrue interest time if there is no change in total debt i.e. 0 interest
if (lastTotalDebt != _currentTotalDebt) {
lastTotalDebt = _currentTotalDebt;
lastAccrueInterestTime = block.timestamp;
}
lastCollateralRatioPoleis = _currentCollateralRatioPoleis;
emit Withdraw(msg.sender, amount);
emit Transfer(msg.sender, address(0), _shares);
if(_accruedFeeShares > 0) {
balanceOf[_feeRecipient] += _accruedFeeShares;
emit Transfer(address(0), _feeRecipient, _accruedFeeShares);
}
// interactions
safeTransfer(LOAN_TOKEN, msg.sender, amount);
// sync balance
lastLoanTokenBalance = LOAN_TOKEN.balanceOf(address(this));
}
|
function withdraw(uint amount) external {
require(lastDepositTimestamp[msg.sender] + MIN_LOCKUP_DURATION <= block.timestamp, "Pool: cannot transfer within lockup duration");
(address _feeRecipient, uint _feePoleis) = FACTORY.getFee();
(
uint _currentTotalSupply,
uint _accruedFeeShares,
uint _currentCollateralRatioPoleis,
uint _currentTotalDebt
) = getCurrentState(
lastLoanTokenBalance,
_feePoleis,
lastCollateralRatioPoleis,
totalSupply,
lastAccrueInterestTime,
lastTotalDebt
);
uint _shares;
if (amount == type(uint).max) {
amount = balanceOf[msg.sender] * (_currentTotalDebt + lastLoanTokenBalance) / _currentTotalSupply;
_shares = balanceOf[msg.sender];
} else {
_shares = tokenToShares(amount, (_currentTotalDebt + lastLoanTokenBalance), _currentTotalSupply, true);
}
_currentTotalSupply -= _shares;
// commit current state
balanceOf[msg.sender] -= _shares;
totalSupply = _currentTotalSupply;
// avoid recording accrue interest time if there is no change in total debt i.e. 0 interest
if (lastTotalDebt != _currentTotalDebt) {
lastTotalDebt = _currentTotalDebt;
lastAccrueInterestTime = block.timestamp;
}
lastCollateralRatioPoleis = _currentCollateralRatioPoleis;
emit Withdraw(msg.sender, amount);
emit Transfer(msg.sender, address(0), _shares);
if(_accruedFeeShares > 0) {
balanceOf[_feeRecipient] += _accruedFeeShares;
emit Transfer(address(0), _feeRecipient, _accruedFeeShares);
}
// interactions
safeTransfer(LOAN_TOKEN, msg.sender, amount);
// sync balance
lastLoanTokenBalance = LOAN_TOKEN.balanceOf(address(this));
}
| 16,392
|
24
|
// BiconomyForwarderA trusted forwarder for Biconomy relayed meta transactions- Inherits the ERC20ForwarderRequest struct - Verifies EIP712 signatures - Verifies personalSign signatures - Implements 2D nonces... each Tx has a BatchId and a BatchNonce - Keeps track of highest BatchId used by a given address, to assist in encoding of transactions client-side - maintains a list of verified domain seperators/
|
contract BiconomyForwarder is ERC20ForwardRequestTypes,Ownable{
using ECDSA for bytes32;
mapping(bytes32 => bool) public domains;
uint256 chainId;
string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)";
bytes32 public constant REQUEST_TYPEHASH = keccak256(bytes("ERC20ForwardRequest(address from,address to,address token,uint256 txGas,uint256 tokenGasPrice,uint256 batchId,uint256 batchNonce,uint256 deadline,bytes data)"));
mapping(address => mapping(uint256 => uint256)) nonces;
constructor(
address _owner
) public Ownable(_owner){
uint256 id;
assembly {
id := chainid()
}
chainId = id;
require(_owner != address(0), "Owner Address cannot be 0");
}
/**
* @dev registers domain seperators, maintaining that all domain seperators used for EIP712 forward requests use...
* ... the address of this contract and the chainId of the chain this contract is deployed to
* @param name : name of dApp/dApp fee proxy
* @param version : version of dApp/dApp fee proxy
*/
function registerDomainSeparator(string calldata name, string calldata version) external onlyOwner{
uint256 id;
/* solhint-disable-next-line no-inline-assembly */
assembly {
id := chainid()
}
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
address(this),
bytes32(id));
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
/**
* @dev returns a value from the nonces 2d mapping
* @param from : the user address
* @param batchId : the key of the user's batch being queried
* @return nonce : the number of transaction made within said batch
*/
function getNonce(address from, uint256 batchId)
public view
returns (uint256) {
return nonces[from][batchId];
}
/**
* @dev an external function which exposes the internal _verifySigEIP712 method
* @param req : request being verified
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
*/
function verifyEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig)
external view {
_verifySigEIP712(req, domainSeparator, sig);
}
/**
* @dev verifies the call is valid by calling _verifySigEIP712
* @dev executes the forwarded call if valid
* @dev updates the nonce after
* @param req : request being executed
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executeEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig
)
external
returns (bool success, bytes memory ret) {
_verifySigEIP712(req,domainSeparator,sig);
_updateNonce(req);
/* solhint-disable-next-line avoid-low-level-calls */
(success,ret) = req.to.call{gas : req.txGas}(abi.encodePacked(req.data, req.from));
// Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.txGas / 63);
_verifyCallResult(success,ret,"Forwarded call to destination did not succeed");
}
/**
* @dev an external function which exposes the internal _verifySigPersonSign method
* @param req : request being verified
* @param sig : the signature generated by the user's wallet
*/
function verifyPersonalSign(
ERC20ForwardRequest calldata req,
bytes calldata sig)
external view {
_verifySigPersonalSign(req, sig);
}
/**
* @dev verifies the call is valid by calling _verifySigPersonalSign
* @dev executes the forwarded call if valid
* @dev updates the nonce after
* @param req : request being executed
* @param sig : the signature generated by the user's wallet
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executePersonalSign(ERC20ForwardRequest calldata req,bytes calldata sig)
external
returns(bool success, bytes memory ret){
_verifySigPersonalSign(req, sig);
_updateNonce(req);
(success,ret) = req.to.call{gas : req.txGas}(abi.encodePacked(req.data, req.from));
// Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.txGas / 63);
_verifyCallResult(success,ret,"Forwarded call to destination did not succeed");
}
/**
* @dev Increments the nonce of given user/batch pair
* @dev Updates the highestBatchId of the given user if the request's batchId > current highest
* @dev only intended to be called post call execution
* @param req : request that was executed
*/
function _updateNonce(ERC20ForwardRequest calldata req) internal {
nonces[req.from][req.batchId]++;
}
/**
* @dev verifies the domain separator used has been registered via registerDomainSeparator()
* @dev recreates the 32 byte hash signed by the user's wallet (as per EIP712 specifications)
* @dev verifies the signature using Open Zeppelin's ECDSA library
* @dev signature valid if call doesn't throw
*
* @param req : request being executed
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
*
*/
function _verifySigEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes memory sig)
internal
view
{
uint256 id;
/* solhint-disable-next-line no-inline-assembly */
assembly {
id := chainid()
}
require(req.deadline == 0 || block.timestamp + 20 <= req.deadline, "request expired");
require(domains[domainSeparator], "unregistered domain separator");
require(chainId == id, "potential replay attack on the fork");
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(abi.encode(REQUEST_TYPEHASH,
req.from,
req.to,
req.token,
req.txGas,
req.tokenGasPrice,
req.batchId,
nonces[req.from][req.batchId],
req.deadline,
keccak256(req.data)
))));
require(digest.recover(sig) == req.from, "signature mismatch");
}
/**
* @dev encodes a 32 byte data string (presumably a hash of encoded data) as per eth_sign
*
* @param hash : hash of encoded data that signed by user's wallet using eth_sign
* @return input hash encoded to matched what is signed by the user's key when using eth_sign*/
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev recreates the 32 byte hash signed by the user's wallet
* @dev verifies the signature using Open Zeppelin's ECDSA library
* @dev signature valid if call doesn't throw
*
* @param req : request being executed
* @param sig : the signature generated by the user's wallet
*
*/
function _verifySigPersonalSign(
ERC20ForwardRequest calldata req,
bytes memory sig)
internal
view
{
require(req.deadline == 0 || block.timestamp + 20 <= req.deadline, "request expired");
bytes32 digest = prefixed(keccak256(abi.encodePacked(
req.from,
req.to,
req.token,
req.txGas,
req.tokenGasPrice,
req.batchId,
nonces[req.from][req.batchId],
req.deadline,
keccak256(req.data)
)));
require(digest.recover(sig) == req.from, "signature mismatch");
}
/**
* @dev verifies the call result and bubbles up revert reason for failed calls
*
* @param success : outcome of forwarded call
* @param returndata : returned data from the frowarded call
* @param errorMessage : fallback error message to show
*/
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure {
if (!success) {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
contract BiconomyForwarder is ERC20ForwardRequestTypes,Ownable{
using ECDSA for bytes32;
mapping(bytes32 => bool) public domains;
uint256 chainId;
string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)";
bytes32 public constant REQUEST_TYPEHASH = keccak256(bytes("ERC20ForwardRequest(address from,address to,address token,uint256 txGas,uint256 tokenGasPrice,uint256 batchId,uint256 batchNonce,uint256 deadline,bytes data)"));
mapping(address => mapping(uint256 => uint256)) nonces;
constructor(
address _owner
) public Ownable(_owner){
uint256 id;
assembly {
id := chainid()
}
chainId = id;
require(_owner != address(0), "Owner Address cannot be 0");
}
/**
* @dev registers domain seperators, maintaining that all domain seperators used for EIP712 forward requests use...
* ... the address of this contract and the chainId of the chain this contract is deployed to
* @param name : name of dApp/dApp fee proxy
* @param version : version of dApp/dApp fee proxy
*/
function registerDomainSeparator(string calldata name, string calldata version) external onlyOwner{
uint256 id;
/* solhint-disable-next-line no-inline-assembly */
assembly {
id := chainid()
}
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
address(this),
bytes32(id));
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
/**
* @dev returns a value from the nonces 2d mapping
* @param from : the user address
* @param batchId : the key of the user's batch being queried
* @return nonce : the number of transaction made within said batch
*/
function getNonce(address from, uint256 batchId)
public view
returns (uint256) {
return nonces[from][batchId];
}
/**
* @dev an external function which exposes the internal _verifySigEIP712 method
* @param req : request being verified
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
*/
function verifyEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig)
external view {
_verifySigEIP712(req, domainSeparator, sig);
}
/**
* @dev verifies the call is valid by calling _verifySigEIP712
* @dev executes the forwarded call if valid
* @dev updates the nonce after
* @param req : request being executed
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executeEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig
)
external
returns (bool success, bytes memory ret) {
_verifySigEIP712(req,domainSeparator,sig);
_updateNonce(req);
/* solhint-disable-next-line avoid-low-level-calls */
(success,ret) = req.to.call{gas : req.txGas}(abi.encodePacked(req.data, req.from));
// Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.txGas / 63);
_verifyCallResult(success,ret,"Forwarded call to destination did not succeed");
}
/**
* @dev an external function which exposes the internal _verifySigPersonSign method
* @param req : request being verified
* @param sig : the signature generated by the user's wallet
*/
function verifyPersonalSign(
ERC20ForwardRequest calldata req,
bytes calldata sig)
external view {
_verifySigPersonalSign(req, sig);
}
/**
* @dev verifies the call is valid by calling _verifySigPersonalSign
* @dev executes the forwarded call if valid
* @dev updates the nonce after
* @param req : request being executed
* @param sig : the signature generated by the user's wallet
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executePersonalSign(ERC20ForwardRequest calldata req,bytes calldata sig)
external
returns(bool success, bytes memory ret){
_verifySigPersonalSign(req, sig);
_updateNonce(req);
(success,ret) = req.to.call{gas : req.txGas}(abi.encodePacked(req.data, req.from));
// Validate that the relayer has sent enough gas for the call.
// See https://ronan.eth.link/blog/ethereum-gas-dangers/
assert(gasleft() > req.txGas / 63);
_verifyCallResult(success,ret,"Forwarded call to destination did not succeed");
}
/**
* @dev Increments the nonce of given user/batch pair
* @dev Updates the highestBatchId of the given user if the request's batchId > current highest
* @dev only intended to be called post call execution
* @param req : request that was executed
*/
function _updateNonce(ERC20ForwardRequest calldata req) internal {
nonces[req.from][req.batchId]++;
}
/**
* @dev verifies the domain separator used has been registered via registerDomainSeparator()
* @dev recreates the 32 byte hash signed by the user's wallet (as per EIP712 specifications)
* @dev verifies the signature using Open Zeppelin's ECDSA library
* @dev signature valid if call doesn't throw
*
* @param req : request being executed
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
*
*/
function _verifySigEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes memory sig)
internal
view
{
uint256 id;
/* solhint-disable-next-line no-inline-assembly */
assembly {
id := chainid()
}
require(req.deadline == 0 || block.timestamp + 20 <= req.deadline, "request expired");
require(domains[domainSeparator], "unregistered domain separator");
require(chainId == id, "potential replay attack on the fork");
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(abi.encode(REQUEST_TYPEHASH,
req.from,
req.to,
req.token,
req.txGas,
req.tokenGasPrice,
req.batchId,
nonces[req.from][req.batchId],
req.deadline,
keccak256(req.data)
))));
require(digest.recover(sig) == req.from, "signature mismatch");
}
/**
* @dev encodes a 32 byte data string (presumably a hash of encoded data) as per eth_sign
*
* @param hash : hash of encoded data that signed by user's wallet using eth_sign
* @return input hash encoded to matched what is signed by the user's key when using eth_sign*/
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev recreates the 32 byte hash signed by the user's wallet
* @dev verifies the signature using Open Zeppelin's ECDSA library
* @dev signature valid if call doesn't throw
*
* @param req : request being executed
* @param sig : the signature generated by the user's wallet
*
*/
function _verifySigPersonalSign(
ERC20ForwardRequest calldata req,
bytes memory sig)
internal
view
{
require(req.deadline == 0 || block.timestamp + 20 <= req.deadline, "request expired");
bytes32 digest = prefixed(keccak256(abi.encodePacked(
req.from,
req.to,
req.token,
req.txGas,
req.tokenGasPrice,
req.batchId,
nonces[req.from][req.batchId],
req.deadline,
keccak256(req.data)
)));
require(digest.recover(sig) == req.from, "signature mismatch");
}
/**
* @dev verifies the call result and bubbles up revert reason for failed calls
*
* @param success : outcome of forwarded call
* @param returndata : returned data from the frowarded call
* @param errorMessage : fallback error message to show
*/
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure {
if (!success) {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| 23,082
|
108
|
// DAO code/operator management/dutch auction, etc by BoringCrypto Staking in DictatorDAO inspired by Chef Nomi's SushiBar (heavily modified) - MIT license (originally WTFPL) TimeLock functionality Copyright 2020 Compound Labs, Inc. - BSD 3-Clause "New" or "Revised" License Token pool code from SushiSwap MasterChef V2, pioneered by Chef Nomi (I think, under WTFPL) and improved by Keno Budde - MIT license
|
contract DictatorDAO is IERC20, Domain {
using BoringMath for uint256;
using BoringMath128 for uint128;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public override totalSupply;
DictatorToken public immutable token;
address public operator;
mapping(address => address) userVote;
mapping(address => uint256) votes;
constructor(
string memory tokenSymbol,
string memory tokenName,
string memory sharesSymbol,
string memory sharesName,
address initialOperator
) public {
// The DAO is the owner of the DictatorToken
token = new DictatorToken(tokenSymbol, tokenName);
symbol = sharesSymbol;
name = sharesName;
operator = initialOperator;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
address userVoteTo = userVote[to];
address userVoteFrom = userVote[from];
// If the to has no vote and no balance, copy the from vote
address operatorVote = toUser.balance > 0 && userVoteTo == address(0) ? userVoteTo : userVoteFrom;
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^256-1
votes[userVoteFrom] -= shares;
votes[operatorVote] += shares;
userVote[to] = operatorVote;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
// Operator Setting
address pendingOperator;
uint256 pendingOperatorTime;
function setOperator(address newOperator) public {
if (newOperator != pendingOperator) {
require(votes[newOperator] / 2 > totalSupply, "Not enough votes");
pendingOperator = newOperator;
pendingOperatorTime = block.timestamp + 7 days;
} else {
if (votes[newOperator] / 2 > totalSupply) {
require(block.timestamp >= pendingOperatorTime, "Wait longer");
operator = pendingOperator;
}
pendingOperator = address(0);
pendingOperatorTime = 0;
}
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount, address operatorVote) public returns (bool) {
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + 24 hours).to128();
users[msg.sender] = user;
totalSupply += shares;
votes[operatorVote] += shares;
token.transferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
votes[userVote[from]] -= shares;
token.transfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant DELAY = 2 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public returns (bytes32) {
require(msg.sender == operator, "Operator only");
require(votes[operator] / 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = block.timestamp + DELAY;
queuedTransactions[txHash] = eta;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
bytes memory data
) public {
require(msg.sender == operator, "Operator only");
bytes32 txHash = keccak256(abi.encode(target, value, data));
queuedTransactions[txHash] = 0;
emit CancelTransaction(txHash, target, value, data);
}
function executeTransaction(
address target,
uint256 value,
bytes memory data
) public payable returns (bytes memory) {
require(msg.sender == operator, "Operator only");
require(votes[operator] / 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = queuedTransactions[txHash];
require(block.timestamp >= eta, "Too early");
require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale");
queuedTransactions[txHash] = 0;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Tx reverted :(");
emit ExecuteTransaction(txHash, target, value, data);
return returnData;
}
}
|
contract DictatorDAO is IERC20, Domain {
using BoringMath for uint256;
using BoringMath128 for uint128;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public override totalSupply;
DictatorToken public immutable token;
address public operator;
mapping(address => address) userVote;
mapping(address => uint256) votes;
constructor(
string memory tokenSymbol,
string memory tokenName,
string memory sharesSymbol,
string memory sharesName,
address initialOperator
) public {
// The DAO is the owner of the DictatorToken
token = new DictatorToken(tokenSymbol, tokenName);
symbol = sharesSymbol;
name = sharesName;
operator = initialOperator;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
address userVoteTo = userVote[to];
address userVoteFrom = userVote[from];
// If the to has no vote and no balance, copy the from vote
address operatorVote = toUser.balance > 0 && userVoteTo == address(0) ? userVoteTo : userVoteFrom;
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^256-1
votes[userVoteFrom] -= shares;
votes[operatorVote] += shares;
userVote[to] = operatorVote;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
// Operator Setting
address pendingOperator;
uint256 pendingOperatorTime;
function setOperator(address newOperator) public {
if (newOperator != pendingOperator) {
require(votes[newOperator] / 2 > totalSupply, "Not enough votes");
pendingOperator = newOperator;
pendingOperatorTime = block.timestamp + 7 days;
} else {
if (votes[newOperator] / 2 > totalSupply) {
require(block.timestamp >= pendingOperatorTime, "Wait longer");
operator = pendingOperator;
}
pendingOperator = address(0);
pendingOperatorTime = 0;
}
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount, address operatorVote) public returns (bool) {
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + 24 hours).to128();
users[msg.sender] = user;
totalSupply += shares;
votes[operatorVote] += shares;
token.transferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
votes[userVote[from]] -= shares;
token.transfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant DELAY = 2 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public returns (bytes32) {
require(msg.sender == operator, "Operator only");
require(votes[operator] / 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = block.timestamp + DELAY;
queuedTransactions[txHash] = eta;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
bytes memory data
) public {
require(msg.sender == operator, "Operator only");
bytes32 txHash = keccak256(abi.encode(target, value, data));
queuedTransactions[txHash] = 0;
emit CancelTransaction(txHash, target, value, data);
}
function executeTransaction(
address target,
uint256 value,
bytes memory data
) public payable returns (bytes memory) {
require(msg.sender == operator, "Operator only");
require(votes[operator] / 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = queuedTransactions[txHash];
require(block.timestamp >= eta, "Too early");
require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale");
queuedTransactions[txHash] = 0;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Tx reverted :(");
emit ExecuteTransaction(txHash, target, value, data);
return returnData;
}
}
| 17,987
|
5
|
// Account Library /
|
library AccountLibrary {
using ECDSA for bytes32;
function isOwnerDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool isOwner;
(isOwner,,) = _account.devices(_device);
return isOwner;
}
function isAnyDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool exists;
(,exists,) = _account.devices(_device);
return exists;
}
function isExistedDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool existed;
(,,existed) = _account.devices(_device);
return existed;
}
function verifyOwnerSignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
_result = isOwnerDevice(_account, _recovered);
}
}
function verifySignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature,
bool _strict
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
if (_strict) {
_result = isAnyDevice(_account, _recovered);
} else {
_result = isExistedDevice(_account, _recovered);
}
}
}
}
|
library AccountLibrary {
using ECDSA for bytes32;
function isOwnerDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool isOwner;
(isOwner,,) = _account.devices(_device);
return isOwner;
}
function isAnyDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool exists;
(,exists,) = _account.devices(_device);
return exists;
}
function isExistedDevice(
AbstractAccount _account,
address _device
) internal view returns (bool) {
bool existed;
(,,existed) = _account.devices(_device);
return existed;
}
function verifyOwnerSignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
_result = isOwnerDevice(_account, _recovered);
}
}
function verifySignature(
AbstractAccount _account,
bytes32 _messageHash,
bytes memory _signature,
bool _strict
) internal view returns (bool _result) {
address _recovered = _messageHash.recover(_signature);
if (_recovered != address(0)) {
if (_strict) {
_result = isAnyDevice(_account, _recovered);
} else {
_result = isExistedDevice(_account, _recovered);
}
}
}
}
| 40,392
|
9
|
// return the result
|
return i;
|
return i;
| 38,854
|
1,444
|
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter denominated in token currency units and we can avoid adding another parameter.
|
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
|
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
| 21,916
|
8
|
// Calculate the new total amount for the "whale" condition (considering only the amount of the current transaction)
|
uint256 newBlocksPerPeriod;
if (amount >= totalSupply() / 100 || _isWhale[account]) {
newBlocksPerPeriod = WHALE_BLOCKS_PER_UNLOCK_PERIOD;
_isWhale[account] = true; // Mark this account as a whale
} else if (!_isWhale[account] && amount > balanceBeforeTransaction) {
|
uint256 newBlocksPerPeriod;
if (amount >= totalSupply() / 100 || _isWhale[account]) {
newBlocksPerPeriod = WHALE_BLOCKS_PER_UNLOCK_PERIOD;
_isWhale[account] = true; // Mark this account as a whale
} else if (!_isWhale[account] && amount > balanceBeforeTransaction) {
| 23,788
|
1
|
// ERC-20 extension for multiple recipients Extends the functionality of the ERC-20 standard token with the ability to transfer tokensto multiple recipients in a single transaction. /
|
contract ERC20MultiRecipient is ERC20 {
function transferMulti(address[] recipients, uint256[] values) public returns (bool) {
require(recipients.length > 0);
require(recipients.length == values.length);
uint256 i;
uint256 total;
for (i = 0; i < values.length; i++) {
total = total.add(values[i]);
}
require(total <= _balances[msg.sender]);
_balances[msg.sender] = _balances[msg.sender].sub(total);
for (i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0));
_balances[recipients[i]] = _balances[recipients[i]].add(values[i]);
emit Transfer(msg.sender, recipients[i], values[i]);
}
return true;
}
}
|
contract ERC20MultiRecipient is ERC20 {
function transferMulti(address[] recipients, uint256[] values) public returns (bool) {
require(recipients.length > 0);
require(recipients.length == values.length);
uint256 i;
uint256 total;
for (i = 0; i < values.length; i++) {
total = total.add(values[i]);
}
require(total <= _balances[msg.sender]);
_balances[msg.sender] = _balances[msg.sender].sub(total);
for (i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0));
_balances[recipients[i]] = _balances[recipients[i]].add(values[i]);
emit Transfer(msg.sender, recipients[i], values[i]);
}
return true;
}
}
| 8,857
|
10
|
// Historical merkle roots
|
mapping(bytes32 => bool) public override previousMerkleRoot;
|
mapping(bytes32 => bool) public override previousMerkleRoot;
| 22,293
|
6
|
// this operation returns all Natural Events for which 'crypto asset prices' can be requested adhoc from Block Sat.return _eventIds for the Natural Events return _eventTitles published titles for the Natural Events return _latestEventTimes latest time at which the event was known to have occured e.g. when tracking storms /
|
function getAvailableEvents() external returns (string [] memory _eventIds, string [] memory _eventTitles, uint256 [] memory _latestEventTimes);
|
function getAvailableEvents() external returns (string [] memory _eventIds, string [] memory _eventTitles, uint256 [] memory _latestEventTimes);
| 15,674
|
17
|
// _owner <==> _tokenCount
|
mapping (address => uint) ownerThingCount;
function _createThing(string _name, string _ext_url,
uint _parent_id, uint _func_id, uint _generation) internal
|
mapping (address => uint) ownerThingCount;
function _createThing(string _name, string _ext_url,
uint _parent_id, uint _func_id, uint _generation) internal
| 19,112
|
110
|
// Remove a Telegram chat ID from the array. _tgChatId Telegram chat ID to remove /
|
function removeTgId(int64 _tgChatId) internal {
for (uint256 i = 0; i < activeTgGroups.length; i++) {
if (activeTgGroups[i] == _tgChatId) {
activeTgGroups[i] = activeTgGroups[activeTgGroups.length - 1];
activeTgGroups.pop();
}
}
}
|
function removeTgId(int64 _tgChatId) internal {
for (uint256 i = 0; i < activeTgGroups.length; i++) {
if (activeTgGroups[i] == _tgChatId) {
activeTgGroups[i] = activeTgGroups[activeTgGroups.length - 1];
activeTgGroups.pop();
}
}
}
| 17,558
|
243
|
// uint currDuty = getIlkDuty(collateralType);warn about change in pricing
|
uint dsrEff = rpow(getDsr(), timeInterval, ONE);
uint firEff = rpow(interestRate, timeInterval, ONE);
if(getDsr() > interestRate )
|
uint dsrEff = rpow(getDsr(), timeInterval, ONE);
uint firEff = rpow(interestRate, timeInterval, ONE);
if(getDsr() > interestRate )
| 41,179
|
31
|
// Calculate the min LP out expected
|
uint256 ttl_val_usd = _frax_amount + (_usdc_amount * (10 ** usdc_missing_decimals)) + (_usdt_amount * (10 ** usdt_missing_decimals));
ttl_val_usd = (ttl_val_usd * VIRTUAL_PRICE_PRECISION) / frax2pool.get_virtual_price();
uint256 min_3pool_out = (ttl_val_usd * liq_slippage_2pool) / PRICE_PRECISION;
|
uint256 ttl_val_usd = _frax_amount + (_usdc_amount * (10 ** usdc_missing_decimals)) + (_usdt_amount * (10 ** usdt_missing_decimals));
ttl_val_usd = (ttl_val_usd * VIRTUAL_PRICE_PRECISION) / frax2pool.get_virtual_price();
uint256 min_3pool_out = (ttl_val_usd * liq_slippage_2pool) / PRICE_PRECISION;
| 12,125
|
210
|
// Get the amount of pending bets
|
function getBetWaitEndEther() public
constant
returns(uint result)
|
function getBetWaitEndEther() public
constant
returns(uint result)
| 47,965
|
76
|
// Vault's Accumulation Rate [wad]
|
uint256 rate;
|
uint256 rate;
| 69,592
|
18
|
// Base rate is in WAD
|
basePlusRate = _plusRewardPerDay * WAD / DAY;
plusBoost = WAD;
lastCheckpoint = block.timestamp;
|
basePlusRate = _plusRewardPerDay * WAD / DAY;
plusBoost = WAD;
lastCheckpoint = block.timestamp;
| 41,730
|
24
|
// generate shared keys with all other peers/signingKeys the ephemeral keys/identities of all peers in this app/npks list of public key broadcasted by peers for this run/my signingKey of the func caller/sk secret key of the func caller/sidH a unique identifier of a particular run & session
|
function DCKeys(
address[] memory signingKeys,
PK[] memory npks,
address my,
bytes memory sk,
bytes32 sidH
)
public
pure
returns (bytes32[] memory)
|
function DCKeys(
address[] memory signingKeys,
PK[] memory npks,
address my,
bytes memory sk,
bytes32 sidH
)
public
pure
returns (bytes32[] memory)
| 32,555
|
16
|
// global indices for each gov tokens used as a reference to calculate a fair share for each user
|
mapping (address => uint256) public govTokensIndexes;
|
mapping (address => uint256) public govTokensIndexes;
| 42,015
|
15
|
// require(!_tokenInUse(token));TODO add back after beta
|
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0)
IERC20(token).safeTransfer(to, balance);
|
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0)
IERC20(token).safeTransfer(to, balance);
| 17,320
|
340
|
// Restricted access function which updates the royalty infoRequires executor to have ROLE_ROYALTY_MANAGER permissionroyaltyPercentage_ new royalty percentage to set /
|
function setRoyaltyInfo(uint16 royaltyPercentage_) external {
// verify the access permission
require(isSenderInRole(ROLE_ROYALTY_MANAGER), "access denied");
// verify royalty percentage doesn't exceed 100%
require(royaltyPercentage_ <= 100_00, "royalty percentage exceeds 100%");
// emit an event first - to log both old and new values
emit RoyaltyInfoUpdated(msg.sender, royaltyPercentage, royaltyPercentage_);
// update the values
royaltyPercentage = royaltyPercentage_;
}
|
function setRoyaltyInfo(uint16 royaltyPercentage_) external {
// verify the access permission
require(isSenderInRole(ROLE_ROYALTY_MANAGER), "access denied");
// verify royalty percentage doesn't exceed 100%
require(royaltyPercentage_ <= 100_00, "royalty percentage exceeds 100%");
// emit an event first - to log both old and new values
emit RoyaltyInfoUpdated(msg.sender, royaltyPercentage, royaltyPercentage_);
// update the values
royaltyPercentage = royaltyPercentage_;
}
| 8,791
|
8
|
// 16M summa
|
uint256 public pub_total_summa = 16000000;
|
uint256 public pub_total_summa = 16000000;
| 27,252
|
7
|
// All NFTs have the token ID 0 in your case
|
tokenIds[0] = 0;
|
tokenIds[0] = 0;
| 11,592
|
12
|
// Sets the {userRegistry} address Emits a {SetUserRegistry}. Requirements - the caller should have {REGISTRY_MANAGER_ROLE} role. /
|
function setUserRegistry(IUserRegistry _userRegistry)
public
onlyRegistryManager
{
userRegistry = _userRegistry;
emit SetUserRegistry(userRegistry);
}
|
function setUserRegistry(IUserRegistry _userRegistry)
public
onlyRegistryManager
{
userRegistry = _userRegistry;
emit SetUserRegistry(userRegistry);
}
| 930
|
72
|
// Burn a token - any game logic should be handled before this function./
|
function burn(uint256 tokenId) external override whenNotPaused {
require(admins[_msgSender()], "Only admins can call this");
if(tokenId <= PAID_TOKENS) {
cnmWithEth.burn(tokenId);
} else {
_burn(tokenId);
if (tokenTraits[tokenId].isCat) {
if (tokenTraits[tokenId].isCrazy) {
emit CrazyCatLadyBurned(tokenId, block.number, block.timestamp);
} else {
emit CatBurned(tokenId, block.number, block.timestamp);
}
} else {
emit MouseBurned(tokenId, block.number, block.timestamp);
}
}
}
|
function burn(uint256 tokenId) external override whenNotPaused {
require(admins[_msgSender()], "Only admins can call this");
if(tokenId <= PAID_TOKENS) {
cnmWithEth.burn(tokenId);
} else {
_burn(tokenId);
if (tokenTraits[tokenId].isCat) {
if (tokenTraits[tokenId].isCrazy) {
emit CrazyCatLadyBurned(tokenId, block.number, block.timestamp);
} else {
emit CatBurned(tokenId, block.number, block.timestamp);
}
} else {
emit MouseBurned(tokenId, block.number, block.timestamp);
}
}
}
| 31,717
|
19
|
// funcion publica para otorgarle un voto a uno de los candidatos
|
function votar(string memory _candidato) public{
require(votosPorAdress[msg.sender] == 0, "Ya ha votado");
require(periodo_eleccion, "Las elecciones han sido finalizadas, o no han comenzado aun");
require(mapping_candidatos[_candidato].esValor, "El candidato no existe");
require(estaValidada[msg.sender], "Su direccion aun no ha sido validada, debe esperar la validacion antes de votar");
votosPorAdress[msg.sender]++;
mapping_candidatos[_candidato].votos++;
}
|
function votar(string memory _candidato) public{
require(votosPorAdress[msg.sender] == 0, "Ya ha votado");
require(periodo_eleccion, "Las elecciones han sido finalizadas, o no han comenzado aun");
require(mapping_candidatos[_candidato].esValor, "El candidato no existe");
require(estaValidada[msg.sender], "Su direccion aun no ha sido validada, debe esperar la validacion antes de votar");
votosPorAdress[msg.sender]++;
mapping_candidatos[_candidato].votos++;
}
| 36,463
|
39
|
// add the converted character to the byte array.
|
asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset);
|
asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset);
| 69,847
|
92
|
// set router
|
uniswapV2Router = _uniswapV2Router;
pairToken = IUniswapV2Factory(IUniswapV2Router02(uniswapV2Router).factory()).createPair(
address(this),
IUniswapV2Router02(uniswapV2Router).WETH()
);
address owner = _msgSender();
_shares[owner] = sharesFromToken(totalTokens, false);
_addValue(owner, totalTokens);
|
uniswapV2Router = _uniswapV2Router;
pairToken = IUniswapV2Factory(IUniswapV2Router02(uniswapV2Router).factory()).createPair(
address(this),
IUniswapV2Router02(uniswapV2Router).WETH()
);
address owner = _msgSender();
_shares[owner] = sharesFromToken(totalTokens, false);
_addValue(owner, totalTokens);
| 11,098
|
146
|
// set Withdrawed to zero
|
Withdrawed[sender] = 0;
|
Withdrawed[sender] = 0;
| 13,042
|
47
|
// Updates maximum per transaction for the particular token. Only owner can call this method._token address of the token contract, or address(0) for configuring the default limit._maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. 0 value is also allowed, will stop the bridge operations in outgoing direction./
|
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
|
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
| 47,587
|
112
|
// Calculate expected and settled collateral
|
executeSettlement.redeemableCollateral = calculateCollateralAmount(
executeSettlement
.emergencyPrice,
collateralDecimals,
executeSettlement
.userNumTokens
)
.add(executeSettlement.overCollateral);
executeSettlement.unusedCollateral = self.calculateUnusedCollateral(
|
executeSettlement.redeemableCollateral = calculateCollateralAmount(
executeSettlement
.emergencyPrice,
collateralDecimals,
executeSettlement
.userNumTokens
)
.add(executeSettlement.overCollateral);
executeSettlement.unusedCollateral = self.calculateUnusedCollateral(
| 7,894
|
57
|
// Sells all tokens of erc20Contract.
|
function proxiedSell(address erc20Contract) external onlyERC20Controller {
_sell(erc20Contract);
}
|
function proxiedSell(address erc20Contract) external onlyERC20Controller {
_sell(erc20Contract);
}
| 9,755
|
130
|
// Mappings to find partition / List of partitions.
|
bytes32[] internal _totalPartitions;
|
bytes32[] internal _totalPartitions;
| 23,805
|
53
|
// Returns the downcasted int152 from int256, reverting onoverflow (when the input is less than smallest int152 orgreater than largest int152). Counterpart to Solidity's `int152` operator. Requirements: - input must fit into 152 bits _Available since v4.7._ /
|
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
|
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
| 25,796
|
144
|
// tokensInForExactBptOut (per token)aI = amountIn / bptOut \ b = balance aI = b| ------------ |bptOut = bptAmountOut \totalBPT/ bpt = totalBPT/ Tokens in, so we round up overall.
|
uint256 bptRatio = bptAmountOut.divUp(totalBPT);
uint256[] memory amountsIn = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsIn[i] = balances[i].mulUp(bptRatio);
}
|
uint256 bptRatio = bptAmountOut.divUp(totalBPT);
uint256[] memory amountsIn = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amountsIn[i] = balances[i].mulUp(bptRatio);
}
| 56,689
|
23
|
// ======== VIEW FUNCTIONS ======== /
|
function getPendingRewards() public view returns (uint256) {
return veFXSYieldDistributorV4.earned(address(this));
}
|
function getPendingRewards() public view returns (uint256) {
return veFXSYieldDistributorV4.earned(address(this));
}
| 58,047
|
120
|
// We might choose to use poolToken.totalSupply to compute the amount, but decide to use D in case we have multiple minters on the pool token.
|
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
|
amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]);
| 54,032
|
4
|
// variables essential to calculating auction/price information for each cloneId
|
struct CloneShape {
uint256 tokenId;
uint256 worth;
address ERC721Contract;
address ERC20Contract;
uint8 heat;
bool floor;
uint256 term;
}
|
struct CloneShape {
uint256 tokenId;
uint256 worth;
address ERC721Contract;
address ERC20Contract;
uint8 heat;
bool floor;
uint256 term;
}
| 44,720
|
133
|
// Returns a token ID owned by `owner` at a given `index` of its token list.
|
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| 17,690
|
46
|
// Set new base URI for all tokens for `URI_SETTER_ROLE` rolebaseURI New baseURI/
|
function setBaseURI(string memory baseURI) external AccessControlUpgradeable.onlyRole(URI_SETTER_ROLE) {
BaseURIUpgradeable._setBaseURI(baseURI);
}
|
function setBaseURI(string memory baseURI) external AccessControlUpgradeable.onlyRole(URI_SETTER_ROLE) {
BaseURIUpgradeable._setBaseURI(baseURI);
}
| 15,866
|
138
|
// Set in place in map
|
_tokens[symbol] = token;
|
_tokens[symbol] = token;
| 50,747
|
26
|
// Sets default royalty if royalty manager allows it _royalty New default royalty /
|
function setDefaultRoyalty(IRoyaltyManager.Royalty calldata _royalty)
external
nonReentrant
royaltyValid(_royalty.royaltyPercentageBPS)
|
function setDefaultRoyalty(IRoyaltyManager.Royalty calldata _royalty)
external
nonReentrant
royaltyValid(_royalty.royaltyPercentageBPS)
| 12,909
|
14
|
// burn the collateral tokens from the sender, which is the vault that holds the collateral tokens
|
ERC20Upgradeable._burn(_msgSender(), amount);
|
ERC20Upgradeable._burn(_msgSender(), amount);
| 43,740
|
4
|
// Initializes the contract setting the deployer as the initial owner. /
|
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
|
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
| 517
|
28
|
// Get All Deposit IDs /
|
{
return allDepositIds;
}
|
{
return allDepositIds;
}
| 29,907
|
329
|
// Allows DelegationController contract to execute slashing ofdelegations. /
|
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
|
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
| 31,937
|
6
|
// example: 200 is 2% interests
|
function getInterestPerSecond(uint256 yearlyInterestBips) public pure returns (uint64 interestsPerSecond) {
return uint64((yearlyInterestBips * 316880878) / 100); // 316880878 is the precomputed integral part of 1e18 / (36525 * 3600 * 24)
}
|
function getInterestPerSecond(uint256 yearlyInterestBips) public pure returns (uint64 interestsPerSecond) {
return uint64((yearlyInterestBips * 316880878) / 100); // 316880878 is the precomputed integral part of 1e18 / (36525 * 3600 * 24)
}
| 12,783
|
104
|
// how much ETH did we just swap into?
|
uint256 newBalance = address(this).balance.sub(initialBalance);
|
uint256 newBalance = address(this).balance.sub(initialBalance);
| 28,163
|
4
|
// Creates a new edition contract as a factory with a deterministic address/ Important: None of these fields (except the Url fields with the same hash) can be changed after calling/_name Name of the edition contract/_symbol Symbol of the edition contract/_description Metadata: Description of the edition entry/_animationUrl Metadata: Animation url (optional) of the edition entry/_imageUrl Metadata: Image url (semi-required) of the edition entry/_items Items collection/_isSale status sell/_seriesSize Total size of the edition (number of possible editions)
|
function createAsset(
string memory _name,
string memory _symbol,
string memory _description,
string memory _animationUrl,
string memory _imageUrl,
string[] memory _items,
bool _isSale,
uint256 _seriesSize
|
function createAsset(
string memory _name,
string memory _symbol,
string memory _description,
string memory _animationUrl,
string memory _imageUrl,
string[] memory _items,
bool _isSale,
uint256 _seriesSize
| 3,524
|
87
|
// Overload of {ECDSA-recover} that receives the `v`,`r` and `s` signature fields separately. /
|
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
|
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
| 2,631
|
121
|
// Lock ETH (msg.value) as collateral in safe/manager address - Safe Manager/ethJoin address/safe uint - Safe Id
|
function lockETH(
address manager,
address ethJoin,
uint safe
|
function lockETH(
address manager,
address ethJoin,
uint safe
| 54,809
|
54
|
// Unset the first bit of the last byte
|
buf[numBytes - 1] &= 0x7F;
return buf;
|
buf[numBytes - 1] &= 0x7F;
return buf;
| 28,603
|
85
|
// Sets `adminRole` as ``role``'s admin role.
|
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
|
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
| 4,327
|
5
|
// must be a valid transition
|
return validTransition(_fromState, _toState);
|
return validTransition(_fromState, _toState);
| 48,061
|
308
|
// safely transfer tokens without underflowing
|
function safeTokenTransfer(
address recipient,
address token,
uint256 amount
) internal returns (uint256) {
if (amount == 0) {
return 0;
}
|
function safeTokenTransfer(
address recipient,
address token,
uint256 amount
) internal returns (uint256) {
if (amount == 0) {
return 0;
}
| 5,818
|
5
|
// Checksum associated to the DID
|
bytes32 lastChecksum;
|
bytes32 lastChecksum;
| 27,494
|
20
|
// Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
|
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
|
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
| 14,974
|
59
|
// price as usd = token/eth price eth priceFetches the current token usd price from dex swap, with 6 decimals of precision. ethPrice: with 6 decimals of precision /
|
function fetchAnchorPriceETH(string memory symbol, TokenConfig memory config, uint ethPrice) internal virtual returns (uint) {
(uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config);
// This should be impossible, but better safe than sorry
require(block.timestamp > oldTimestamp, "now must come after before");
uint timeElapsed = block.timestamp - oldTimestamp;
// Calculate uniswap time-weighted average price
// Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed));
uint rawUniswapPriceMantissa = priceAverage.decode112with18();
uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, ethPrice);
uint anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale;
emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp);
return anchorPrice;
}
|
function fetchAnchorPriceETH(string memory symbol, TokenConfig memory config, uint ethPrice) internal virtual returns (uint) {
(uint nowCumulativePrice, uint oldCumulativePrice, uint oldTimestamp) = pokeWindowValues(config);
// This should be impossible, but better safe than sorry
require(block.timestamp > oldTimestamp, "now must come after before");
uint timeElapsed = block.timestamp - oldTimestamp;
// Calculate uniswap time-weighted average price
// Underflow is a property of the accumulators: https://uniswap.org/audit.html#orgc9b3190
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed));
uint rawUniswapPriceMantissa = priceAverage.decode112with18();
uint unscaledPriceMantissa = mul(rawUniswapPriceMantissa, ethPrice);
uint anchorPrice = mul(unscaledPriceMantissa, config.baseUnit) / ethBaseUnit / expScale;
emit AnchorPriceUpdated(symbol, anchorPrice, oldTimestamp, block.timestamp);
return anchorPrice;
}
| 32,930
|
135
|
// Writes a checkpoint with given data to the given record and returns the checkpoint ID /
|
function writeCheckpoint(Record storage record, uint192 data)
internal returns (uint32 id)
|
function writeCheckpoint(Record storage record, uint192 data)
internal returns (uint32 id)
| 638
|
62
|
// if contract has X tokens, not sold since Y time, sell Z tokens
|
if (overMinimumTokenBalance && startTimeForSwap + intervalSecondsForSwap <= block.timestamp) {
startTimeForSwap = block.timestamp;
|
if (overMinimumTokenBalance && startTimeForSwap + intervalSecondsForSwap <= block.timestamp) {
startTimeForSwap = block.timestamp;
| 12,792
|
20
|
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
|
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner());
_;
}
|
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner());
_;
}
| 37,750
|
18
|
// proof for the node chosen by the participant
|
ChoiceProof proof;
|
ChoiceProof proof;
| 11,749
|
55
|
// data is active
|
bool _active;
|
bool _active;
| 13,301
|
7
|
// ensure the msgWaiting is not done, and that this auditor has not submitted an audit previously
|
require(msgsWaitingDone[msgWaitingN] == false);
MessageAwaitingAudit msgWaiting = msgsWaiting[msgWaitingN];
require(msgWaiting.auditedBy[msg.sender] == false);
require(msgWaiting.alarmedBy[msg.sender] == false);
require(alarmRaised[msgWaitingN] == false);
|
require(msgsWaitingDone[msgWaitingN] == false);
MessageAwaitingAudit msgWaiting = msgsWaiting[msgWaitingN];
require(msgWaiting.auditedBy[msg.sender] == false);
require(msgWaiting.alarmedBy[msg.sender] == false);
require(alarmRaised[msgWaitingN] == false);
| 11,878
|
16
|
// Removes tokens from liquidity pool and send result ETH to the Balancer
|
function remLiquidity(uint256 lpAmount) private returns (uint ETHAmount) {
IERC20(uniswapV2Pair).approve(uniswapV2Router, lpAmount);
(ETHAmount) = IUniswapV2Router02(uniswapV2Router)
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this),
lpAmount,
0,
0,
address(balancer),
block.timestamp
);
}
|
function remLiquidity(uint256 lpAmount) private returns (uint ETHAmount) {
IERC20(uniswapV2Pair).approve(uniswapV2Router, lpAmount);
(ETHAmount) = IUniswapV2Router02(uniswapV2Router)
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this),
lpAmount,
0,
0,
address(balancer),
block.timestamp
);
}
| 35,569
|
178
|
// /
|
uint32 private timeToVotingClosing = 259200;
|
uint32 private timeToVotingClosing = 259200;
| 3,219
|
4
|
// In order to keep backwards compatibility we have kept the userseed field around. We remove the use of it because given that the blockhashenters later, it overrides whatever randomness the used seed provides.Given that it adds no security, and can easily lead to misunderstandings,we have removed it from usage and can now provide a simpler API. /
|
uint256 constant private USER_SEED_PLACEHOLDER = 0;
|
uint256 constant private USER_SEED_PLACEHOLDER = 0;
| 29,228
|
617
|
// Changed to use new nonces.
|
bytes32 salt = keccak256(abi.encodePacked(pool.stakingToken, pool.rewardToken, uint256(1)));
address rewardDistToken = ClonesUpgradeable.cloneDeterministic(address(rewardDistTokenImpl), salt);
string memory name = stakingTokenProvider.nameForStakingToken(pool.rewardToken);
RewardDistributionTokenUpgradeable(rewardDistToken).__RewardDistributionToken_init(IERC20Upgradeable(pool.rewardToken), name, name);
return rewardDistToken;
|
bytes32 salt = keccak256(abi.encodePacked(pool.stakingToken, pool.rewardToken, uint256(1)));
address rewardDistToken = ClonesUpgradeable.cloneDeterministic(address(rewardDistTokenImpl), salt);
string memory name = stakingTokenProvider.nameForStakingToken(pool.rewardToken);
RewardDistributionTokenUpgradeable(rewardDistToken).__RewardDistributionToken_init(IERC20Upgradeable(pool.rewardToken), name, name);
return rewardDistToken;
| 74,411
|
1
|
// Should fail for `b == true`.
|
assert(x == 0);
|
assert(x == 0);
| 14,264
|
13
|
// Creates `_amount` tokens and assigns them to `_to`, increasingthe total supply.
|
* Emits a {Transfer} event with `from` set to the zero address.
* Emits a {Mint} event with `to` set to the `_to` address.
*
* Requirements
*
* - the caller should have {MINTER_ROLE} role.
* - {userRegistry.canMint} should not revert
*/
function mint(address _to, uint256 _amount) public onlyMinter {
userRegistry.canMint(_to);
_mint(_to, _amount);
emit Mint(_to, _amount);
}
|
* Emits a {Transfer} event with `from` set to the zero address.
* Emits a {Mint} event with `to` set to the `_to` address.
*
* Requirements
*
* - the caller should have {MINTER_ROLE} role.
* - {userRegistry.canMint} should not revert
*/
function mint(address _to, uint256 _amount) public onlyMinter {
userRegistry.canMint(_to);
_mint(_to, _amount);
emit Mint(_to, _amount);
}
| 34,585
|
25
|
// Message sender declares itself as a super app. configWord The super app manifest configuration, flags are defined in `SuperAppDefinitions` registrationKey The registration key issued by the governance, needed to register on a mainnet.On testnets or in dev environment, a placeholder (e.g. empty string) can be used.While the message sender must be the super app itself, the transaction sender (tx.origin)must be the deployer account the registration key was issued for. /
|
function registerAppWithKey(uint256 configWord, string calldata registrationKey) external;
|
function registerAppWithKey(uint256 configWord, string calldata registrationKey) external;
| 29,288
|
1
|
// =======sale_configure=======
|
uint256 public status;
mapping(address => bool) public White_List;
constructor(
uint256 maxBatchSize_,
uint256 collectionSize_,
uint256 gift_amount_
|
uint256 public status;
mapping(address => bool) public White_List;
constructor(
uint256 maxBatchSize_,
uint256 collectionSize_,
uint256 gift_amount_
| 21,673
|
19
|
// Required methods
|
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) external view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) external payable;
function transfer(address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
|
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) external view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) external payable;
function transfer(address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
| 2,016
|
2
|
// The event fired when a new mapp or gateway is stored here:
|
event addedNewStakeholder(uint8 gateway, address newStakeholderQNTAddress, address newStakeholderOperatorAddress, uint256 QNTforChannel, uint256 QNTforDeposit, uint256 expirationTime);
|
event addedNewStakeholder(uint8 gateway, address newStakeholderQNTAddress, address newStakeholderOperatorAddress, uint256 QNTforChannel, uint256 QNTforDeposit, uint256 expirationTime);
| 17,989
|
0
|
// VARIABLES /STRUCTS
|
struct Proposal {
uint256 yesCount;
uint256 noCount;
uint256 totalVotes;
}
|
struct Proposal {
uint256 yesCount;
uint256 noCount;
uint256 totalVotes;
}
| 21,049
|
34
|
// Receive an exact amount of KLAY for as few input tokens as possible, along the route determined bythe path. The first element of path is the input token, the last must be WKLAY, and any intermediate elementsrepresent intermediate pairs to trade through (if, for example, a direct pair does not exist). msg.sender should have already given the router an allowance of at least amountInMax on the input token.If the to address is a smart contract, it must have the ability to receive KLAY. amountOut The amount of KLAY to receive. amountInMax The maximum amount of input tokens that can be
|
function swapTokensForExactKLAY(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
|
function swapTokensForExactKLAY(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
| 31,091
|
51
|
// Resolves asset implementation contract for the caller and forwards there arguments along with/ the caller address./ return success.
|
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
|
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
| 36,280
|
167
|
// Encode pid, sushiPerShare to ERC1155 token id/pid Pool id (16-bit)/sushiPerShare Sushi amount per share, multiplied by 1e18 (240-bit)
|
function encodeId(uint pid, uint sushiPerShare) public pure returns (uint id) {
require(pid < (1 << 16), 'bad pid');
require(sushiPerShare < (1 << 240), 'bad sushi per share');
return (pid << 240) | sushiPerShare;
}
|
function encodeId(uint pid, uint sushiPerShare) public pure returns (uint id) {
require(pid < (1 << 16), 'bad pid');
require(sushiPerShare < (1 << 240), 'bad sushi per share');
return (pid << 240) | sushiPerShare;
}
| 59,956
|
3
|
// Returns the public RGT claim fee for users during liquidity mining (scaled by 1e18) at `blockNumber`. /
|
function getPublicRgtClaimFee(uint256 blockNumber) public view returns (uint256) {
return 0;
}
|
function getPublicRgtClaimFee(uint256 blockNumber) public view returns (uint256) {
return 0;
}
| 35,906
|
285
|
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
|
_balances[account] += amount;
|
_balances[account] += amount;
| 26,857
|
20
|
// Will be called by GelatoActionPipeline if Action.dataFlow.Out=> do not use for _actionData encoding
|
function execWithDataFlowOut(bytes calldata _actionData)
external
payable
virtual
override
returns (bytes memory)
|
function execWithDataFlowOut(bytes calldata _actionData)
external
payable
virtual
override
returns (bytes memory)
| 53,454
|
19
|
// Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`call, or as part of the Solidity `fallback` or `receive` functions. If overridden should call `super._beforeFallback()`. /
|
function _beforeFallback() internal virtual {}
}
|
function _beforeFallback() internal virtual {}
}
| 18,415
|
133
|
// Executing all minting
|
for (uint256 i = 0; i < nMint; i++) {
|
for (uint256 i = 0; i < nMint; i++) {
| 23,074
|
10
|
// the longest an new funding round can ever be
|
uint256 public constant maxMaxNumberDaysNewFunding = 8 weeks;
|
uint256 public constant maxMaxNumberDaysNewFunding = 8 weeks;
| 33,898
|
9
|
// The initial Public Reserved balance of tokens is assigned to the given token holder address. from total supple 90% tokens assign to public reservedholder
|
publicReservedToken = _totalSupply.mul(_publicReservedPersentage).div(tokenConversionFactor);
balances[_publicReserved] = publicReservedToken;
|
publicReservedToken = _totalSupply.mul(_publicReservedPersentage).div(tokenConversionFactor);
balances[_publicReserved] = publicReservedToken;
| 13,591
|
15
|
// Invest ETH into AAVE
|
_invest(_poolsTarget[2].sub(_pools[2]), _AAVE);
|
_invest(_poolsTarget[2].sub(_pools[2]), _AAVE);
| 25,189
|
10
|
// Error indicating that an invalid share has been passed to the function. /
|
error InvalidShare();
|
error InvalidShare();
| 27,358
|
69
|
// Divides x between y, rounding up to the closest representable number./ Assumes x and y are both fixed point with `decimals` digits.
|
function divdrup(uint256 x, uint256 y) internal pure returns (uint256)
|
function divdrup(uint256 x, uint256 y) internal pure returns (uint256)
| 45,455
|
4
|
// A data structure that represents a set of rules/Aaron Kendall//The actual rules are kept outside the struct since I'm currently unsure about the costs to keeping it inside
|
struct WonkaRuleSet {
bytes32 ruleSetId;
// WonkaRule[] ruleSetCollection;
bool andOp;
bool failImmediately;
bool isValue;
}
|
struct WonkaRuleSet {
bytes32 ruleSetId;
// WonkaRule[] ruleSetCollection;
bool andOp;
bool failImmediately;
bool isValue;
}
| 14,768
|
178
|
// This also deletes the contents at the last position of the array
|
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
|
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
| 145
|
148
|
// Set mUSD address
|
musd = _musd;
|
musd = _musd;
| 73,875
|
159
|
// move perToken payout balance to unclaimedPayoutTotals
|
require(settleUnclaimedPerTokenPayouts(msg.sender, _to));
return super.transfer(_to, _value);
|
require(settleUnclaimedPerTokenPayouts(msg.sender, _to));
return super.transfer(_to, _value);
| 8,855
|
8
|
// Overwrite auction with last item and remove duplicate item
|
auctions[auctionIndexes[_id]] = lastAuction;
auctions.length--;
|
auctions[auctionIndexes[_id]] = lastAuction;
auctions.length--;
| 30,834
|
58
|
// return borrowed amount to Flasher
|
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
|
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
| 39,516
|
5
|
// SafeMathMath operations with safety checks that throw on error/
|
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
|
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
| 2,113
|
806
|
// Divide v by the base to remove the digit that was just added.
|
v /= base;
|
v /= base;
| 10,138
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.