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 |
|---|---|---|---|---|
28 | // Copy over the first `submod` bytes of the new data as in case 1 above. | let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
| let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
| 28,220 |
67 | // If the wallet has a main UTXO hash set, cross-check it with the provided plain-text parameter and get the transaction output value as BTC balance. Otherwise, the BTC balance is just zero. | if (walletMainUtxoHash != bytes32(0)) {
require(
keccak256(
abi.encodePacked(
walletMainUtxo.txHash,
walletMainUtxo.txOutputIndex,
walletMainUtxo.txOutputValue
)
) == walletMainUtxoHash,
"Invalid wallet main UTXO data"
| if (walletMainUtxoHash != bytes32(0)) {
require(
keccak256(
abi.encodePacked(
walletMainUtxo.txHash,
walletMainUtxo.txOutputIndex,
walletMainUtxo.txOutputValue
)
) == walletMainUtxoHash,
"Invalid wallet main UTXO data"
| 10,914 |
18 | // sale functions ------------------------------------------------------------------------ | function setSupply(uint256 _MAX_FRENS, uint256 _MAX_MINT_PER_TX) external onlySaleNotActive onlyOwner {
require(_MAX_FRENS >= RESERVED_FRENS, "MAX_FRENS_MUST_GREATER_THAN_RESERVED_FRENS");
MAX_FRENS = _MAX_FRENS;
MAX_MINT_PER_TX = _MAX_MINT_PER_TX;
emit supplyChanged(_MAX_FRENS, _MAX_MINT_PER_TX);
}
| function setSupply(uint256 _MAX_FRENS, uint256 _MAX_MINT_PER_TX) external onlySaleNotActive onlyOwner {
require(_MAX_FRENS >= RESERVED_FRENS, "MAX_FRENS_MUST_GREATER_THAN_RESERVED_FRENS");
MAX_FRENS = _MAX_FRENS;
MAX_MINT_PER_TX = _MAX_MINT_PER_TX;
emit supplyChanged(_MAX_FRENS, _MAX_MINT_PER_TX);
}
| 77,922 |
64 | // Contract mapping identifiers to accounts / | contract Attestations is IAttestations, Ownable, Initializable, UsingRegistry {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint96;
event AttestationsRequested(
bytes32 indexed identifier,
address indexed account,
uint256 attestationsRequested,
address attestationRequestFeeToken
);
event AttestationCompleted(
bytes32 indexed identifier,
address indexed account,
address indexed issuer
);
event Withdrawal(
address indexed account,
address indexed token,
uint256 amount
);
event AttestationExpirySecondsSet(
uint256 value
);
event AttestationRequestFeeSet(
address indexed token,
uint256 value
);
event AccountDataEncryptionKeySet(
address indexed account,
bytes dataEncryptionKey
);
event AccountWalletAddressSet(
address indexed account,
address walletAddress
);
enum AttestationStatus {
None,
Incomplete,
Complete
}
struct Attestation {
AttestationStatus status;
// For outstanding attestations, this is the timestamp of the request
// For completed attestations, this is the timestamp of the attestation completion
uint128 time;
}
struct Account {
// The timestamp of the most recent attestation request
uint96 mostRecentAttestationRequest;
// The address at which the account expects to receive transfers
address walletAddress;
// The token with which attestation request fees are paid
address attestationRequestFeeToken;
// The ECDSA public key used to encrypt and decrypt data for this account
bytes dataEncryptionKey;
}
// Stores attestations state for a single (identifier, account address) pair.
struct AttestationsMapping {
// Number of completed attestations
uint64 completed;
// List of issuers responsible for attestations
address[] issuers;
// State of each attestation keyed by issuer
mapping(address => Attestation) issuedAttestations;
}
struct IdentifierState {
// All account addresses associated with this identifier
address[] accounts;
mapping(address => AttestationsMapping) attestations;
}
mapping(bytes32 => IdentifierState) identifiers;
mapping(address => Account) accounts;
// Address of the RequestAttestation precompiled contract.
// solhint-disable-next-line state-visibility
address constant REQUEST_ATTESTATION = address(0xff);
// The duration in seconds in which an attestation can be completed
uint256 public attestationExpirySeconds;
// The fees that are associated with attestations for a particular token.
mapping(address => uint256) public attestationRequestFees;
// Maps a token and attestation issuer to the amount that they're owed.
mapping(address => mapping(address => uint256)) public pendingWithdrawals;
function initialize(
address registryAddress,
uint256 _attestationExpirySeconds,
address[] calldata attestationRequestFeeTokens,
uint256[] calldata attestationRequestFeeValues
)
external
initializer
{
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setAttestationExpirySeconds(_attestationExpirySeconds);
require(
attestationRequestFeeTokens.length > 0 &&
attestationRequestFeeTokens.length == attestationRequestFeeValues.length,
"attestationRequestFeeTokens specification was invalid"
);
for (uint256 i = 0; i < attestationRequestFeeTokens.length; i = i.add(1)) {
setAttestationRequestFee(attestationRequestFeeTokens[i], attestationRequestFeeValues[i]);
}
}
/**
* @notice Commit to the attestation request of a hashed identifier.
* @param identifier The hash of the identifier to be attested.
* @param attestationsRequested The number of requested attestations for this request
* @param attestationRequestFeeToken The address of the token with which the attestation fee will
* be paid.
*/
function request(
bytes32 identifier,
uint256 attestationsRequested,
address attestationRequestFeeToken
)
external
{
require(
attestationRequestFees[attestationRequestFeeToken] > 0,
"Invalid attestationRequestFeeToken"
);
require(
IERC20Token(attestationRequestFeeToken).transferFrom(
msg.sender,
address(this),
attestationRequestFees[attestationRequestFeeToken].mul(attestationsRequested)
),
"Transfer of attestation request fees failed"
);
require(attestationsRequested > 0, "You have to request at least 1 attestation");
if (accounts[msg.sender].attestationRequestFeeToken != address(0x0)) {
require(
!isAttestationTimeValid(accounts[msg.sender].mostRecentAttestationRequest) ||
accounts[msg.sender].attestationRequestFeeToken == attestationRequestFeeToken,
"A different fee token was previously specified for this account"
);
}
// solhint-disable-next-line not-rely-on-time
accounts[msg.sender].mostRecentAttestationRequest = uint96(now);
accounts[msg.sender].attestationRequestFeeToken = attestationRequestFeeToken;
IdentifierState storage state = identifiers[identifier];
addIncompleteAttestations(attestationsRequested, state.attestations[msg.sender]);
emit AttestationsRequested(
identifier,
msg.sender,
attestationsRequested,
attestationRequestFeeToken
);
}
/**
* @notice Reveal the encrypted phone number to the issuer.
* @param identifier The hash of the identifier to be attested.
* @param encryptedPhone The number ECIES encrypted with the issuer's public key.
* @param issuer The issuer of the attestation
* @param sendSms Whether or not to send an SMS. For testing purposes.
*/
function reveal(
bytes32 identifier,
bytes calldata encryptedPhone,
address issuer,
bool sendSms
)
external
{
Attestation storage attestation =
identifiers[identifier].attestations[msg.sender].issuedAttestations[issuer];
require(
attestation.status == AttestationStatus.Incomplete,
"Attestation is not incomplete"
);
// solhint-disable-next-line not-rely-on-time
require(isAttestationTimeValid(attestation.time), "Attestation request timed out");
// Generate the yet-to-be-signed attestation code that will be signed and sent to the
// encrypted phone number via SMS via the 'RequestAttestation' precompiled contract.
if (sendSms) {
bool success;
// solhint-disable-next-line avoid-call-value
(success, ) = REQUEST_ATTESTATION.call.value(0).gas(gasleft())(abi.encode(
identifier,
keccak256(abi.encodePacked(identifier, msg.sender)),
msg.sender,
issuer,
encryptedPhone
));
require(success, "sending SMS failed");
}
}
/**
* @notice Submit the secret message sent by the issuer to complete the attestation request.
* @param identifier The hash of the identifier for this attestation.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Throws if there is no matching outstanding attestation request.
* @dev Throws if the attestation window has passed.
*/
function complete(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) external {
address issuer = validateAttestationCode(identifier, msg.sender, v, r, s);
Attestation storage attestation =
identifiers[identifier].attestations[msg.sender].issuedAttestations[issuer];
// solhint-disable-next-line not-rely-on-time
attestation.time = uint128(now);
attestation.status = AttestationStatus.Complete;
identifiers[identifier].attestations[msg.sender].completed++;
address token = accounts[msg.sender].attestationRequestFeeToken;
pendingWithdrawals[token][issuer] = pendingWithdrawals[token][issuer].add(
attestationRequestFees[token]
);
IdentifierState storage state = identifiers[identifier];
if (identifiers[identifier].attestations[msg.sender].completed == 1) {
state.accounts.push(msg.sender);
}
emit AttestationCompleted(identifier, msg.sender, issuer);
}
/**
* @notice Revokes an account for an identifier
* @param identifier The identifier for which to revoke
* @param index The index of the account in the accounts array
*/
function revoke(bytes32 identifier, uint256 index) external {
uint256 numAccounts = identifiers[identifier].accounts.length;
require(index < numAccounts, "Index is invalid");
require(
msg.sender == identifiers[identifier].accounts[index],
"Index does not match msg.sender"
);
uint256 newNumAccounts = numAccounts.sub(1);
if (index != newNumAccounts) {
identifiers[identifier].accounts[index] = identifiers[identifier].accounts[newNumAccounts];
}
identifiers[identifier].accounts[newNumAccounts] = address(0x0);
identifiers[identifier].accounts.length--;
}
/**
* @notice Allows issuers to withdraw accumulated attestation rewards.
* @param token The address of the token that will be withdrawn.
* @dev Throws if msg.sender does not have any rewards to withdraw.
*/
function withdraw(address token) external {
uint256 value = pendingWithdrawals[token][msg.sender];
require(value > 0, "value was negative/zero");
pendingWithdrawals[token][msg.sender] = 0;
require(IERC20Token(token).transfer(msg.sender, value), "token transfer failed");
emit Withdrawal(msg.sender, token, value);
}
/**
* @notice Setter for the dataEncryptionKey and wallet address for an account
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
* @param walletAddress The wallet address to set for the account
*/
function setAccount(
bytes calldata dataEncryptionKey,
address walletAddress
)
external
{
setAccountDataEncryptionKey(dataEncryptionKey);
setWalletAddress(walletAddress);
}
/**
* @notice Returns attestation issuers for a identifier/account pair
* @param identifier Hash of the identifier.
* @param account Address of the account
* @return Addresses of the attestation issuers
*/
function getAttestationIssuers(
bytes32 identifier,
address account
)
external
view
returns (address[] memory)
{
return identifiers[identifier].attestations[account].issuers;
}
/**
* @notice Returns attestation stats for a identifier/account pair
* @param identifier Hash of the identifier.
* @param account Address of the account
* @return [Number of completed attestations, Number of total requested attestations]
*/
function getAttestationStats(
bytes32 identifier,
address account
)
external
view
returns (uint64, uint64)
{
return (
identifiers[identifier].attestations[account].completed,
uint64(identifiers[identifier].attestations[account].issuers.length)
);
}
/**
* @notice Batch lookup function to determine attestation stats for a list of identifiers
* @param identifiersToLookup Array of n identifiers
* @return [0] Array of number of matching accounts per identifier
* @return [1] Array of sum([0]) matching walletAddresses
* @return [2] Array of sum([0]) numbers indicating the completions for each account
* @return [3] Array of sum([0]) numbers indicating the total number of requested
attestations for each account
*/
function batchGetAttestationStats(
bytes32[] calldata identifiersToLookup
)
external
view
returns (uint256[] memory, address[] memory, uint64[] memory, uint64[] memory)
{
require(identifiersToLookup.length > 0, "You have to pass at least one identifier");
uint256[] memory matches;
address[] memory addresses;
(matches, addresses) = batchlookupAccountsForIdentifier(
identifiersToLookup
);
uint64[] memory completed = new uint64[](addresses.length);
uint64[] memory total = new uint64[](addresses.length);
uint256 currentIndex = 0;
for (uint256 i = 0; i < identifiersToLookup.length; i++) {
address[] memory addrs = identifiers[identifiersToLookup[i]].accounts;
for (uint256 matchIndex = 0; matchIndex < matches[i]; matchIndex++) {
addresses[currentIndex] = accounts[addrs[matchIndex]].walletAddress;
completed[currentIndex] =
identifiers[identifiersToLookup[i]].attestations[addrs[matchIndex]].completed;
total[currentIndex] = uint64(
identifiers[identifiersToLookup[i]].attestations[addrs[matchIndex]].issuers.length
);
currentIndex++;
}
}
return (matches, addresses, completed, total);
}
/**
* @notice Returns the state of a specific attestation
* @param identifier Hash of the identifier.
* @param account Address of the account
* @param issuer Address of the issuer
* @return [Status of the attestation, time of the attestation]
*/
function getAttestationState(
bytes32 identifier,
address account,
address issuer
)
external
view
returns (uint8, uint128)
{
return (
uint8(identifiers[identifier].attestations[account].issuedAttestations[issuer].status),
identifiers[identifier].attestations[account].issuedAttestations[issuer].time
);
}
/**
* @notice Returns address of the token in which the account chose to pay attestation fees
* @param account Address of the account
* @return Address of the token contract
*/
function getAttestationRequestFeeToken(address account) external view returns (address) {
return accounts[account].attestationRequestFeeToken;
}
/**
* @notice Returns timestamp of the most recent attestation request
* @param account Address of the account
* @return Timestamp of the most recent attestation request
*/
function getMostRecentAttestationRequest(address account)
external
view
returns (uint256)
{
return accounts[account].mostRecentAttestationRequest;
}
/**
* @notice Returns the fee set for a particular token.
* @param token Address of the attestationRequestFeeToken.
* @return The fee.
*/
function getAttestationRequestFee(address token) external view returns (uint256) {
return attestationRequestFees[token];
}
/**
* @notice Updates the fee for a particular token.
* @param token The address of the attestationRequestFeeToken.
* @param fee The fee in 'token' that is required for each attestation.
*/
function setAttestationRequestFee(address token, uint256 fee) public onlyOwner {
require(fee > 0, "You have to specify a fee greater than 0");
attestationRequestFees[token] = fee;
emit AttestationRequestFeeSet(token, fee);
}
/**
* @notice Updates 'attestationExpirySeconds'.
* @param _attestationExpirySeconds The new limit on blocks allowed to come between requesting
* an attestation and completing it.
*/
function setAttestationExpirySeconds(uint256 _attestationExpirySeconds) public onlyOwner {
require(_attestationExpirySeconds > 0, "attestationExpirySeconds has to be greater than 0");
attestationExpirySeconds = _attestationExpirySeconds;
emit AttestationExpirySecondsSet(_attestationExpirySeconds);
}
/**
* @notice Setter for the data encryption key and version.
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function setAccountDataEncryptionKey(bytes memory dataEncryptionKey) public {
require(dataEncryptionKey.length >= 33, "data encryption key length <= 32");
accounts[msg.sender].dataEncryptionKey = dataEncryptionKey;
emit AccountDataEncryptionKeySet(msg.sender, dataEncryptionKey);
}
/**
* @notice Getter for the data encryption key and version.
* @param account The address of the account to get the key for
* @return dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function getDataEncryptionKey(address account) public view returns (bytes memory) {
return accounts[account].dataEncryptionKey;
}
/**
* @notice Setter for the wallet address for an account
* @param walletAddress The wallet address to set for the account
*/
function setWalletAddress(address walletAddress) public {
accounts[msg.sender].walletAddress = walletAddress;
emit AccountWalletAddressSet(msg.sender, walletAddress);
}
/**
* @notice Getter for the wallet address for an account
* @param account The address of the account to get the wallet address for
* @return Wallet address
*/
function getWalletAddress(address account) public view returns (address) {
return accounts[account].walletAddress;
}
/**
* @notice Validates the given attestation code.
* @param identifier The hash of the identifier to be attested.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @return The issuer of the corresponding attestation.
* @dev Throws if there is no matching outstanding attestation request.
* @dev Throws if the attestation window has passed.
*/
function validateAttestationCode(
bytes32 identifier,
address account,
uint8 v,
bytes32 r,
bytes32 s
)
public
view
returns (address)
{
bytes32 codehash = keccak256(abi.encodePacked(identifier, account));
address issuer = ecrecover(codehash, v, r, s);
Attestation storage attestation =
identifiers[identifier].attestations[account].issuedAttestations[issuer];
require(
attestation.status == AttestationStatus.Incomplete,
"Attestation code does not match any outstanding attestation"
);
// solhint-disable-next-line not-rely-on-time
require(isAttestationTimeValid(attestation.time), "Attestation request timed out");
return issuer;
}
function lookupAccountsForIdentifier(
bytes32 identifier
)
public
view
returns (address[] memory)
{
return identifiers[identifier].accounts;
}
/**
* @notice Returns the current validator set
* TODO: Should be replaced with a precompile
*/
function getValidators() public view returns (address[] memory) {
IValidators validatorContract = IValidators(
registry.getAddressForOrDie(VALIDATORS_REGISTRY_ID)
);
return validatorContract.getValidators();
}
/**
* @notice Helper function for batchGetAttestationStats to calculate the
total number of addresses that have >0 complete attestations for the identifiers
* @param identifiersToLookup Array of n identifiers
* @return Array of n numbers that indicate the number of matching addresses per identifier
* and array of addresses preallocated for total number of matches
*/
function batchlookupAccountsForIdentifier(
bytes32[] memory identifiersToLookup
)
internal
view
returns (uint256[] memory, address[] memory)
{
require(identifiersToLookup.length > 0, "You have to pass at least one identifier");
uint256 totalAddresses = 0;
uint256[] memory matches = new uint256[](identifiersToLookup.length);
for (uint256 i = 0; i < identifiersToLookup.length; i++) {
uint256 count = identifiers[identifiersToLookup[i]].accounts.length;
totalAddresses = totalAddresses + count;
matches[i] = count;
}
return (matches, new address[](totalAddresses));
}
/**
* @notice Adds additional attestations given the current randomness
* @param n Number of attestations to add
* @param state The accountState of the address to add attestations for
*/
function addIncompleteAttestations(
uint256 n,
AttestationsMapping storage state
)
internal
{
IRandom random = IRandom(registry.getAddressForOrDie(RANDOM_REGISTRY_ID));
bytes32 seed = random.random();
address[] memory validators = getValidators();
uint256 currentIndex = 0;
address validator;
while (currentIndex < n) {
seed = keccak256(abi.encodePacked(seed));
validator = validators[uint256(seed) % validators.length];
Attestation storage attestations =
state.issuedAttestations[validator];
// Attestation issuers can only be added if they haven't already
if (attestations.status != AttestationStatus.None) {
continue;
}
currentIndex++;
attestations.status = AttestationStatus.Incomplete;
// solhint-disable-next-line not-rely-on-time
attestations.time = uint128(now);
state.issuers.push(validator);
}
}
function isAttestationTimeValid(uint128 attestationTime) internal view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return now < attestationTime.add(attestationExpirySeconds);
}
}
| contract Attestations is IAttestations, Ownable, Initializable, UsingRegistry {
using SafeMath for uint256;
using SafeMath for uint128;
using SafeMath for uint96;
event AttestationsRequested(
bytes32 indexed identifier,
address indexed account,
uint256 attestationsRequested,
address attestationRequestFeeToken
);
event AttestationCompleted(
bytes32 indexed identifier,
address indexed account,
address indexed issuer
);
event Withdrawal(
address indexed account,
address indexed token,
uint256 amount
);
event AttestationExpirySecondsSet(
uint256 value
);
event AttestationRequestFeeSet(
address indexed token,
uint256 value
);
event AccountDataEncryptionKeySet(
address indexed account,
bytes dataEncryptionKey
);
event AccountWalletAddressSet(
address indexed account,
address walletAddress
);
enum AttestationStatus {
None,
Incomplete,
Complete
}
struct Attestation {
AttestationStatus status;
// For outstanding attestations, this is the timestamp of the request
// For completed attestations, this is the timestamp of the attestation completion
uint128 time;
}
struct Account {
// The timestamp of the most recent attestation request
uint96 mostRecentAttestationRequest;
// The address at which the account expects to receive transfers
address walletAddress;
// The token with which attestation request fees are paid
address attestationRequestFeeToken;
// The ECDSA public key used to encrypt and decrypt data for this account
bytes dataEncryptionKey;
}
// Stores attestations state for a single (identifier, account address) pair.
struct AttestationsMapping {
// Number of completed attestations
uint64 completed;
// List of issuers responsible for attestations
address[] issuers;
// State of each attestation keyed by issuer
mapping(address => Attestation) issuedAttestations;
}
struct IdentifierState {
// All account addresses associated with this identifier
address[] accounts;
mapping(address => AttestationsMapping) attestations;
}
mapping(bytes32 => IdentifierState) identifiers;
mapping(address => Account) accounts;
// Address of the RequestAttestation precompiled contract.
// solhint-disable-next-line state-visibility
address constant REQUEST_ATTESTATION = address(0xff);
// The duration in seconds in which an attestation can be completed
uint256 public attestationExpirySeconds;
// The fees that are associated with attestations for a particular token.
mapping(address => uint256) public attestationRequestFees;
// Maps a token and attestation issuer to the amount that they're owed.
mapping(address => mapping(address => uint256)) public pendingWithdrawals;
function initialize(
address registryAddress,
uint256 _attestationExpirySeconds,
address[] calldata attestationRequestFeeTokens,
uint256[] calldata attestationRequestFeeValues
)
external
initializer
{
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setAttestationExpirySeconds(_attestationExpirySeconds);
require(
attestationRequestFeeTokens.length > 0 &&
attestationRequestFeeTokens.length == attestationRequestFeeValues.length,
"attestationRequestFeeTokens specification was invalid"
);
for (uint256 i = 0; i < attestationRequestFeeTokens.length; i = i.add(1)) {
setAttestationRequestFee(attestationRequestFeeTokens[i], attestationRequestFeeValues[i]);
}
}
/**
* @notice Commit to the attestation request of a hashed identifier.
* @param identifier The hash of the identifier to be attested.
* @param attestationsRequested The number of requested attestations for this request
* @param attestationRequestFeeToken The address of the token with which the attestation fee will
* be paid.
*/
function request(
bytes32 identifier,
uint256 attestationsRequested,
address attestationRequestFeeToken
)
external
{
require(
attestationRequestFees[attestationRequestFeeToken] > 0,
"Invalid attestationRequestFeeToken"
);
require(
IERC20Token(attestationRequestFeeToken).transferFrom(
msg.sender,
address(this),
attestationRequestFees[attestationRequestFeeToken].mul(attestationsRequested)
),
"Transfer of attestation request fees failed"
);
require(attestationsRequested > 0, "You have to request at least 1 attestation");
if (accounts[msg.sender].attestationRequestFeeToken != address(0x0)) {
require(
!isAttestationTimeValid(accounts[msg.sender].mostRecentAttestationRequest) ||
accounts[msg.sender].attestationRequestFeeToken == attestationRequestFeeToken,
"A different fee token was previously specified for this account"
);
}
// solhint-disable-next-line not-rely-on-time
accounts[msg.sender].mostRecentAttestationRequest = uint96(now);
accounts[msg.sender].attestationRequestFeeToken = attestationRequestFeeToken;
IdentifierState storage state = identifiers[identifier];
addIncompleteAttestations(attestationsRequested, state.attestations[msg.sender]);
emit AttestationsRequested(
identifier,
msg.sender,
attestationsRequested,
attestationRequestFeeToken
);
}
/**
* @notice Reveal the encrypted phone number to the issuer.
* @param identifier The hash of the identifier to be attested.
* @param encryptedPhone The number ECIES encrypted with the issuer's public key.
* @param issuer The issuer of the attestation
* @param sendSms Whether or not to send an SMS. For testing purposes.
*/
function reveal(
bytes32 identifier,
bytes calldata encryptedPhone,
address issuer,
bool sendSms
)
external
{
Attestation storage attestation =
identifiers[identifier].attestations[msg.sender].issuedAttestations[issuer];
require(
attestation.status == AttestationStatus.Incomplete,
"Attestation is not incomplete"
);
// solhint-disable-next-line not-rely-on-time
require(isAttestationTimeValid(attestation.time), "Attestation request timed out");
// Generate the yet-to-be-signed attestation code that will be signed and sent to the
// encrypted phone number via SMS via the 'RequestAttestation' precompiled contract.
if (sendSms) {
bool success;
// solhint-disable-next-line avoid-call-value
(success, ) = REQUEST_ATTESTATION.call.value(0).gas(gasleft())(abi.encode(
identifier,
keccak256(abi.encodePacked(identifier, msg.sender)),
msg.sender,
issuer,
encryptedPhone
));
require(success, "sending SMS failed");
}
}
/**
* @notice Submit the secret message sent by the issuer to complete the attestation request.
* @param identifier The hash of the identifier for this attestation.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Throws if there is no matching outstanding attestation request.
* @dev Throws if the attestation window has passed.
*/
function complete(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) external {
address issuer = validateAttestationCode(identifier, msg.sender, v, r, s);
Attestation storage attestation =
identifiers[identifier].attestations[msg.sender].issuedAttestations[issuer];
// solhint-disable-next-line not-rely-on-time
attestation.time = uint128(now);
attestation.status = AttestationStatus.Complete;
identifiers[identifier].attestations[msg.sender].completed++;
address token = accounts[msg.sender].attestationRequestFeeToken;
pendingWithdrawals[token][issuer] = pendingWithdrawals[token][issuer].add(
attestationRequestFees[token]
);
IdentifierState storage state = identifiers[identifier];
if (identifiers[identifier].attestations[msg.sender].completed == 1) {
state.accounts.push(msg.sender);
}
emit AttestationCompleted(identifier, msg.sender, issuer);
}
/**
* @notice Revokes an account for an identifier
* @param identifier The identifier for which to revoke
* @param index The index of the account in the accounts array
*/
function revoke(bytes32 identifier, uint256 index) external {
uint256 numAccounts = identifiers[identifier].accounts.length;
require(index < numAccounts, "Index is invalid");
require(
msg.sender == identifiers[identifier].accounts[index],
"Index does not match msg.sender"
);
uint256 newNumAccounts = numAccounts.sub(1);
if (index != newNumAccounts) {
identifiers[identifier].accounts[index] = identifiers[identifier].accounts[newNumAccounts];
}
identifiers[identifier].accounts[newNumAccounts] = address(0x0);
identifiers[identifier].accounts.length--;
}
/**
* @notice Allows issuers to withdraw accumulated attestation rewards.
* @param token The address of the token that will be withdrawn.
* @dev Throws if msg.sender does not have any rewards to withdraw.
*/
function withdraw(address token) external {
uint256 value = pendingWithdrawals[token][msg.sender];
require(value > 0, "value was negative/zero");
pendingWithdrawals[token][msg.sender] = 0;
require(IERC20Token(token).transfer(msg.sender, value), "token transfer failed");
emit Withdrawal(msg.sender, token, value);
}
/**
* @notice Setter for the dataEncryptionKey and wallet address for an account
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
* @param walletAddress The wallet address to set for the account
*/
function setAccount(
bytes calldata dataEncryptionKey,
address walletAddress
)
external
{
setAccountDataEncryptionKey(dataEncryptionKey);
setWalletAddress(walletAddress);
}
/**
* @notice Returns attestation issuers for a identifier/account pair
* @param identifier Hash of the identifier.
* @param account Address of the account
* @return Addresses of the attestation issuers
*/
function getAttestationIssuers(
bytes32 identifier,
address account
)
external
view
returns (address[] memory)
{
return identifiers[identifier].attestations[account].issuers;
}
/**
* @notice Returns attestation stats for a identifier/account pair
* @param identifier Hash of the identifier.
* @param account Address of the account
* @return [Number of completed attestations, Number of total requested attestations]
*/
function getAttestationStats(
bytes32 identifier,
address account
)
external
view
returns (uint64, uint64)
{
return (
identifiers[identifier].attestations[account].completed,
uint64(identifiers[identifier].attestations[account].issuers.length)
);
}
/**
* @notice Batch lookup function to determine attestation stats for a list of identifiers
* @param identifiersToLookup Array of n identifiers
* @return [0] Array of number of matching accounts per identifier
* @return [1] Array of sum([0]) matching walletAddresses
* @return [2] Array of sum([0]) numbers indicating the completions for each account
* @return [3] Array of sum([0]) numbers indicating the total number of requested
attestations for each account
*/
function batchGetAttestationStats(
bytes32[] calldata identifiersToLookup
)
external
view
returns (uint256[] memory, address[] memory, uint64[] memory, uint64[] memory)
{
require(identifiersToLookup.length > 0, "You have to pass at least one identifier");
uint256[] memory matches;
address[] memory addresses;
(matches, addresses) = batchlookupAccountsForIdentifier(
identifiersToLookup
);
uint64[] memory completed = new uint64[](addresses.length);
uint64[] memory total = new uint64[](addresses.length);
uint256 currentIndex = 0;
for (uint256 i = 0; i < identifiersToLookup.length; i++) {
address[] memory addrs = identifiers[identifiersToLookup[i]].accounts;
for (uint256 matchIndex = 0; matchIndex < matches[i]; matchIndex++) {
addresses[currentIndex] = accounts[addrs[matchIndex]].walletAddress;
completed[currentIndex] =
identifiers[identifiersToLookup[i]].attestations[addrs[matchIndex]].completed;
total[currentIndex] = uint64(
identifiers[identifiersToLookup[i]].attestations[addrs[matchIndex]].issuers.length
);
currentIndex++;
}
}
return (matches, addresses, completed, total);
}
/**
* @notice Returns the state of a specific attestation
* @param identifier Hash of the identifier.
* @param account Address of the account
* @param issuer Address of the issuer
* @return [Status of the attestation, time of the attestation]
*/
function getAttestationState(
bytes32 identifier,
address account,
address issuer
)
external
view
returns (uint8, uint128)
{
return (
uint8(identifiers[identifier].attestations[account].issuedAttestations[issuer].status),
identifiers[identifier].attestations[account].issuedAttestations[issuer].time
);
}
/**
* @notice Returns address of the token in which the account chose to pay attestation fees
* @param account Address of the account
* @return Address of the token contract
*/
function getAttestationRequestFeeToken(address account) external view returns (address) {
return accounts[account].attestationRequestFeeToken;
}
/**
* @notice Returns timestamp of the most recent attestation request
* @param account Address of the account
* @return Timestamp of the most recent attestation request
*/
function getMostRecentAttestationRequest(address account)
external
view
returns (uint256)
{
return accounts[account].mostRecentAttestationRequest;
}
/**
* @notice Returns the fee set for a particular token.
* @param token Address of the attestationRequestFeeToken.
* @return The fee.
*/
function getAttestationRequestFee(address token) external view returns (uint256) {
return attestationRequestFees[token];
}
/**
* @notice Updates the fee for a particular token.
* @param token The address of the attestationRequestFeeToken.
* @param fee The fee in 'token' that is required for each attestation.
*/
function setAttestationRequestFee(address token, uint256 fee) public onlyOwner {
require(fee > 0, "You have to specify a fee greater than 0");
attestationRequestFees[token] = fee;
emit AttestationRequestFeeSet(token, fee);
}
/**
* @notice Updates 'attestationExpirySeconds'.
* @param _attestationExpirySeconds The new limit on blocks allowed to come between requesting
* an attestation and completing it.
*/
function setAttestationExpirySeconds(uint256 _attestationExpirySeconds) public onlyOwner {
require(_attestationExpirySeconds > 0, "attestationExpirySeconds has to be greater than 0");
attestationExpirySeconds = _attestationExpirySeconds;
emit AttestationExpirySecondsSet(_attestationExpirySeconds);
}
/**
* @notice Setter for the data encryption key and version.
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function setAccountDataEncryptionKey(bytes memory dataEncryptionKey) public {
require(dataEncryptionKey.length >= 33, "data encryption key length <= 32");
accounts[msg.sender].dataEncryptionKey = dataEncryptionKey;
emit AccountDataEncryptionKeySet(msg.sender, dataEncryptionKey);
}
/**
* @notice Getter for the data encryption key and version.
* @param account The address of the account to get the key for
* @return dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function getDataEncryptionKey(address account) public view returns (bytes memory) {
return accounts[account].dataEncryptionKey;
}
/**
* @notice Setter for the wallet address for an account
* @param walletAddress The wallet address to set for the account
*/
function setWalletAddress(address walletAddress) public {
accounts[msg.sender].walletAddress = walletAddress;
emit AccountWalletAddressSet(msg.sender, walletAddress);
}
/**
* @notice Getter for the wallet address for an account
* @param account The address of the account to get the wallet address for
* @return Wallet address
*/
function getWalletAddress(address account) public view returns (address) {
return accounts[account].walletAddress;
}
/**
* @notice Validates the given attestation code.
* @param identifier The hash of the identifier to be attested.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @return The issuer of the corresponding attestation.
* @dev Throws if there is no matching outstanding attestation request.
* @dev Throws if the attestation window has passed.
*/
function validateAttestationCode(
bytes32 identifier,
address account,
uint8 v,
bytes32 r,
bytes32 s
)
public
view
returns (address)
{
bytes32 codehash = keccak256(abi.encodePacked(identifier, account));
address issuer = ecrecover(codehash, v, r, s);
Attestation storage attestation =
identifiers[identifier].attestations[account].issuedAttestations[issuer];
require(
attestation.status == AttestationStatus.Incomplete,
"Attestation code does not match any outstanding attestation"
);
// solhint-disable-next-line not-rely-on-time
require(isAttestationTimeValid(attestation.time), "Attestation request timed out");
return issuer;
}
function lookupAccountsForIdentifier(
bytes32 identifier
)
public
view
returns (address[] memory)
{
return identifiers[identifier].accounts;
}
/**
* @notice Returns the current validator set
* TODO: Should be replaced with a precompile
*/
function getValidators() public view returns (address[] memory) {
IValidators validatorContract = IValidators(
registry.getAddressForOrDie(VALIDATORS_REGISTRY_ID)
);
return validatorContract.getValidators();
}
/**
* @notice Helper function for batchGetAttestationStats to calculate the
total number of addresses that have >0 complete attestations for the identifiers
* @param identifiersToLookup Array of n identifiers
* @return Array of n numbers that indicate the number of matching addresses per identifier
* and array of addresses preallocated for total number of matches
*/
function batchlookupAccountsForIdentifier(
bytes32[] memory identifiersToLookup
)
internal
view
returns (uint256[] memory, address[] memory)
{
require(identifiersToLookup.length > 0, "You have to pass at least one identifier");
uint256 totalAddresses = 0;
uint256[] memory matches = new uint256[](identifiersToLookup.length);
for (uint256 i = 0; i < identifiersToLookup.length; i++) {
uint256 count = identifiers[identifiersToLookup[i]].accounts.length;
totalAddresses = totalAddresses + count;
matches[i] = count;
}
return (matches, new address[](totalAddresses));
}
/**
* @notice Adds additional attestations given the current randomness
* @param n Number of attestations to add
* @param state The accountState of the address to add attestations for
*/
function addIncompleteAttestations(
uint256 n,
AttestationsMapping storage state
)
internal
{
IRandom random = IRandom(registry.getAddressForOrDie(RANDOM_REGISTRY_ID));
bytes32 seed = random.random();
address[] memory validators = getValidators();
uint256 currentIndex = 0;
address validator;
while (currentIndex < n) {
seed = keccak256(abi.encodePacked(seed));
validator = validators[uint256(seed) % validators.length];
Attestation storage attestations =
state.issuedAttestations[validator];
// Attestation issuers can only be added if they haven't already
if (attestations.status != AttestationStatus.None) {
continue;
}
currentIndex++;
attestations.status = AttestationStatus.Incomplete;
// solhint-disable-next-line not-rely-on-time
attestations.time = uint128(now);
state.issuers.push(validator);
}
}
function isAttestationTimeValid(uint128 attestationTime) internal view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return now < attestationTime.add(attestationExpirySeconds);
}
}
| 49,709 |
5 | // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets | uint256[] collateralAmounts;
| uint256[] collateralAmounts;
| 14,464 |
50 | // find max mostF1Earnerd | softMostF1(refAdress);
| softMostF1(refAdress);
| 33,656 |
70 | // Burn pxCVX | pxCvx.burn(msg.sender, assets);
emit Stake(rounds, f, assets, receiver);
| pxCvx.burn(msg.sender, assets);
emit Stake(rounds, f, assets, receiver);
| 17,681 |
4 | // The VestedERC20 used as the template for all clones created | VestedERC20 public immutable implementation;
constructor(VestedERC20 implementation_) {
implementation = implementation_;
}
| VestedERC20 public immutable implementation;
constructor(VestedERC20 implementation_) {
implementation = implementation_;
}
| 6,988 |
1,694 | // Information about reserves/_tokenAddresses Array of tokens addresses/ return tokens Array of reserves infomartion | function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
| function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
| 31,645 |
1 | // queried by others ({ERC165Checker}).For an implementation, see {ERC165}./ Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30 000 gas. / | function supportsInterface(bytes4 interfaceId) external view returns (bool);
| function supportsInterface(bytes4 interfaceId) external view returns (bool);
| 2,795 |
8 | // facet addresses | address[] facetAddresses;
| address[] facetAddresses;
| 34,243 |
44 | // transferERC20 standard transfer wrapped with `activated` modifier / | function transfer(address to, uint256 value) public activated returns (bool) {
return super.transfer(to, value);
}
| function transfer(address to, uint256 value) public activated returns (bool) {
return super.transfer(to, value);
}
| 1,855 |
544 | // undo timeline so that validator is normal validator | updateTimeline(int256(amount.add(validators[validatorId].delegatedAmount)), 1, 0);
validators[validatorId].status = Status.Active;
address signer = validators[validatorId].signer;
logger.logUnjailed(validatorId, signer);
| updateTimeline(int256(amount.add(validators[validatorId].delegatedAmount)), 1, 0);
validators[validatorId].status = Status.Active;
address signer = validators[validatorId].signer;
logger.logUnjailed(validatorId, signer);
| 12,661 |
10 | // Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. / | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| 13,233 |
111 | // Unpauses HAs functions | function unpause() external override onlyRole(GUARDIAN_ROLE) {
_unpause();
}
| function unpause() external override onlyRole(GUARDIAN_ROLE) {
_unpause();
}
| 31,057 |
13 | // Check the signature length - case 65: r,s,v signature (standard) - case 64: r,vs signature (cf https:eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ | if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
| if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
| 28,611 |
7 | // Error thrown when the owner of the contract tries to burn tokens continuously. | error OwnerCanNotContinuousBurn();
| error OwnerCanNotContinuousBurn();
| 24,733 |
29 | // Overrides the `_startTokenId` function from ERC721A to start at token id `1`.This is to avoid future possible problems since `0` is usually used to signal values that have not been set or have been removed. / | function _startTokenId() internal view virtual override returns (uint256) {
return 1;
}
| function _startTokenId() internal view virtual override returns (uint256) {
return 1;
}
| 1,475 |
24 | // register player if unregistered | Player storage player = players[msg.sender];
if(player.id == 0)
toRegisterPlayer = true;
| Player storage player = players[msg.sender];
if(player.id == 0)
toRegisterPlayer = true;
| 23,789 |
29 | // permission related | function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
require(newOwner != address(this));
require(newOwner != admin);
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
| function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
require(newOwner != address(this));
require(newOwner != admin);
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
| 52,729 |
23 | // transfer profit to the user | shieldMiningInfo[_policyBook].rewardsToken.safeTransfer(
_user,
DecimalsConverter.convertFrom18(reward, _tokenDecimals)
);
shieldMiningInfo[_policyBook].rewardTokensLocked -= reward;
emit ShieldMiningClaimed(_user, _policyBook, reward);
| shieldMiningInfo[_policyBook].rewardsToken.safeTransfer(
_user,
DecimalsConverter.convertFrom18(reward, _tokenDecimals)
);
shieldMiningInfo[_policyBook].rewardTokensLocked -= reward;
emit ShieldMiningClaimed(_user, _policyBook, reward);
| 50,625 |
21 | // Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond. | struct Commitment {
uint32 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
}
| struct Commitment {
uint32 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
}
| 66,185 |
14 | // The address is unregistered so we throw and log event This method and callers have to overriden as non-constant to emit events if ( subjectCount == 0 ) { GotUnregisteredPaymentAddress( paymentAddress ); revert(); } |
require(subjectCount > 0);
return subjectCount;
|
require(subjectCount > 0);
return subjectCount;
| 50,276 |
275 | // Determine if a tokenId exists (has been sold) | function sold(uint256 _tokenId) public view returns (bool) {
return token.exists(_tokenId);
}
| function sold(uint256 _tokenId) public view returns (bool) {
return token.exists(_tokenId);
}
| 68,025 |
51 | // Provides the granularity of the token return uint256/ | function granularity() external view returns(uint256);
| function granularity() external view returns(uint256);
| 3,355 |
7 | // Get the `pos`-th checkpoint for `account`. / | function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) {
return _checkpoints(account, pos);
}
| function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) {
return _checkpoints(account, pos);
}
| 562 |
27 | // get that token from all safe trees token mapping and create a memory of it defined as (struct => KDZTokenStruct) | KDZTokenStruct memory updatedToken = _kdzTokens[_tokenId];
| KDZTokenStruct memory updatedToken = _kdzTokens[_tokenId];
| 10,784 |
18 | // Transfers vested tokens to given address. token ERC20 token which is being vested receiver Address receiving the token amount Amount of tokens to be transferred / | function releaseToAddress(IERC20 token, address receiver, uint256 amount) public {
require(_msgSender() == _beneficiary, "TokenVesting::setBeneficiary: Not contract beneficiary");
require(amount > 0, "TokenVesting::_releaseToAddress: amount should be greater than 0");
require(receiver != address(0), "TokenVesting::_releaseToAddress: receiver is the zero address");
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenVesting::_releaseToAddress: no tokens are due");
require(unreleased >= amount, "TokenVesting::_releaseToAddress: enough tokens not vested yet");
_released[address(token)] = _released[address(token)].add(amount);
token.safeTransfer(receiver, amount);
emit TokensReleasedToAccount(address(token), receiver, amount);
}
| function releaseToAddress(IERC20 token, address receiver, uint256 amount) public {
require(_msgSender() == _beneficiary, "TokenVesting::setBeneficiary: Not contract beneficiary");
require(amount > 0, "TokenVesting::_releaseToAddress: amount should be greater than 0");
require(receiver != address(0), "TokenVesting::_releaseToAddress: receiver is the zero address");
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenVesting::_releaseToAddress: no tokens are due");
require(unreleased >= amount, "TokenVesting::_releaseToAddress: enough tokens not vested yet");
_released[address(token)] = _released[address(token)].add(amount);
token.safeTransfer(receiver, amount);
emit TokensReleasedToAccount(address(token), receiver, amount);
}
| 13,329 |
218 | // stETH and rETH token contracts | IstETH internal constant steth =
IstETH(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);
IwstETH internal constant wsteth =
IwstETH(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0);
IERC20 internal constant reth =
IERC20(0xae78736Cd615f374D3085123A210448E74Fc6393);
| IstETH internal constant steth =
IstETH(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);
IwstETH internal constant wsteth =
IwstETH(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0);
IERC20 internal constant reth =
IERC20(0xae78736Cd615f374D3085123A210448E74Fc6393);
| 3,706 |
56 | // We restrict transferFrom by overriding it / | function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) {
// Call StandardToken.transferForm()
return super.transferFrom(from, to, value);
}
| function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) {
// Call StandardToken.transferForm()
return super.transferFrom(from, to, value);
}
| 24,299 |
91 | // Buy and burn | uint256 rewardForCaller = tokensForBuyAndBurn.mul(_rebalanceCallerFee).div(10 ** (_feeDecimal + 2));
uint256 amountToBurn = tokensForBuyAndBurn.sub(rewardForCaller);
uint256 rate = _getReflectionRate();
_reflectionBalance[tx.origin] = _reflectionBalance[tx.origin].add(rewardForCaller.mul(rate));
_reflectionBalance[address(balancer)] = 0;
_tokenTotal = _tokenTotal.sub(amountToBurn);
_reflectionTotal = _reflectionTotal.sub(amountToBurn.mul(rate));
| uint256 rewardForCaller = tokensForBuyAndBurn.mul(_rebalanceCallerFee).div(10 ** (_feeDecimal + 2));
uint256 amountToBurn = tokensForBuyAndBurn.sub(rewardForCaller);
uint256 rate = _getReflectionRate();
_reflectionBalance[tx.origin] = _reflectionBalance[tx.origin].add(rewardForCaller.mul(rate));
_reflectionBalance[address(balancer)] = 0;
_tokenTotal = _tokenTotal.sub(amountToBurn);
_reflectionTotal = _reflectionTotal.sub(amountToBurn.mul(rate));
| 17,139 |
224 | // Used to change `strategist`.This may only be called by governance or the existing strategist. _strategist The new address to assign as `strategist`. / | function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
| function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
| 3,165 |
2 | // Transfer shares from contract owner to the buyer | nft.sharesLeft -= _sharesToBuy;
userNFTBalances[msg.sender][_tokenId] += _sharesToBuy;
emit NFTBought(_tokenId, msg.sender, _sharesToBuy);
| nft.sharesLeft -= _sharesToBuy;
userNFTBalances[msg.sender][_tokenId] += _sharesToBuy;
emit NFTBought(_tokenId, msg.sender, _sharesToBuy);
| 25,238 |
2 | // Admin for financial contracts in the UMA system. Allows appropriately permissioned admin roles to interact with financial contracts. / | contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
| contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
| 53,166 |
60 | // pay pending reward | uint256 pending = user.amount.mul(pool.accEarningsPerShare).div(1e18).sub(
user.rewardDebt
);
if (pending > 0) {
safeEarningsTransfer(msg.sender, pending);
payReferralCommission(msg.sender, pending);
}
| uint256 pending = user.amount.mul(pool.accEarningsPerShare).div(1e18).sub(
user.rewardDebt
);
if (pending > 0) {
safeEarningsTransfer(msg.sender, pending);
payReferralCommission(msg.sender, pending);
}
| 3,317 |
6 | // It is emitted if an operator is removed from the global allowlist. operator Operator address / | event OperatorRemoved(address operator);
| event OperatorRemoved(address operator);
| 46,341 |
163 | // Send market fees to owner |
if (FeeManager.cutPerMillion > 0) {
|
if (FeeManager.cutPerMillion > 0) {
| 11,580 |
10 | // ============ Constructor ============ //Set core. Also requires a minimum rebalance interval and minimum proposal periods that are enforcedon RebalancingSetToken _core Address of deployed core contract_componentWhitelist Address of deployed whitelist contract_minimumRebalanceInterval Minimum amount of time between rebalances in seconds_minimumProposalPeriodMinimum amount of time users can review proposals in seconds_minimumTimeToPivot Minimum amount of time before auction pivot can be reached_maximumTimeToPivot Maximum amount of time before auction pivot can be reached_minimumNaturalUnit Minimum number for the token natural unit_maximumNaturalUnit Maximum number for the token natural unit / | constructor(
address _core,
address _componentWhitelist,
uint256 _minimumRebalanceInterval,
uint256 _minimumProposalPeriod,
uint256 _minimumTimeToPivot,
uint256 _maximumTimeToPivot,
uint256 _minimumNaturalUnit,
uint256 _maximumNaturalUnit
)
| constructor(
address _core,
address _componentWhitelist,
uint256 _minimumRebalanceInterval,
uint256 _minimumProposalPeriod,
uint256 _minimumTimeToPivot,
uint256 _maximumTimeToPivot,
uint256 _minimumNaturalUnit,
uint256 _maximumNaturalUnit
)
| 49,116 |
315 | // The Black Bear SVG renderer | IBearRenderer private _blackBearRenderer;
| IBearRenderer private _blackBearRenderer;
| 14,124 |
238 | // Make sure the strategy meets some criteria | require(strategies[_strategy].isSupported, "Strategy not approved");
IStrategy strategy = IStrategy(_strategy);
require(assets[_asset].isSupported, "Asset is not supported");
require(
strategy.supportsAsset(_asset),
"Asset not supported by Strategy"
);
| require(strategies[_strategy].isSupported, "Strategy not approved");
IStrategy strategy = IStrategy(_strategy);
require(assets[_asset].isSupported, "Asset is not supported");
require(
strategy.supportsAsset(_asset),
"Asset not supported by Strategy"
);
| 25,968 |
35 | // Gets Stanley address. | function getStanley() external view returns (address);
| function getStanley() external view returns (address);
| 41,948 |
30 | // Registers the exist layer2 on DAO/_layer2 Layer2 contract address to be registered/_memo A memo for the candidate | function registerLayer2Candidate(
address _layer2,
string memory _memo
)
external
override
validSeigManager
validLayer2Registry
validCommitteeL2Factory
| function registerLayer2Candidate(
address _layer2,
string memory _memo
)
external
override
validSeigManager
validLayer2Registry
validCommitteeL2Factory
| 5,110 |
17 | // Query if a contract implements an interface _interfaceId The interface identifier, as specified in ERC-165 Interface identification is specified in ERC-165. This functionuses less than 30,000 gas. / | function supportsInterface(bytes4 _interfaceId) external view returns (bool);
| function supportsInterface(bytes4 _interfaceId) external view returns (bool);
| 37,941 |
15 | // Only allow this to call itself since any call to a facet should be to the guardian contract address | require(address(this) == msg.sender, 'Call only allowed from guardian or facet contracts');
success = exec(_to, _value, _data, _operation);
return success;
| require(address(this) == msg.sender, 'Call only allowed from guardian or facet contracts');
success = exec(_to, _value, _data, _operation);
return success;
| 46,259 |
72 | // Note: do a direct access to avoid the validity check. | return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
| return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
| 19,280 |
20 | // It mints a new token for a Tier index. tierIndex Tier to mint token on. owner The owner of the new token. Requirements: - Caller must be an authorized minter / | function mint(uint256 tierIndex, address owner)
external
override
onlyMinter
| function mint(uint256 tierIndex, address owner)
external
override
onlyMinter
| 9,363 |
84 | // Structure holding information about a transaction/id Unique identifier of the transaction/from Address of the user from whose account tokens were transfered/to Address of the user to whom the tokens were transfered/token Address of the tokens which were transfered/amount Amount of the transfered tokens/note Each transaction must contain a note describing the transaction/timestamp Timestamp when the transaction was executed | struct Transaction
| struct Transaction
| 23,529 |
84 | // Contract constructor sets initial owners, required number of confirmations, and time lock. _owners List of initial owners._required Number of required confirmations._secondsTimeLockedDuration needed after a transaction is confirmed and before itbecomes executable, in seconds. / | constructor (
address[] memory _owners,
uint256 _required,
uint32 _secondsTimeLocked
)
public
MultiSig(_owners, _required)
| constructor (
address[] memory _owners,
uint256 _required,
uint32 _secondsTimeLocked
)
public
MultiSig(_owners, _required)
| 33,630 |
65 | // Resume a previously suspended ICO. / | function resume() public onlyOwner isSuspended {
state = State.Active;
ICOResumed(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei);
touch();
}
| function resume() public onlyOwner isSuspended {
state = State.Active;
ICOResumed(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei);
touch();
}
| 16,979 |
58 | // See {ERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}; Requirements:- `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for `sender`'s tokens of at least`amount`. / | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| 5,562 |
23 | // pragma solidity >0.4.13; / | contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
| contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
| 61,681 |
170 | // make a function to toss a proposal if no one can call enact based on time limt_changeDelegationMinimumsetBuoysetBPoolsetSwapFeechangeOwnersetStakingActivesetSwapingActive changeOwnerchangeWeightchangeStakingMaxchangeStakingShareupdate weights must be passed weights as a stringadd token needs amount of token to add in the contractremove token takes the amount of bpt to be burned/ | contract GovernanceProxy {
using BalancerSafeMath for uint256;
uint256 public lastProposed;
uint256 public proposalCount; //used to assign a unique ID to each proposal
uint256 public proposalsVoted; //used to keep track of which proposals have been decided on
uint256 proposalDelegationMinimum = 500; //should be adjustable
bool public proposalActive;
mapping (address => Delegation) delegation;
mapping (address => bool) proposers;
mapping (uint => Proposal) proposal;
struct Delegation {
uint withdrawDate;
uint delegated;
}
struct Proposal {
uint proposaltype;
uint creationDate;
uint startDate;
address proposer;
uint value1;
uint value2;
address address1;
bool bool1;
uint[] array1;
uint yesVotes;
uint noVotes;
}
IAddressIndex addressIndex;
constructor() public {
addressIndex = IAddressIndex(0x75843DB21C59Ca36e0c581da91F255883AfD3009);
}
//=======================enactable functions======================//
function _setSwapFee(uint _swapFee) private {
IBPool ibpool = IBPool(addressIndex.getBalancer());
ibpool.setSwapFee(_swapFee);
}
function _setDelegationMinimum(uint a) private {
proposalDelegationMinimum = a;
}
//========================vote functions=============================//
function newProposal(uint kind, uint _value1, uint _value2, address _address1, bool _bool1, uint[] calldata _array1) public payable {
//set it to require a delegation of 1% of the tokens
IERC20 buoyERC20 = IERC20(addressIndex.getBuoy());
require(buoyERC20.balanceOf(msg.sender) >= proposalDelegationMinimum, "Address has an active proposal already");
require(proposers[msg.sender] == false, "Address has an active proposal already");
buoyERC20.transferFrom(msg.sender, address(this), proposalDelegationMinimum);
proposalActive = true;
uint creationDate = now;
uint startDate;
if(lastProposed > (creationDate - 1 hours) && lastProposed != 0) {
startDate = lastProposed + 1 hours;
} else {
startDate = creationDate;
}
delegation[msg.sender] = Delegation(startDate+3 hours,proposalDelegationMinimum);
proposal[proposalCount] = Proposal(kind, creationDate, startDate, msg.sender, _value1, _value2, _address1, _bool1, _array1, 0, 0);
proposers[msg.sender] = true;
proposalCount++;
lastProposed = startDate;
}
// 0 = no, 1 = yes. voteWeight is measured in wei. approvals must be made before you can delegate
function castVoteERC20(uint propID, uint vote, uint voteWeight) public {
IERC20 BuoyERC20 = IERC20(addressIndex.getBuoy());
uint256 maxVoteWeight = BuoyERC20.balanceOf(msg.sender);
require(proposalActive == true, 'No active proposal');
require(propID <= proposalCount && propID >= proposalsVoted, 'Not a valid ID');
require(vote == 0 || vote == 1, 'Vote must be 0 or 1');
require(voteWeight > 0 && voteWeight <= maxVoteWeight, 'Vote weight not valid');
require(now >= proposal[propID].startDate && now <= proposal[propID].startDate+3 hours, 'Proposal not active');
BuoyERC20.transferFrom(msg.sender, address(this), voteWeight);
delegation[msg.sender] = Delegation(proposal[propID].startDate+3 hours,voteWeight);
if(vote == 0) {
proposal[propID].noVotes = proposal[propID].noVotes.badd(voteWeight);
} else {
proposal[propID].yesVotes = proposal[propID].yesVotes.badd(voteWeight);
}
}
function castVoteERC721(uint propID, uint vote, uint id) public {
IBuoy buoyERC721 = IBuoy(addressIndex.getXBuoy());
uint256 _voteWeight;
(,_voteWeight,,,,) = buoyERC721.viewNFT(id);
require(proposalActive == true, 'No active proposal');
require(vote == 0 || vote == 1, 'Vote must be 0 or 1');
require(now >= proposal[propID].startDate && now <= proposal[propID].startDate+3 hours, 'Proposal not active');
buoyERC721.safeTransferfrom(msg.sender, address(this), id);
delegation[msg.sender] = Delegation(proposal[propID].startDate+3 hours,_voteWeight);
if(vote == 0) {
proposal[propID].noVotes = proposal[propID].noVotes.badd(_voteWeight);
} else {
proposal[propID].yesVotes = proposal[propID].yesVotes.badd(_voteWeight);
}
}
function withdrawDelegation() public {
IERC20 BuoyERC20 = IERC20(addressIndex.getBuoy());
uint delegated = delegation[msg.sender].delegated;
require(delegated > 0, 'No tokens delegated');
require(now > delegation[msg.sender].withdrawDate, 'Too early');
delegation[msg.sender].delegated = 0;
BuoyERC20.transfer(msg.sender, delegated);
}
function endVote() public returns (bool) {
require(now > proposal[proposalsVoted].startDate+3 hours, 'No endable proposal');
bool passed;
address propAcc = proposal[proposalsVoted].proposer;
if(proposal[proposalsVoted].yesVotes > proposal[proposalsVoted].noVotes) {
passed = true;
enactProposal();
}
proposalActive = false;
proposers[propAcc] = false;
proposalsVoted++;
return passed;
}
function applyt() public {
SPool spool = SPool(addressIndex.getGovernanceProxy());
spool.applyAddToken();
}
function enactProposal() private {
//type 1 - change minimum delegation needed to make a proposal
if(proposal[proposalsVoted].proposaltype == 1) {
_setDelegationMinimum(proposal[proposalsVoted].value1);
} else
//type 2 - change the swap fee for the smart pool
if(proposal[proposalsVoted].proposaltype == 2) {
_setSwapFee(proposal[proposalsVoted].value1);
} else
//type 3 - change the Buoy ERC-20
if(proposal[proposalsVoted].proposaltype == 3) {
addressIndex.setBuoy(proposal[proposalsVoted].address1);
} else
//type 4 - change the Buoy ERC-721
if(proposal[proposalsVoted].proposaltype == 4) {
addressIndex.setXBuoy(proposal[proposalsVoted].address1);
} else
//type 5 - change the Balancer Smartpool
if(proposal[proposalsVoted].proposaltype == 5) {
addressIndex.setBalancer(proposal[proposalsVoted].address1);
} else
//type 6 - change the owner of the Balancer Smartpool
if(proposal[proposalsVoted].proposaltype == 6) {
SPool spool = SPool(addressIndex.getBalancer());
spool.changeOwner(proposal[proposalsVoted].address1);
} else
//type 7 - de or re activate staking
if(proposal[proposalsVoted].proposaltype == 7) {
Mine mine = Mine(addressIndex.getMine());
mine.setStakingActive(proposal[proposalsVoted].bool1);
} else
//type 8 - de or re activate trades in the Smartpool
if(proposal[proposalsVoted].proposaltype == 8) {
Mine mine = Mine(addressIndex.getMine());
mine.setSwapingActive(proposal[proposalsVoted].bool1);
} else
//type 9 - change the staking maxs for each period
if(proposal[proposalsVoted].proposaltype == 9) {
Mine mine = Mine(addressIndex.getMine());
mine.changeStakingMax(proposal[proposalsVoted].array1);
} else
//type 10 - change the share given by each period
if(proposal[proposalsVoted].proposaltype == 10) {
Mine mine = Mine(addressIndex.getMine());
mine.changeStakingShare(proposal[proposalsVoted].array1);
}
//type 11 - change the weights of each token
if(proposal[proposalsVoted].proposaltype == 11) {
SPool spool = SPool(addressIndex.getBalancer());
spool.changeWeight(proposal[proposalsVoted].array1);
}
//type 12 - add a new token to the pool
if(proposal[proposalsVoted].proposaltype == 12) {
SPool spool = SPool(addressIndex.getBalancer());
spool.proposeAddToken(proposal[proposalsVoted].address1, proposal[proposalsVoted].value1, proposal[proposalsVoted].value2);
}
//type 13 - add a new token to the pool
if(proposal[proposalsVoted].proposaltype == 13) {
require(proposal[proposalsVoted].address1 != addressIndex.getBalancer());
SPool spool = SPool(addressIndex.getBalancer());
spool.removeToken(proposal[proposalsVoted].address1);
}
}
function viewProposal(uint id) public view returns(uint,
uint,
uint,
address,
uint,
uint,
address,
bool,
uint [] memory,
uint,
uint) {
Proposal memory prop = proposal[id];
return(prop.proposaltype,
prop.creationDate,
prop.startDate,
prop.proposer,
prop.value1,
prop.value2,
prop.address1,
prop.bool1,
prop.array1,
prop.yesVotes,
prop.noVotes);
}
function viewDelgated(address a) public view returns(uint,uint) {
return(delegation[a].withdrawDate,delegation[a].delegated);
}
function viewMyDelgated() public view returns(uint,uint) {
return(delegation[msg.sender].withdrawDate,delegation[msg.sender].delegated);
}
} | contract GovernanceProxy {
using BalancerSafeMath for uint256;
uint256 public lastProposed;
uint256 public proposalCount; //used to assign a unique ID to each proposal
uint256 public proposalsVoted; //used to keep track of which proposals have been decided on
uint256 proposalDelegationMinimum = 500; //should be adjustable
bool public proposalActive;
mapping (address => Delegation) delegation;
mapping (address => bool) proposers;
mapping (uint => Proposal) proposal;
struct Delegation {
uint withdrawDate;
uint delegated;
}
struct Proposal {
uint proposaltype;
uint creationDate;
uint startDate;
address proposer;
uint value1;
uint value2;
address address1;
bool bool1;
uint[] array1;
uint yesVotes;
uint noVotes;
}
IAddressIndex addressIndex;
constructor() public {
addressIndex = IAddressIndex(0x75843DB21C59Ca36e0c581da91F255883AfD3009);
}
//=======================enactable functions======================//
function _setSwapFee(uint _swapFee) private {
IBPool ibpool = IBPool(addressIndex.getBalancer());
ibpool.setSwapFee(_swapFee);
}
function _setDelegationMinimum(uint a) private {
proposalDelegationMinimum = a;
}
//========================vote functions=============================//
function newProposal(uint kind, uint _value1, uint _value2, address _address1, bool _bool1, uint[] calldata _array1) public payable {
//set it to require a delegation of 1% of the tokens
IERC20 buoyERC20 = IERC20(addressIndex.getBuoy());
require(buoyERC20.balanceOf(msg.sender) >= proposalDelegationMinimum, "Address has an active proposal already");
require(proposers[msg.sender] == false, "Address has an active proposal already");
buoyERC20.transferFrom(msg.sender, address(this), proposalDelegationMinimum);
proposalActive = true;
uint creationDate = now;
uint startDate;
if(lastProposed > (creationDate - 1 hours) && lastProposed != 0) {
startDate = lastProposed + 1 hours;
} else {
startDate = creationDate;
}
delegation[msg.sender] = Delegation(startDate+3 hours,proposalDelegationMinimum);
proposal[proposalCount] = Proposal(kind, creationDate, startDate, msg.sender, _value1, _value2, _address1, _bool1, _array1, 0, 0);
proposers[msg.sender] = true;
proposalCount++;
lastProposed = startDate;
}
// 0 = no, 1 = yes. voteWeight is measured in wei. approvals must be made before you can delegate
function castVoteERC20(uint propID, uint vote, uint voteWeight) public {
IERC20 BuoyERC20 = IERC20(addressIndex.getBuoy());
uint256 maxVoteWeight = BuoyERC20.balanceOf(msg.sender);
require(proposalActive == true, 'No active proposal');
require(propID <= proposalCount && propID >= proposalsVoted, 'Not a valid ID');
require(vote == 0 || vote == 1, 'Vote must be 0 or 1');
require(voteWeight > 0 && voteWeight <= maxVoteWeight, 'Vote weight not valid');
require(now >= proposal[propID].startDate && now <= proposal[propID].startDate+3 hours, 'Proposal not active');
BuoyERC20.transferFrom(msg.sender, address(this), voteWeight);
delegation[msg.sender] = Delegation(proposal[propID].startDate+3 hours,voteWeight);
if(vote == 0) {
proposal[propID].noVotes = proposal[propID].noVotes.badd(voteWeight);
} else {
proposal[propID].yesVotes = proposal[propID].yesVotes.badd(voteWeight);
}
}
function castVoteERC721(uint propID, uint vote, uint id) public {
IBuoy buoyERC721 = IBuoy(addressIndex.getXBuoy());
uint256 _voteWeight;
(,_voteWeight,,,,) = buoyERC721.viewNFT(id);
require(proposalActive == true, 'No active proposal');
require(vote == 0 || vote == 1, 'Vote must be 0 or 1');
require(now >= proposal[propID].startDate && now <= proposal[propID].startDate+3 hours, 'Proposal not active');
buoyERC721.safeTransferfrom(msg.sender, address(this), id);
delegation[msg.sender] = Delegation(proposal[propID].startDate+3 hours,_voteWeight);
if(vote == 0) {
proposal[propID].noVotes = proposal[propID].noVotes.badd(_voteWeight);
} else {
proposal[propID].yesVotes = proposal[propID].yesVotes.badd(_voteWeight);
}
}
function withdrawDelegation() public {
IERC20 BuoyERC20 = IERC20(addressIndex.getBuoy());
uint delegated = delegation[msg.sender].delegated;
require(delegated > 0, 'No tokens delegated');
require(now > delegation[msg.sender].withdrawDate, 'Too early');
delegation[msg.sender].delegated = 0;
BuoyERC20.transfer(msg.sender, delegated);
}
function endVote() public returns (bool) {
require(now > proposal[proposalsVoted].startDate+3 hours, 'No endable proposal');
bool passed;
address propAcc = proposal[proposalsVoted].proposer;
if(proposal[proposalsVoted].yesVotes > proposal[proposalsVoted].noVotes) {
passed = true;
enactProposal();
}
proposalActive = false;
proposers[propAcc] = false;
proposalsVoted++;
return passed;
}
function applyt() public {
SPool spool = SPool(addressIndex.getGovernanceProxy());
spool.applyAddToken();
}
function enactProposal() private {
//type 1 - change minimum delegation needed to make a proposal
if(proposal[proposalsVoted].proposaltype == 1) {
_setDelegationMinimum(proposal[proposalsVoted].value1);
} else
//type 2 - change the swap fee for the smart pool
if(proposal[proposalsVoted].proposaltype == 2) {
_setSwapFee(proposal[proposalsVoted].value1);
} else
//type 3 - change the Buoy ERC-20
if(proposal[proposalsVoted].proposaltype == 3) {
addressIndex.setBuoy(proposal[proposalsVoted].address1);
} else
//type 4 - change the Buoy ERC-721
if(proposal[proposalsVoted].proposaltype == 4) {
addressIndex.setXBuoy(proposal[proposalsVoted].address1);
} else
//type 5 - change the Balancer Smartpool
if(proposal[proposalsVoted].proposaltype == 5) {
addressIndex.setBalancer(proposal[proposalsVoted].address1);
} else
//type 6 - change the owner of the Balancer Smartpool
if(proposal[proposalsVoted].proposaltype == 6) {
SPool spool = SPool(addressIndex.getBalancer());
spool.changeOwner(proposal[proposalsVoted].address1);
} else
//type 7 - de or re activate staking
if(proposal[proposalsVoted].proposaltype == 7) {
Mine mine = Mine(addressIndex.getMine());
mine.setStakingActive(proposal[proposalsVoted].bool1);
} else
//type 8 - de or re activate trades in the Smartpool
if(proposal[proposalsVoted].proposaltype == 8) {
Mine mine = Mine(addressIndex.getMine());
mine.setSwapingActive(proposal[proposalsVoted].bool1);
} else
//type 9 - change the staking maxs for each period
if(proposal[proposalsVoted].proposaltype == 9) {
Mine mine = Mine(addressIndex.getMine());
mine.changeStakingMax(proposal[proposalsVoted].array1);
} else
//type 10 - change the share given by each period
if(proposal[proposalsVoted].proposaltype == 10) {
Mine mine = Mine(addressIndex.getMine());
mine.changeStakingShare(proposal[proposalsVoted].array1);
}
//type 11 - change the weights of each token
if(proposal[proposalsVoted].proposaltype == 11) {
SPool spool = SPool(addressIndex.getBalancer());
spool.changeWeight(proposal[proposalsVoted].array1);
}
//type 12 - add a new token to the pool
if(proposal[proposalsVoted].proposaltype == 12) {
SPool spool = SPool(addressIndex.getBalancer());
spool.proposeAddToken(proposal[proposalsVoted].address1, proposal[proposalsVoted].value1, proposal[proposalsVoted].value2);
}
//type 13 - add a new token to the pool
if(proposal[proposalsVoted].proposaltype == 13) {
require(proposal[proposalsVoted].address1 != addressIndex.getBalancer());
SPool spool = SPool(addressIndex.getBalancer());
spool.removeToken(proposal[proposalsVoted].address1);
}
}
function viewProposal(uint id) public view returns(uint,
uint,
uint,
address,
uint,
uint,
address,
bool,
uint [] memory,
uint,
uint) {
Proposal memory prop = proposal[id];
return(prop.proposaltype,
prop.creationDate,
prop.startDate,
prop.proposer,
prop.value1,
prop.value2,
prop.address1,
prop.bool1,
prop.array1,
prop.yesVotes,
prop.noVotes);
}
function viewDelgated(address a) public view returns(uint,uint) {
return(delegation[a].withdrawDate,delegation[a].delegated);
}
function viewMyDelgated() public view returns(uint,uint) {
return(delegation[msg.sender].withdrawDate,delegation[msg.sender].delegated);
}
} | 9,236 |
3 | // pay outstanding interest to lender | _payInterest(
msg.sender, // lender
loanToken
);
| _payInterest(
msg.sender, // lender
loanToken
);
| 36,518 |
68 | // executes a function on the ERC20 token and reverts upon failure the main purpose of this function is to prevent a non standard ERC20 token from failing silently_token ERC20 token address_datadata to pass in to the token's contract for execution/ | function execute(IERC20Token _token, bytes memory _data) private {
uint256[1] memory ret = [uint256(1)];
assembly {
let success := call(
gas, // gas remaining
_token, // destination address
0, // no ether
add(_data, 32), // input buffer (starts after the first 32 bytes in the `data` array)
mload(_data), // input length (loaded from the first 32 bytes in the `data` array)
ret, // output buffer
32 // output length
)
if iszero(success) {
revert(0, 0)
}
}
require(ret[0] != 0, "ERR_TRANSFER_FAILED");
}
| function execute(IERC20Token _token, bytes memory _data) private {
uint256[1] memory ret = [uint256(1)];
assembly {
let success := call(
gas, // gas remaining
_token, // destination address
0, // no ether
add(_data, 32), // input buffer (starts after the first 32 bytes in the `data` array)
mload(_data), // input length (loaded from the first 32 bytes in the `data` array)
ret, // output buffer
32 // output length
)
if iszero(success) {
revert(0, 0)
}
}
require(ret[0] != 0, "ERR_TRANSFER_FAILED");
}
| 1,554 |
4 | // Creates an RLPItem from an array of RLP encoded bytes./self The RLP encoded bytes./strict Will revert() if the data is not RLP encoded./ return An RLPItem | function toRLPItem(bytes memory self, bool strict) internal pure returns (RLPLib.RLPItem memory) {
RLPLib.RLPItem memory item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
revert();
if(_itemLength(item._unsafe_memPtr) != len)
revert();
if(!_validate(item))
revert();
}
return item;
}
| function toRLPItem(bytes memory self, bool strict) internal pure returns (RLPLib.RLPItem memory) {
RLPLib.RLPItem memory item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
revert();
if(_itemLength(item._unsafe_memPtr) != len)
revert();
if(!_validate(item))
revert();
}
return item;
}
| 9,468 |
76 | // Address where funds are collected | address payable private _wallet;
address private admin;
| address payable private _wallet;
address private admin;
| 5,558 |
34 | // Convert Tokens (token) to Tokens (exchange_addr.token). Allows trades through contracts that were not deployed from the same factory. User specifies exact input && minimum output. tokens_sold Amount of Tokens sold. min_tokens_bought Minimum Tokens (token_addr) purchased. min_trx_bought Minimum TRX purchased as intermediary. deadline Time after which this transaction can no longer be executed. exchange_addr The address of the exchange for the token being purchased.return Amount of Tokens (exchange_addr.token) bought. / | function tokenToExchangeSwapInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_trx_bought,
uint256 deadline,
address payable exchange_addr)
public returns (uint256)
| function tokenToExchangeSwapInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_trx_bought,
uint256 deadline,
address payable exchange_addr)
public returns (uint256)
| 54,069 |
11 | // BasicToken Basic version of Token, with no allowances. / | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* BasicToken transfer function
* @dev transfer token for a specified address
* @param _to address to transfer to.
* @param _value amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
//Safemath fnctions will throw if value is invalid
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* BasicToken balanceOf function
* @dev Gets the balance of the specified address.
* @param _owner address to get balance of.
* @return uint256 amount owned by the address.
*/
function balanceOf(address _owner) public constant returns (uint256 bal) {
return balances[_owner];
}
}
| contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* BasicToken transfer function
* @dev transfer token for a specified address
* @param _to address to transfer to.
* @param _value amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
//Safemath fnctions will throw if value is invalid
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* BasicToken balanceOf function
* @dev Gets the balance of the specified address.
* @param _owner address to get balance of.
* @return uint256 amount owned by the address.
*/
function balanceOf(address _owner) public constant returns (uint256 bal) {
return balances[_owner];
}
}
| 39,932 |
52 | // Sets a new comptroller for the market Admin function to set a new comptrollerreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function _setComptroller(ComptrollerInterface newComptroller)
public
override
returns (uint256)
| function _setComptroller(ComptrollerInterface newComptroller)
public
override
returns (uint256)
| 14,910 |
162 | // Voken reserved. | Allocations.Allocation memory __allocation = __allocations[i];
__reserved = __reserved.add(__allocation.amount);
if (now >= __allocation.timestamp.add(90 days)) {
| Allocations.Allocation memory __allocation = __allocations[i];
__reserved = __reserved.add(__allocation.amount);
if (now >= __allocation.timestamp.add(90 days)) {
| 46,827 |
606 | // Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped) | withdrawal.minGas = 0;
| withdrawal.minGas = 0;
| 32,405 |
160 | // This is a basic function to read price, although this is a public function,It is not recommended, the recommended function is `assetPrices(asset)`.If `asset` does not has a reader to reader price, then read price from originalstructure `_assetPrices`;If `asset` has a reader to read price, first gets the price of reader, then`readerPrice10|(18-assetDecimals)|` Get price of `asset`. _asset Asset for which to get the price.return Uint mantissa of asset price (scaled by 1e18) or zero if unset. / | function _getReaderPrice(address _asset) internal view returns (uint256) {
Reader storage reader = readers[_asset];
if (reader.asset == address(0)) return _assetPrices[_asset].mantissa;
uint256 readerPrice = _assetPrices[reader.asset].mantissa;
if (reader.decimalsDifference < 0)
return
srcMul(
readerPrice,
pow(10, uint256(0 - reader.decimalsDifference))
);
return srcDiv(readerPrice, pow(10, uint256(reader.decimalsDifference)));
}
| function _getReaderPrice(address _asset) internal view returns (uint256) {
Reader storage reader = readers[_asset];
if (reader.asset == address(0)) return _assetPrices[_asset].mantissa;
uint256 readerPrice = _assetPrices[reader.asset].mantissa;
if (reader.decimalsDifference < 0)
return
srcMul(
readerPrice,
pow(10, uint256(0 - reader.decimalsDifference))
);
return srcDiv(readerPrice, pow(10, uint256(reader.decimalsDifference)));
}
| 17,834 |
84 | // Gets total amount of deposits that has left after users&39; bonus withdrawals/ return amount of deposits available for bonus payments | function getTotalDepositsAmountLeft() public view returns (uint _amount) {
uint _lastDepositDate = lastDepositDate;
for (
uint _startDate = firstDepositDate;
_startDate <= _lastDepositDate || _startDate != 0;
_startDate = distributionDeposits[_startDate].nextDepositDate
) {
_amount = _amount.add(distributionDeposits[_startDate].left);
}
}
| function getTotalDepositsAmountLeft() public view returns (uint _amount) {
uint _lastDepositDate = lastDepositDate;
for (
uint _startDate = firstDepositDate;
_startDate <= _lastDepositDate || _startDate != 0;
_startDate = distributionDeposits[_startDate].nextDepositDate
) {
_amount = _amount.add(distributionDeposits[_startDate].left);
}
}
| 7,291 |
3 | // @inheritdoc ITransferStrategyBase | function getIncentivesController() external view override returns (address) {
return INCENTIVES_CONTROLLER;
}
| function getIncentivesController() external view override returns (address) {
return INCENTIVES_CONTROLLER;
}
| 31,600 |
7 | // verifyClaim(_dropMsgSender(), _quantity, _currency, _pricePerToken, _allowlistProof); |
bool verified = BTVerifyClaim(_receiver,proof, root);
if(!verified) {
revert("not in allowlist");
}
|
bool verified = BTVerifyClaim(_receiver,proof, root);
if(!verified) {
revert("not in allowlist");
}
| 31,506 |
40 | // its goal is to return the total number of DAppNode packages/ return the total number of DAppNode packages | function numberOfDAppNodePackages() view public returns (uint) {
return DAppNodePackages.length;
}
| function numberOfDAppNodePackages() view public returns (uint) {
return DAppNodePackages.length;
}
| 77,320 |
24 | // ERC20 interface / | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| 13,146 |
36 | // (oracleCosttotalTweSupply) / (denominatorlinkBalance) | (uint oracleCost, ) = oracleCost();
return (oracleCost.wadMul(totalSupply())).wadDiv(tweetherDenominator.wadMul(linkBalance()));
| (uint oracleCost, ) = oracleCost();
return (oracleCost.wadMul(totalSupply())).wadDiv(tweetherDenominator.wadMul(linkBalance()));
| 3,209 |
30 | // Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),reverting with custom message when dividing by zero. CAUTION: This function is deprecated because it requires allocating memory for the error | * message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
| * message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
| 1,787 |
15 | // Checks if everyone is allowed to participate after delay. / | function isEveryoneAllowedToParticipateAfterDelay() public view returns (bool) {
return _isEveryoneAllowedToParticipateAfterDelay;
}
| function isEveryoneAllowedToParticipateAfterDelay() public view returns (bool) {
return _isEveryoneAllowedToParticipateAfterDelay;
}
| 51,491 |
6 | // return the time when the tokens are released. / | function releaseTime() public view returns (uint256) {
return _releaseTime;
}
| function releaseTime() public view returns (uint256) {
return _releaseTime;
}
| 23,925 |
6 | // Retrieve the tokens | lpToken.transferFrom(msg.sender, address(this), balance);
| lpToken.transferFrom(msg.sender, address(this), balance);
| 5,405 |
20 | // Get underlying tokens | for (uint8 i = 0; i < 8; i++) {
try
MetaSwapDeposit(inputData.metaSwapDepositAddress).getToken(
i
)
returns (IERC20 token) {
require(address(token) != address(0), "PR: token is 0");
underlyingTokens[i] = token;
| for (uint8 i = 0; i < 8; i++) {
try
MetaSwapDeposit(inputData.metaSwapDepositAddress).getToken(
i
)
returns (IERC20 token) {
require(address(token) != address(0), "PR: token is 0");
underlyingTokens[i] = token;
| 15,484 |
33 | // LXL `client` or `clientOracle` can release milestone `amount` to `provider`.registration Registered LXL number. / | function release(uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
uint256 milestone = locker.currentMilestone-1;
uint256 payment = locker.amount[milestone];
uint256 released = locker.released;
uint256 sum = locker.sum;
require(_msgSender() == locker.client || _msgSender() == locker.clientOracle, "!client/oracle");
require(locker.confirmed == 1, "!confirmed");
require(locker.locked == 0, "locked");
require(released < sum, "released");
IERC20(locker.token).safeTransfer(locker.provider, payment);
locker.released = released.add(payment);
if (locker.released < sum) {locker.currentMilestone++;}
emit Release(milestone+1, payment, registration);
}
| function release(uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
uint256 milestone = locker.currentMilestone-1;
uint256 payment = locker.amount[milestone];
uint256 released = locker.released;
uint256 sum = locker.sum;
require(_msgSender() == locker.client || _msgSender() == locker.clientOracle, "!client/oracle");
require(locker.confirmed == 1, "!confirmed");
require(locker.locked == 0, "locked");
require(released < sum, "released");
IERC20(locker.token).safeTransfer(locker.provider, payment);
locker.released = released.add(payment);
if (locker.released < sum) {locker.currentMilestone++;}
emit Release(milestone+1, payment, registration);
}
| 7,632 |
5 | // Notice period before activation preparation status of upgrade mode | function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
| function getNoticePeriod() external pure override returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
| 10,994 |
58 | // len < = length(tokenList) + 1 | require(len == tokenList.length + 1, "Nest: Pool: !assetsList");
uint256[] memory list = new uint256[](len);
list[0] = _eth_ledger[address(msg.sender)];
for (uint i = 0; i < len - 1; i++) {
address _token = tokenList[i];
list[i+1] = _token_ledger[_token][address(msg.sender)];
}
| require(len == tokenList.length + 1, "Nest: Pool: !assetsList");
uint256[] memory list = new uint256[](len);
list[0] = _eth_ledger[address(msg.sender)];
for (uint i = 0; i < len - 1; i++) {
address _token = tokenList[i];
list[i+1] = _token_ledger[_token][address(msg.sender)];
}
| 24,586 |
5 | // 每一期的购买人地址信息 期数=》地址 | mapping(uint256 => address[]) lotteryPlayers;
| mapping(uint256 => address[]) lotteryPlayers;
| 35,296 |
125 | // Migrate the deed | Entry storage h = _entries[_hash];
h.deed.setRegistrar(registrar);
| Entry storage h = _entries[_hash];
h.deed.setRegistrar(registrar);
| 34,018 |
527 | // Round up to ensure the maker's exchange rate does not exceed the price specified by the order. We favor the maker when the exchange rate must be rounded. | matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
| matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
| 2,495 |
97 | // Gets the queue element at a particular index. _index Index of the queue element to access.return _element Queue element at the given index. / | function getQueueElement(
| function getQueueElement(
| 6,227 |
2 | // Add rewards for Nest-Nodes, only governance or NestMining (contract) are allowed/ The rewards need to pull from NestPool/_amount The amount of Nest token as the rewards to each nest-node | function addNNReward(uint256 _amount) external;
| function addNNReward(uint256 _amount) external;
| 24,589 |
131 | // Registers a potential new internal token in the bank Can not be a reserved token or an available token token The address of the token / | function registerPotentialNewInternalToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_INTERNAL_TOKEN)
| function registerPotentialNewInternalToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_INTERNAL_TOKEN)
| 63,461 |
169 | // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC has 8, so the multiplier should be 1018 / 108 => 1010 | uint256[] tokenPrecisionMultipliers;
| uint256[] tokenPrecisionMultipliers;
| 17,336 |
18 | // GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids https:github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol | address public immutable GNOSIS_EASY_AUCTION;
| address public immutable GNOSIS_EASY_AUCTION;
| 45,357 |
93 | // Unlocks WETH amount from the CDP | frob(manager, cdp, -toInt(wad), 0);
| frob(manager, cdp, -toInt(wad), 0);
| 51,173 |
165 | // Max amount of token to Gift per time/ | uint public MAX_GIFT;
| uint public MAX_GIFT;
| 18,873 |
165 | // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and then delete the last slot (swap and pop). |
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
|
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
| 17,932 |
80 | // Tells the address that generated the message on the other network that is currently being executed by the AMB bridge. return the address of the message sender./ | function messageSender() internal view returns (address) {
return bridgeContract().messageSender();
}
| function messageSender() internal view returns (address) {
return bridgeContract().messageSender();
}
| 51,492 |
14 | // 2.2.2) add new shares to the shares mapping and the finalShares array | uint256 newShareIdA = shareCount;
shareCount++;
uint256 newShareIdB = shareCount;
shareCount++;
finalShares.push(newShareIdA);
finalShares.push(newShareIdB);
shares[newShareIdA] = Share(participantA, finalSharePercentageA, parentShareId, true);
shares[newShareIdB] = Share(participantB, finalSharePercentageB, parentShareId, true);
| uint256 newShareIdA = shareCount;
shareCount++;
uint256 newShareIdB = shareCount;
shareCount++;
finalShares.push(newShareIdA);
finalShares.push(newShareIdB);
shares[newShareIdA] = Share(participantA, finalSharePercentageA, parentShareId, true);
shares[newShareIdB] = Share(participantB, finalSharePercentageB, parentShareId, true);
| 21,851 |
97 | // All joins are disabled while the contract is paused. |
uint256[] memory normalizedWeights = _normalizedWeights();
|
uint256[] memory normalizedWeights = _normalizedWeights();
| 10,613 |
8 | // payout for the deposit = amount / price wherepayout = FLOOR outamount = quote tokens inprice = quote tokens : floor (i.e. 42069 DAI : FLOOR) 1e18 = FLOOR decimals (9) + price decimals (9) / | payout_ = (_amount * 1e18 / price) / (10 ** metadata[_id].quoteDecimals);
| payout_ = (_amount * 1e18 / price) / (10 ** metadata[_id].quoteDecimals);
| 33,340 |
153 | // Sets a sender address of the failed message that came from the other side._messageId id of the message from the other side that triggered a call._receiver address of the receiver./ | function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal {
addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver;
}
| function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal {
addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver;
}
| 43,442 |
30 | // Converts a `uint256` to its ASCII `string` hexadecimal representation. / | function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
| function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
| 152 |
60 | // Update operator status | operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
| operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
| 14,041 |
28 | // add recipients | if (_recipientAddresses.length > 0) {
addRecipients(campaignId, _recipientAddresses);
}
| if (_recipientAddresses.length > 0) {
addRecipients(campaignId, _recipientAddresses);
}
| 16,780 |
55 | // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. | _balances[account] += amount;
| _balances[account] += amount;
| 37,296 |
1,528 | // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, this is the voting round where this price will be voted on, but not necessarily resolved. | uint256 lastVotingRound;
| uint256 lastVotingRound;
| 17,872 |
184 | // Enters the Compound market so it can be deposited/borrowed/_cTokenAddr CToken address of the token | function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
| function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
| 13,488 |
96 | // // | function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) {
(amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0);
}
| function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) {
(amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0);
}
| 51,682 |
86 | // owners between swapped slots should't be renumbered - that saves a lot of gas | m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
| m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
| 41,336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.