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
|
---|---|---|---|---|
6 | // Restricts a function to only being called by the RenExSettlement/ contract. | modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
| modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
| 10,886 |
1 | // Maps the implementation to the hash of all its selectors implementation => keccak256(abi.encode(selectors)) | mapping(address => bytes32) selectorsHash;
| mapping(address => bytes32) selectorsHash;
| 17,572 |
113 | // Allows owner to change the treasury address. Treasury is the address where all funds from sale go totreasury New treasury address/ | function adminSetTreasury(address treasury) external onlyOwner {
_treasury = treasury;
}
| function adminSetTreasury(address treasury) external onlyOwner {
_treasury = treasury;
}
| 23,507 |
106 | // These functions deal with verification of Merkle Trees proofs. The proofs can be generated using the JavaScript libraryNote: the hashing algorithm should be keccak256 and pair sorting should be enabled. See `test/utils/cryptography/MerkleProof.test.js` for some examples. / | library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
| library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
| 13,489 |
2 | // The admin of the wallet; the only address that is a valid `msg.sender` in this contract. | address public controller;
| address public controller;
| 17,013 |
235 | // Updates listingHash to store most recent challenge | listing.challengeID = pollID;
| listing.challengeID = pollID;
| 41,203 |
37 | // Note: calling `_projectUnlocked` enforces that the `_projectId` passed in is valid.` | require(_projectUnlocked(_projectId), "Only if unlocked");
| require(_projectUnlocked(_projectId), "Only if unlocked");
| 20,258 |
10 | // Use Base tokens held by this contract to buy from the Elite Pool and sell in the Base Pool | function balancePriceElite(uint256 amount, uint256 minAmountOut) public override seniorVaultManagerOnly()
| function balancePriceElite(uint256 amount, uint256 minAmountOut) public override seniorVaultManagerOnly()
| 60,228 |
26 | // contracts are not allowed to participate / | require(tx.origin == msg.sender && msg.value >= priceWei);
| require(tx.origin == msg.sender && msg.value >= priceWei);
| 48,736 |
68 | // Transfer ETH to the designated address. | receiver.transfer(boughtBuyAmt);
emit Swap(
msg.sender,
address(0),
boughtBuyAmt,
sellToken,
sellAmt,
receiver
);
| receiver.transfer(boughtBuyAmt);
emit Swap(
msg.sender,
address(0),
boughtBuyAmt,
sellToken,
sellAmt,
receiver
);
| 5,749 |
4 | // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. | function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
| function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external;
| 6,275 |
64 | // Token Tax // Events / | constructor() ERC20('Hunt DAO', 'HUNT') payable {
_totalSupply = 80000000000000000000000000000;
addToWhitelist('from', address(this));
addToWhitelist('to', address(this));
addToWhitelist('from', msg.sender);
_mint(msg.sender, _totalSupply);
}
| constructor() ERC20('Hunt DAO', 'HUNT') payable {
_totalSupply = 80000000000000000000000000000;
addToWhitelist('from', address(this));
addToWhitelist('to', address(this));
addToWhitelist('from', msg.sender);
_mint(msg.sender, _totalSupply);
}
| 56,409 |
24 | // Show the type of the reason | function show_reason () pure public returns(string) {
return "Type-1: Wrong key || Type-2: Messy watermark || Type-3: Two or more watermarks";
}
| function show_reason () pure public returns(string) {
return "Type-1: Wrong key || Type-2: Messy watermark || Type-3: Two or more watermarks";
}
| 19,957 |
12 | // If offer is active check if the amount is bigger than the current offer. | if (amount == 0) {
break;
} else if (amount >= offer.amount) {
| if (amount == 0) {
break;
} else if (amount >= offer.amount) {
| 19,102 |
2 | // Commitment token address | Token public token;
| Token public token;
| 31,020 |
18 | // ---------------------------------------------------------------------------- ERC Token Standard 20 Interface ---------------------------------------------------------------------------- | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function allowance(address tokenOwner, address spender) external view returns (uint256 remaining);
function transfer(address to, uint256 tokens) external returns (bool success);
function approve(address spender, uint256 tokens) external returns (bool success);
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
function burnTokens(uint256 _amount) external;
function calculateFees(
address sender,
address recipient,
uint256 amount
) external view returns (uint256, uint256);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
| interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function allowance(address tokenOwner, address spender) external view returns (uint256 remaining);
function transfer(address to, uint256 tokens) external returns (bool success);
function approve(address spender, uint256 tokens) external returns (bool success);
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
function burnTokens(uint256 _amount) external;
function calculateFees(
address sender,
address recipient,
uint256 amount
) external view returns (uint256, uint256);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
| 3,785 |
13 | // mint the token to target address | if ( quantity > 4) {
for (uint256 i = 0; i < quantity; i++) {
_safeMint(_address, 1);
}
| if ( quantity > 4) {
for (uint256 i = 0; i < quantity; i++) {
_safeMint(_address, 1);
}
| 36,298 |
0 | // Mapping storing how much is spent in each block Note - There's minor stability and griefing considerations around tracking the expenditureper block for all spend limits. Namely two proposals may try to get executed in the same block and have onefail on accident or on purpose. These are for semi-rare non contentious spending sowe do not consider either a major concern. | mapping(uint256 => uint256) public blockExpenditure;
| mapping(uint256 => uint256) public blockExpenditure;
| 76,157 |
106 | // NOTE: solidity 0.4.x does not support STATICCALL outside of assembly | assembly {
let success := staticcall( // perform a staticcall
gas, // forward all available gas
orderMaker, // call the order maker
add(isValidSignatureData, 0x20), // calldata offset comes after length
mload(isValidSignatureData), // load calldata length
0, // do not use memory for return data
0 // do not use memory for return data
)
if iszero(success) { // if the call fails
returndatacopy(0, 0, returndatasize) // copy returndata buffer to memory
revert(0, returndatasize) // revert + pass through revert data
}
if eq(returndatasize, 0x20) { // if returndata == 32 (one word)
returndatacopy(0, 0, 0x20) // copy return data to memory in scratch space
result := mload(0) // load return data from memory to the stack
}
}
| assembly {
let success := staticcall( // perform a staticcall
gas, // forward all available gas
orderMaker, // call the order maker
add(isValidSignatureData, 0x20), // calldata offset comes after length
mload(isValidSignatureData), // load calldata length
0, // do not use memory for return data
0 // do not use memory for return data
)
if iszero(success) { // if the call fails
returndatacopy(0, 0, returndatasize) // copy returndata buffer to memory
revert(0, returndatasize) // revert + pass through revert data
}
if eq(returndatasize, 0x20) { // if returndata == 32 (one word)
returndatacopy(0, 0, 0x20) // copy return data to memory in scratch space
result := mload(0) // load return data from memory to the stack
}
}
| 39,863 |
6 | // Force the recipient to not be set, otherwise wrapped token refunded will besent to the user and we won't be able to unwrap it. | require(
obj.recipient == address(0x0) || obj.recipient == address(this),
"WrapAndBSwap#wrapAndSwap: ORDER RECIPIENT MUST BE THIS CONTRACT"
);
| require(
obj.recipient == address(0x0) || obj.recipient == address(this),
"WrapAndBSwap#wrapAndSwap: ORDER RECIPIENT MUST BE THIS CONTRACT"
);
| 3,004 |
19 | // `proxyPayment()` allows the caller to send ether to the Campaign/ and have the tokens created in an address of their choosing/_owner The address that will hold the newly created tokens | function proxyPayment(address _owner) payable returns(bool);
| function proxyPayment(address _owner) payable returns(bool);
| 25,600 |
135 | // Mutable and removable. | function addStrategy(uint256 _key, address _strategy) external onlyOwner {
isStrategy[_strategy] = true;
strategyByKey[_key] = _strategy;
}
| function addStrategy(uint256 _key, address _strategy) external onlyOwner {
isStrategy[_strategy] = true;
strategyByKey[_key] = _strategy;
}
| 383 |
12 | // CreatureCreature - a contract for my non-fungible creatures. / | contract Creature is ERC721Tradable {
enum ClaimStatus { CLAIMABLE, CLAIM_REQUESTED, DELIVERED, UNCLAIMABLE }
bool public publicMintingStarted = false;
mapping(uint256 => ClaimStatus) private claimStatuses;
mapping(string => uint256) public names;
event PhysicalBadgeRequested(uint256 tokenId, bytes32 requestHash);
event PhysicalBadgeDelivered(uint256 tokenId);
constructor(address _proxyRegistryAddress)
ERC721Tradable("LivinTheMeme", "LTM", _proxyRegistryAddress)
{}
function baseTokenURI() override public pure returns (string memory) {
return "https://creatures-api.opensea.io/api/creature/";
}
function contractURI() public pure returns (string memory) {
return "https://creatures-api.opensea.io/contract/opensea-creatures";
}
function mintPremiumBadge(address _to, string memory _name) public onlyOwner {
uint256 tokenId = _mintBadge(_to, _name);
claimStatuses[tokenId] = ClaimStatus.CLAIMABLE;
}
function registerBadge(address _to, string memory _name, bytes memory _signature) public virtual {
require(publicMintingStarted, "badge registration has not started");
require(checkSignature(_name, _signature), "the name must be signed by the contract owner");
uint256 tokenId = _mintBadge(_to, _name);
claimStatuses[tokenId] = ClaimStatus.UNCLAIMABLE;
}
function _mintBadge(address _to, string memory _name) private returns (uint256 tokenId){
require(names[_name] == 0, "Name must be unique");
uint256 currentTokenId = getNextTokenId();
super.mintTo(_to);
names[_name] = currentTokenId;
return currentTokenId;
}
function mintTo(address _to) public override onlyOwner {
revert('token minting requires a unique name');
}
function setPublicMinting(bool _publicMintingAllowed) public onlyOwner {
publicMintingStarted = _publicMintingAllowed;
}
function checkSignature(string memory _name, bytes memory _signature) private returns (bool) {
bytes32 messageHash = keccak256(abi.encodePacked(_name));
return recoverSigner(messageHash, _signature) == owner();
}
function recoverSigner(bytes32 _signedMessage, bytes memory _signature) private returns (address) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_signedMessage, v, r, s);
}
function splitSignature(bytes memory sig) private returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(sig.length == 65, "invalid signature length");
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
}
function registerPhysicalBadgeRequest(uint256 tokenId, bytes32 requestHash) public {
require(ownerOf(tokenId) == _msgSender(), "Only the token owner can claim");
require(claimStatuses[tokenId] == ClaimStatus.CLAIMABLE, "Already claimed");
claimStatuses[tokenId] = ClaimStatus.CLAIM_REQUESTED;
emit PhysicalBadgeRequested(tokenId, requestHash);
}
function sendPhysicalBadge(uint256 tokenId) public onlyOwner {
claimStatuses[tokenId] = ClaimStatus.DELIVERED;
emit PhysicalBadgeDelivered(tokenId);
}
}
| contract Creature is ERC721Tradable {
enum ClaimStatus { CLAIMABLE, CLAIM_REQUESTED, DELIVERED, UNCLAIMABLE }
bool public publicMintingStarted = false;
mapping(uint256 => ClaimStatus) private claimStatuses;
mapping(string => uint256) public names;
event PhysicalBadgeRequested(uint256 tokenId, bytes32 requestHash);
event PhysicalBadgeDelivered(uint256 tokenId);
constructor(address _proxyRegistryAddress)
ERC721Tradable("LivinTheMeme", "LTM", _proxyRegistryAddress)
{}
function baseTokenURI() override public pure returns (string memory) {
return "https://creatures-api.opensea.io/api/creature/";
}
function contractURI() public pure returns (string memory) {
return "https://creatures-api.opensea.io/contract/opensea-creatures";
}
function mintPremiumBadge(address _to, string memory _name) public onlyOwner {
uint256 tokenId = _mintBadge(_to, _name);
claimStatuses[tokenId] = ClaimStatus.CLAIMABLE;
}
function registerBadge(address _to, string memory _name, bytes memory _signature) public virtual {
require(publicMintingStarted, "badge registration has not started");
require(checkSignature(_name, _signature), "the name must be signed by the contract owner");
uint256 tokenId = _mintBadge(_to, _name);
claimStatuses[tokenId] = ClaimStatus.UNCLAIMABLE;
}
function _mintBadge(address _to, string memory _name) private returns (uint256 tokenId){
require(names[_name] == 0, "Name must be unique");
uint256 currentTokenId = getNextTokenId();
super.mintTo(_to);
names[_name] = currentTokenId;
return currentTokenId;
}
function mintTo(address _to) public override onlyOwner {
revert('token minting requires a unique name');
}
function setPublicMinting(bool _publicMintingAllowed) public onlyOwner {
publicMintingStarted = _publicMintingAllowed;
}
function checkSignature(string memory _name, bytes memory _signature) private returns (bool) {
bytes32 messageHash = keccak256(abi.encodePacked(_name));
return recoverSigner(messageHash, _signature) == owner();
}
function recoverSigner(bytes32 _signedMessage, bytes memory _signature) private returns (address) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_signedMessage, v, r, s);
}
function splitSignature(bytes memory sig) private returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(sig.length == 65, "invalid signature length");
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
}
function registerPhysicalBadgeRequest(uint256 tokenId, bytes32 requestHash) public {
require(ownerOf(tokenId) == _msgSender(), "Only the token owner can claim");
require(claimStatuses[tokenId] == ClaimStatus.CLAIMABLE, "Already claimed");
claimStatuses[tokenId] = ClaimStatus.CLAIM_REQUESTED;
emit PhysicalBadgeRequested(tokenId, requestHash);
}
function sendPhysicalBadge(uint256 tokenId) public onlyOwner {
claimStatuses[tokenId] = ClaimStatus.DELIVERED;
emit PhysicalBadgeDelivered(tokenId);
}
}
| 1,946 |
159 | // oods_coefficients[84]/ mload(add(context, 0x77a0)), res += c_85(f_17(x) - f_17(g^70z)) / (x - g^70z). |
res := add(
res,
mulmod(mulmod(/*(x - g^70 * z)^(-1)*/ mload(add(denominatorsPtr, 0x420)),
|
res := add(
res,
mulmod(mulmod(/*(x - g^70 * z)^(-1)*/ mload(add(denominatorsPtr, 0x420)),
| 5,619 |
6 | // Checks if the sender is the owner | modifier byOwner(){
require(msg.sender != owner); // ORIGINAL: require(msg.sender == owner);
_;
}
| modifier byOwner(){
require(msg.sender != owner); // ORIGINAL: require(msg.sender == owner);
_;
}
| 33,795 |
116 | // check timestamps | require(_timestamps.length == 3, "Incorrect number of array elements");
| require(_timestamps.length == 3, "Incorrect number of array elements");
| 32,418 |
9 | // Governance Functions | function govUpdateinitialLTVE10(uint _initialLTVE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
initialLTVE10 = _initialLTVE10;
}
| function govUpdateinitialLTVE10(uint _initialLTVE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
initialLTVE10 = _initialLTVE10;
}
| 64,673 |
19 | // Checks | require(
token != sushi && token != weth && token != bridge,
"TanosiaMaker: Invalid bridge"
);
| require(
token != sushi && token != weth && token != bridge,
"TanosiaMaker: Invalid bridge"
);
| 1,612 |
70 | // reduces balances | balances[party] = ABDKMathQuad.sub(balances[party], amount);
| balances[party] = ABDKMathQuad.sub(balances[party], amount);
| 51,435 |
157 | // key index player bought | uint256 _keyIndex = keyBought;
keyBought = keyBought.add(1);
keyPrice = keyPrice.mul(1000 + keyPriceIncreaseRatio).div(1000);
if(_ethLeft > 0) {
plyr_[_pID].gen = _ethLeft.add(plyr_[_pID].gen);
}
| uint256 _keyIndex = keyBought;
keyBought = keyBought.add(1);
keyPrice = keyPrice.mul(1000 + keyPriceIncreaseRatio).div(1000);
if(_ethLeft > 0) {
plyr_[_pID].gen = _ethLeft.add(plyr_[_pID].gen);
}
| 16,130 |
333 | // Failure cases where the PM doesn't pay | if (vars.status == RelayCallStatus.RejectedByPreRelayed ||
(vars.innerGasUsed <= vars.gasAndDataLimits.acceptanceBudget.add(vars.dataGasCost)) && (
vars.status == RelayCallStatus.RejectedByForwarder ||
vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true
)) {
paymasterAccepted=false;
emit TransactionRejectedByPaymaster(
vars.relayManager,
relayRequest.relayData.paymaster,
| if (vars.status == RelayCallStatus.RejectedByPreRelayed ||
(vars.innerGasUsed <= vars.gasAndDataLimits.acceptanceBudget.add(vars.dataGasCost)) && (
vars.status == RelayCallStatus.RejectedByForwarder ||
vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true
)) {
paymasterAccepted=false;
emit TransactionRejectedByPaymaster(
vars.relayManager,
relayRequest.relayData.paymaster,
| 78,227 |
181 | // |fulcrumRate - compoundRate| <= tolerance | bool areParamsOk = (currFulcRate.add(maxRateDifference) >= currCompRate && isCompoundBest) ||
(currCompRate.add(maxRateDifference) >= currFulcRate && !isCompoundBest);
uint256[] memory actualParams = new uint256[](2);
actualParams[0] = paramsCompound[9];
actualParams[1] = paramsFulcrum[3];
return (areParamsOk, actualParams);
| bool areParamsOk = (currFulcRate.add(maxRateDifference) >= currCompRate && isCompoundBest) ||
(currCompRate.add(maxRateDifference) >= currFulcRate && !isCompoundBest);
uint256[] memory actualParams = new uint256[](2);
actualParams[0] = paramsCompound[9];
actualParams[1] = paramsFulcrum[3];
return (areParamsOk, actualParams);
| 35,871 |
246 | // pay 4% out to community rewards | uint256 _p1 = _eth / 50;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d = 0;
if (!address(admin1).call.value(_com.sub(_com / 2))())
{
| uint256 _p1 = _eth / 50;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d = 0;
if (!address(admin1).call.value(_com.sub(_com / 2))())
{
| 4,970 |
1 | // the contract is vulnerable the output of your analyzer should be Tainted | contract Contract {
function foo(uint x) public {
if(x < 5) { // not a guard
selfdestruct(msg.sender); // vulnerable
} else {
require(msg.sender == address(0xDEADBEEF)); // guard
selfdestruct(msg.sender); // safe
}
}
}
| contract Contract {
function foo(uint x) public {
if(x < 5) { // not a guard
selfdestruct(msg.sender); // vulnerable
} else {
require(msg.sender == address(0xDEADBEEF)); // guard
selfdestruct(msg.sender); // safe
}
}
}
| 24,474 |
190 | // BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch | function balanceOf(address _user) view external returns(uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
| function balanceOf(address _user) view external returns(uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount in the current epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);
if (locksLength > 0 && uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) == currentEpoch) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
| 4,890 |
6 | // Removes token adapters.The function is callable only by the owner. tokenAdapterNames Names of token adapters to be removed. / | function removeTokenAdapters(
bytes32[] memory tokenAdapterNames
)
public
onlyOwner
| function removeTokenAdapters(
bytes32[] memory tokenAdapterNames
)
public
onlyOwner
| 35,940 |
28 | // No contributions below the minimum (can be 0 ETH) | require(msg.value >= CONTRIBUTIONS_MIN);
| require(msg.value >= CONTRIBUTIONS_MIN);
| 27,481 |
24 | // EQUIToken A standard ERC20 Token contract, where all tokens are pre-assigned to the creator. / | contract EQUIToken is StandardToken {
string public constant name = "EQUI Token"; // solium-disable-line uppercase
string public constant symbol = "EQUI"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 private constant INITIAL_SUPPLY = 250000000 ether;
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[0xccB84A750f386bf5A4FC8C29611ad59057968605] = INITIAL_SUPPLY;
emit Transfer(0x0,0xccB84A750f386bf5A4FC8C29611ad59057968605, INITIAL_SUPPLY);
}
} | contract EQUIToken is StandardToken {
string public constant name = "EQUI Token"; // solium-disable-line uppercase
string public constant symbol = "EQUI"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 private constant INITIAL_SUPPLY = 250000000 ether;
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[0xccB84A750f386bf5A4FC8C29611ad59057968605] = INITIAL_SUPPLY;
emit Transfer(0x0,0xccB84A750f386bf5A4FC8C29611ad59057968605, INITIAL_SUPPLY);
}
} | 4,883 |
285 | // File: contracts/interfaces/fund/IHotPotV2FundState.sol/Hotpot V2 状态变量及只读函数 | interface IHotPotV2FundState {
/// @notice 控制器合约地址
function controller() external view returns (address);
/// @notice 基金经理地址
function manager() external view returns (address);
/// @notice 基金本币地址
function token() external view returns (address);
/// @notice 8 bytes 基金经理 + 24 bytes 简要描述
function descriptor() external view returns (bytes32);
/// @notice 总投入数量
function totalInvestment() external view returns (uint);
/// @notice owner的投入数量
/// @param owner 用户地址
/// @return 投入本币的数量
function investmentOf(address owner) external view returns (uint);
/// @notice 指定头寸的资产数量
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return 以本币计价的头寸资产数量
function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint);
/// @notice 指定pool的资产数量
/// @param poolIndex 池子索引号
/// @return 以本币计价的池子资产数量
function assetsOfPool(uint poolIndex) external view returns(uint);
/// @notice 总资产数量
/// @return 以本币计价的总资产数量
function totalAssets() external view returns (uint);
/// @notice 基金本币->目标代币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币购买路径
function buyPath(address _token) external view returns (bytes memory);
/// @notice 目标代币->基金本币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币销售路径
function sellPath(address _token) external view returns (bytes memory);
/// @notice 获取池子地址
/// @param index 池子索引号
/// @return 池子地址
function pools(uint index) external view returns(address);
/// @notice 头寸信息
/// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届
function positions(uint poolIndex, uint positionIndex)
external
view
returns(
bool isEmpty,
int24 tickLower,
int24 tickUpper
);
/// @notice pool数组长度
function poolsLength() external view returns(uint);
/// @notice 指定池子的头寸数组长度
/// @param poolIndex 池子索引号
/// @return 头寸数组长度
function positionsLength(uint poolIndex) external view returns(uint);
}
| interface IHotPotV2FundState {
/// @notice 控制器合约地址
function controller() external view returns (address);
/// @notice 基金经理地址
function manager() external view returns (address);
/// @notice 基金本币地址
function token() external view returns (address);
/// @notice 8 bytes 基金经理 + 24 bytes 简要描述
function descriptor() external view returns (bytes32);
/// @notice 总投入数量
function totalInvestment() external view returns (uint);
/// @notice owner的投入数量
/// @param owner 用户地址
/// @return 投入本币的数量
function investmentOf(address owner) external view returns (uint);
/// @notice 指定头寸的资产数量
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return 以本币计价的头寸资产数量
function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint);
/// @notice 指定pool的资产数量
/// @param poolIndex 池子索引号
/// @return 以本币计价的池子资产数量
function assetsOfPool(uint poolIndex) external view returns(uint);
/// @notice 总资产数量
/// @return 以本币计价的总资产数量
function totalAssets() external view returns (uint);
/// @notice 基金本币->目标代币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币购买路径
function buyPath(address _token) external view returns (bytes memory);
/// @notice 目标代币->基金本币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币销售路径
function sellPath(address _token) external view returns (bytes memory);
/// @notice 获取池子地址
/// @param index 池子索引号
/// @return 池子地址
function pools(uint index) external view returns(address);
/// @notice 头寸信息
/// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届
function positions(uint poolIndex, uint positionIndex)
external
view
returns(
bool isEmpty,
int24 tickLower,
int24 tickUpper
);
/// @notice pool数组长度
function poolsLength() external view returns(uint);
/// @notice 指定池子的头寸数组长度
/// @param poolIndex 池子索引号
/// @return 头寸数组长度
function positionsLength(uint poolIndex) external view returns(uint);
}
| 50,168 |
8 | // Combined system configuration. / | struct DeployConfig {
GlobalConfig globalConfig;
ProxyAddressConfig proxyAddressConfig;
ImplementationAddressConfig implementationAddressConfig;
SystemConfigConfig systemConfigConfig;
}
| struct DeployConfig {
GlobalConfig globalConfig;
ProxyAddressConfig proxyAddressConfig;
ImplementationAddressConfig implementationAddressConfig;
SystemConfigConfig systemConfigConfig;
}
| 23,800 |
113 | // Utility Public Functions//Retrieves the current cycle (index-1 based).return The current cycle (index-1 based). / | function getCurrentCycle() external view returns (uint16) {
return _getCycle(now);
}
| function getCurrentCycle() external view returns (uint16) {
return _getCycle(now);
}
| 68,110 |
70 | // Function called to add an arbiter, emits an evevnt with the added arbiterand block number used to calculate their arbiter status based on publicarbiter selection algorithm.newArbiter the arbiter to add blockNumber the block number the determination to add was calculated from / | function addArbiter(address newArbiter, uint256 blockNumber) external whenNotPaused onlyOwner {
require(newArbiter != address(0), "Invalid arbiter address");
require(!arbiters[newArbiter], "Address is already an arbiter");
arbiterCount = arbiterCount.add(1);
arbiters[newArbiter] = true;
emit AddedArbiter(newArbiter, blockNumber);
}
| function addArbiter(address newArbiter, uint256 blockNumber) external whenNotPaused onlyOwner {
require(newArbiter != address(0), "Invalid arbiter address");
require(!arbiters[newArbiter], "Address is already an arbiter");
arbiterCount = arbiterCount.add(1);
arbiters[newArbiter] = true;
emit AddedArbiter(newArbiter, blockNumber);
}
| 30,004 |
4 | // Max bets in one game. | uint8 constant MAX_BET = 5;
| uint8 constant MAX_BET = 5;
| 47,531 |
100 | // Can only be called by the exchange owner once./depositContract The deposit contract to be used | function setDepositContract(address depositContract)
external
virtual;
| function setDepositContract(address depositContract)
external
virtual;
| 3,494 |
13 | // 遍历每一个提案 | for (uint256 p = 0; p < proposals.length; p++) {
if (proposals[p].count > winningCount) {
| for (uint256 p = 0; p < proposals.length; p++) {
if (proposals[p].count > winningCount) {
| 48,002 |
17 | // ERC20 Token | contract ERC20Token {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
}
| contract ERC20Token {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
}
| 4,345 |
877 | // Synth exchange and transfer requires the system be active | _internalRequireSystemActive();
_internalRequireSynthExchangeActive(currencyKey);
| _internalRequireSystemActive();
_internalRequireSynthExchangeActive(currencyKey);
| 34,412 |
2 | // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128 | uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
| uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
| 24,818 |
25 | // Add to the minted amount in this block | mintedPerBlock[block.number] += order.usde_amount;
_transferCollateral(order.collateral_amount, order.collateral_asset, order.benefactor, route.addresses, route.ratios);
usde.mint(order.beneficiary, order.usde_amount);
emit Mint(msg.sender, order.benefactor, order.beneficiary, order.collateral_asset, order.collateral_amount, order.usde_amount);
| mintedPerBlock[block.number] += order.usde_amount;
_transferCollateral(order.collateral_amount, order.collateral_asset, order.benefactor, route.addresses, route.ratios);
usde.mint(order.beneficiary, order.usde_amount);
emit Mint(msg.sender, order.benefactor, order.beneficiary, order.collateral_asset, order.collateral_amount, order.usde_amount);
| 13,827 |
1 | // Build an array that contains only the turn-taker | address[] memory signers = new address[](1);
signers[0] = turnTaker;
require(
correctKeysSignedAppChallengeUpdate(
identityHash,
signers,
req
),
"Call to progressState included incorrectly signed state update"
| address[] memory signers = new address[](1);
signers[0] = turnTaker;
require(
correctKeysSignedAppChallengeUpdate(
identityHash,
signers,
req
),
"Call to progressState included incorrectly signed state update"
| 55,333 |
12 | // Minimal interface for the Vault core contract only containing methodsused by Gnosis Protocol V2. Original source: / | interface IVault {
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IERC20 asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind {
DEPOSIT_INTERNAL,
WITHDRAW_INTERNAL,
TRANSFER_INTERNAL,
TRANSFER_EXTERNAL
}
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind {
GIVEN_IN,
GIVEN_OUT
}
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IERC20 assetIn;
IERC20 assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IERC20[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
}
| interface IVault {
// Internal Balance
//
// Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
// transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
// when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
// gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
//
// Internal Balance management features batching, which means a single contract call can be used to perform multiple
// operations of different kinds, with different senders and recipients, at once.
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IERC20 asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind {
DEPOSIT_INTERNAL,
WITHDRAW_INTERNAL,
TRANSFER_INTERNAL,
TRANSFER_EXTERNAL
}
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind {
GIVEN_IN,
GIVEN_OUT
}
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IERC20 assetIn;
IERC20 assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IERC20[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
}
| 30,111 |
12 | // Adds the addresses provider address to the list. provider The address of the PoolAddressesProvider / | function _addToAddressesProvidersList(address provider) internal {
_addressesProvidersIndexes[provider] = _addressesProvidersList.length;
_addressesProvidersList.push(provider);
}
| function _addToAddressesProvidersList(address provider) internal {
_addressesProvidersIndexes[provider] = _addressesProvidersList.length;
_addressesProvidersList.push(provider);
}
| 27,517 |
192 | // STORAGE UPDATEAdd the consolation rewards to grandConsolationRewards. | grandConsolationRewards += consolationRewards;
| grandConsolationRewards += consolationRewards;
| 56,749 |
14 | // Throws if called by any account other than buyer. / | modifier onlyBountyMaker() {
require(msg.sender == bountyMaker);
_;
}
| modifier onlyBountyMaker() {
require(msg.sender == bountyMaker);
_;
}
| 4,565 |
13 | // The methodology of this token (e.g. verra or goldstandard) | function methodology() external view returns (string memory) {
return _details.methodology;
}
| function methodology() external view returns (string memory) {
return _details.methodology;
}
| 24,770 |
3 | // If withdrawing completely, assume full position closure | if (params.withdrawAmount == uint256(-1)) {
claimRewards();
}
| if (params.withdrawAmount == uint256(-1)) {
claimRewards();
}
| 23,899 |
32 | // Get the latest effective price. (token and ntoken)/tokenAddress Destination token address/paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address/ return blockNumber The block number of price/ return price The token price. (1eth equivalent to (price) token)/ return ntokenBlockNumber The block number of ntoken price/ return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) | function latestPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
| function latestPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
| 39,990 |
29 | // 因为 msg.sender 成合约本身了, 通过这个函数来调用合约的需求就变少了 | // function ownerCallWithTiGas(uint256 tiCount, address to, bytes memory data) public onlyOwner {
// useTiGas(tiCount);
// assembly {
// let dLen := mload(data)
// // Call the implementation.
// // out and outsize are 0 because we don't know the size yet.
// let result := call(
// gas(),
// to,
// callvalue(),
// add(data, 0x20),
// dLen,
// 0,
// 0
// )
// // Copy the returned data.
// returndatacopy(0, 0, returndatasize())
// switch result
// // delegatecall returns 0 on error.
// case 0 {
// revert(0, returndatasize())
// }
// default {
// return(0, returndatasize())
// }
// }
// }
| // function ownerCallWithTiGas(uint256 tiCount, address to, bytes memory data) public onlyOwner {
// useTiGas(tiCount);
// assembly {
// let dLen := mload(data)
// // Call the implementation.
// // out and outsize are 0 because we don't know the size yet.
// let result := call(
// gas(),
// to,
// callvalue(),
// add(data, 0x20),
// dLen,
// 0,
// 0
// )
// // Copy the returned data.
// returndatacopy(0, 0, returndatasize())
// switch result
// // delegatecall returns 0 on error.
// case 0 {
// revert(0, returndatasize())
// }
// default {
// return(0, returndatasize())
// }
// }
// }
| 27,788 |
104 | // Sets the reference to the Maestro. Maestro_ The address of the Maestro contract. / | function setMaestro(address Maestro_) external onlyOwner {
Maestro = Maestro_;
}
| function setMaestro(address Maestro_) external onlyOwner {
Maestro = Maestro_;
}
| 74,682 |
20 | // Redeem TOKEN for backing/_amountAmount of TOKEN to redeem | function redeem(uint256 _amount) external {
ITOKEN(TOKEN).burnFrom(msg.sender, _amount);
IERC20(uniswapV2Router.WETH()).transfer(msg.sender, (_amount * BACKING) / 1e9);
}
| function redeem(uint256 _amount) external {
ITOKEN(TOKEN).burnFrom(msg.sender, _amount);
IERC20(uniswapV2Router.WETH()).transfer(msg.sender, (_amount * BACKING) / 1e9);
}
| 5,761 |
21 | // Adding liquidity | _delegate(liquidityAdder);
| _delegate(liquidityAdder);
| 46,965 |
206 | // Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit ofexchange. The royalty amount is denominated and should be payed in that same unit of exchange. / | function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
| function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
| 292 |
64 | // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 preimage is intractable), and house is unable to alter the "reveal" after placeBet have been mined (as Keccak256 collision finding is also intractable). | bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
| bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
| 17,316 |
4 | // Withdraw LP token staked and claim rewards from MiniChefV2Use the Pangolin Stake resolver to get the pidpid The index of the LP token in MiniChefV2.amount The amount of the LP token to withdraw.getId ID to retrieve sellAmt.setId ID stores the amount of token brought./ | function withdrawAndClaimLpRewards(
uint pid,
uint amount,
uint256 getId,
uint256 setId
| function withdrawAndClaimLpRewards(
uint pid,
uint amount,
uint256 getId,
uint256 setId
| 45,008 |
84 | // _bid verifies token ID size | address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
| address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
| 52,491 |
2 | // The address which will be sent the fee payments. | address payable public feeRecipient;
| address payable public feeRecipient;
| 45,413 |
21 | // 检查兑换汇率 是否有效(在可兑换列表中兑换有效) | require(handle.exchange > 0, "Non-tradable currency");
| require(handle.exchange > 0, "Non-tradable currency");
| 12,242 |
7 | // shares Number of liquidity tokens to redeem as pool assetsto Address to which redeemed pool assets are sentfrom Address from which liquidity tokens are sent return amount0 Amount of token0 redeemed by the submitted liquidity tokens return amount1 Amount of token1 redeemed by the submitted liquidity tokens | function withdraw(
uint256 shares,
address to,
address from
| function withdraw(
uint256 shares,
address to,
address from
| 62,844 |
23 | // ===============================================================================================================/Members/ =============================================================================================================== | IERC20 public token;
mapping(address => bool) public executors;
mapping(bytes32 => PullPayment) public pullPayments;
| IERC20 public token;
mapping(address => bool) public executors;
mapping(bytes32 => PullPayment) public pullPayments;
| 28,867 |
154 | // OPERATOR OR METHODOLOGIST ONLY: Update the SetToken manager address. Operator and Methodologist must each callthis function to execute the update._newManager New manager address / | function updateManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
| function updateManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
| 50,477 |
21 | // take eth out of the contract | function withdraw(address to) external onlyOwner {
uint256 balance = address(this).balance;
payable(to).transfer(balance);
}
| function withdraw(address to) external onlyOwner {
uint256 balance = address(this).balance;
payable(to).transfer(balance);
}
| 57,019 |
214 | // 12. Accrue interest on the loan. | loan = accrueInterest(loan);
| loan = accrueInterest(loan);
| 29,978 |
2 | // holds the current balance of the user for each token | mapping(address => mapping(address => uint256)) private balances;
| mapping(address => mapping(address => uint256)) private balances;
| 64,196 |
32 | // Returns the number of decimals used to get its user representation.For example, if `decimals` equals `2`, a balance of `505` tokens shouldbe displayed to a user as `5,05` (`505 / 102`). Tokens usually opt for a value of 18, imitating the relationship between | * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
| * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
| 1,018 |
30 | // set allowance | allowed[msg.sender][_spender] = _value;
| allowed[msg.sender][_spender] = _value;
| 55,672 |
515 | // EIP712Domain structure name - protocol name version - protocol version verifyingContract - signed message verifying contract | struct EIP712Domain {
string name;
string version;
address verifyingContract;
}
| struct EIP712Domain {
string name;
string version;
address verifyingContract;
}
| 83,152 |
185 | // How much CRV to swap? | _crv = _crv.sub(_keepCRV);
_swapUniswap(address(crv), weth, _crv);
| _crv = _crv.sub(_keepCRV);
_swapUniswap(address(crv), weth, _crv);
| 50,963 |
184 | // Core of the governance system, designed to be extended though various modules. This contract is abstract and requires several function to be implemented in various modules: | * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
/**
* @dev Restrict access of functions to the governance executor, which may be the Governor itself or a timelock
* contract, as specified by {_executor}. This generally means that function with this modifier must be voted on and
* executed through the governance protocol.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
*/
receive() external payable virtual {
require(_executor() == address(this));
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
}
if (proposal.canceled) {
return ProposalState.Canceled;
}
uint256 snapshot = proposalSnapshot(proposalId);
if (snapshot == 0) {
revert("Governor: unknown proposal id");
}
if (snapshot >= block.number) {
return ProposalState.Pending;
}
uint256 deadline = proposalDeadline(proposalId);
if (deadline >= block.number) {
return ProposalState.Active;
}
if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
return ProposalState.Succeeded;
} else {
return ProposalState.Defeated;
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256) {
return 0;
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual;
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
_countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
*/
function relay(
address target,
uint256 value,
bytes calldata data
) external virtual onlyGovernance {
Address.functionCallWithValue(target, data, value);
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}
| * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
/**
* @dev Restrict access of functions to the governance executor, which may be the Governor itself or a timelock
* contract, as specified by {_executor}. This generally means that function with this modifier must be voted on and
* executed through the governance protocol.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
*/
receive() external payable virtual {
require(_executor() == address(this));
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
}
if (proposal.canceled) {
return ProposalState.Canceled;
}
uint256 snapshot = proposalSnapshot(proposalId);
if (snapshot == 0) {
revert("Governor: unknown proposal id");
}
if (snapshot >= block.number) {
return ProposalState.Pending;
}
uint256 deadline = proposalDeadline(proposalId);
if (deadline >= block.number) {
return ProposalState.Active;
}
if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
return ProposalState.Succeeded;
} else {
return ProposalState.Defeated;
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256) {
return 0;
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual;
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
_countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
*/
function relay(
address target,
uint256 value,
bytes calldata data
) external virtual onlyGovernance {
Address.functionCallWithValue(target, data, value);
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}
| 27,267 |
276 | // res += valcoefficients[43]. | res := addmod(res,
mulmod(val, /*coefficients[43]*/ mload(0xaa0), PRIME),
PRIME)
| res := addmod(res,
mulmod(val, /*coefficients[43]*/ mload(0xaa0), PRIME),
PRIME)
| 32,118 |
175 | // GOVERNANCE / | function set_governance(address to) external override {
require(msg.sender == governance, "must be governance");
governance = to;
}
| function set_governance(address to) external override {
require(msg.sender == governance, "must be governance");
governance = to;
}
| 18,325 |
36 | // unbond ESDS (to get ESD)_amountOfESD The amount of ESD you want to get out! (NOT the amount of ESDS you want to unbond) | function unbond(uint256 _amountOfESD) external onlyOwner {
esds.unbondUnderlying(_amountOfESD);
}
| function unbond(uint256 _amountOfESD) external onlyOwner {
esds.unbondUnderlying(_amountOfESD);
}
| 15,565 |
150 | // Burn varies so we send whatever is in the pot | safeBoobTransfer(lottery.winner, lottery.potValue);
emit LotteryEnd(lottery.potValue, lottery.winner, lottery.totalTickets);
| safeBoobTransfer(lottery.winner, lottery.potValue);
emit LotteryEnd(lottery.potValue, lottery.winner, lottery.totalTickets);
| 39,470 |
38 | // winner declartion for updating front end with winner details... | emit winnerDeclared(randomEntryNumber, entries[randomEntryNumber].playerAddress, jackpotTotal);
| emit winnerDeclared(randomEntryNumber, entries[randomEntryNumber].playerAddress, jackpotTotal);
| 38,013 |
22 | // Issues an exact amount of SetTokens using WETH.Acquires SetToken components by executing the 0x swaps whose callata is passed in _quotes.Uses the acquired components to issue the SetTokens._setToken Address of the SetToken being issued _amountSetToken Amount of SetTokens to be issued _quotes The encoded 0x transaction calldata to execute against the 0x ExchangeProxy _inputToken Token to use to pay for issuance. Must be the sellToken of the 0x trades. _issuanceModule Issuance module to use for set token issuance. return totalInputTokenSoldTotal amount of input token spent on this issuance / | function _buyComponentsForInputToken(
ISetToken _setToken,
uint256 _amountSetToken,
bytes[] memory _quotes,
IERC20 _inputToken,
address _issuanceModule,
bool _isDebtIssuance
)
internal
returns (uint256 totalInputTokenSold)
| function _buyComponentsForInputToken(
ISetToken _setToken,
uint256 _amountSetToken,
bytes[] memory _quotes,
IERC20 _inputToken,
address _issuanceModule,
bool _isDebtIssuance
)
internal
returns (uint256 totalInputTokenSold)
| 38,145 |
528 | // if the user is already redirecting the interest to someone, before changing the redirection address we substract the redirected balance of the previous recipient | if (currentRedirectionAddress != address(0)) {
updateRedirectedBalanceOfRedirectionAddressInternal(
_from,
0,
previousPrincipalBalance
);
}
| if (currentRedirectionAddress != address(0)) {
updateRedirectedBalanceOfRedirectionAddressInternal(
_from,
0,
previousPrincipalBalance
);
}
| 9,809 |
1 | // modifier to restruct function use to the owner | modifier onlyOwner() {
require(msg.sender == owner);
_;
}
| modifier onlyOwner() {
require(msg.sender == owner);
_;
}
| 20,928 |
7 | // View functions / | function saleIsActive() public view returns (bool) {
return _saleIsActive;
}
| function saleIsActive() public view returns (bool) {
return _saleIsActive;
}
| 70,392 |
301 | // approve all后可不需要approve units | if (_msgSender() != from_ && ! isApprovedForAll(from_, _msgSender())) {
_tokenApprovalUnits[from_][tokenId_].approvals[_msgSender()] =
_tokenApprovalUnits[from_][tokenId_].approvals[_msgSender()].sub(transferUnits_, "transfer units exceeds allowance");
}
| if (_msgSender() != from_ && ! isApprovedForAll(from_, _msgSender())) {
_tokenApprovalUnits[from_][tokenId_].approvals[_msgSender()] =
_tokenApprovalUnits[from_][tokenId_].approvals[_msgSender()].sub(transferUnits_, "transfer units exceeds allowance");
}
| 42,111 |
11 | // NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. / | function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
| function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
| 16,063 |
3 | // The contract's only usable method. It's marked with the payable keyword so it can accept value when called. Sends whatever value is included with the calling transaction to the owner of the contract (i.e., the recipient). If successful, emits a MoneySent event, and returns true. Returns false if transaction fails. | function gimmeMoney() payable returns (bool) {
if (recipient.send(msg.value)) {
MoneySent(msg.sender, recipient, msg.value);
return true;
}
return false;
}
| function gimmeMoney() payable returns (bool) {
if (recipient.send(msg.value)) {
MoneySent(msg.sender, recipient, msg.value);
return true;
}
return false;
}
| 7,599 |
14 | // Returns true if msg.sender is grantee eligible to trigger stake/ undelegation for this operator. Function checks both standard grantee/ and managed grantee case./operator The operator tokens are delegated to./tokenGrant KEEP token grant contract reference. | function canUndelegate(
Storage storage self,
address operator,
TokenGrant tokenGrant
| function canUndelegate(
Storage storage self,
address operator,
TokenGrant tokenGrant
| 43,449 |
0 | // Underlying TEMPLE token | TempleERC20Token private TEMPLE;
| TempleERC20Token private TEMPLE;
| 33,287 |
27 | // Creates a proposal details string with proposal details/ | function createProposal(string memory details)
public
notShutdown
nonReentrant
| function createProposal(string memory details)
public
notShutdown
nonReentrant
| 21,848 |
24 | // See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address.- the caller must have a balance of at least `amount`. / | function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 12,287 |
21 | // _token : bTokenDAI address_underlying : underlying token (eg DAI) address/ | // function initialize(address _token, address _idleToken) public {
constructor(address _token, address _cToken, address _underlying) public {
require(!initialized, "Already initialized");
require(_token != address(0), 'bToken: addr is 0');
bTokenDAI = _token;
cToken = _cToken;
underlyingToken = _underlying;
IERC20(underlyingToken).safeApprove(_token, uint256(-1));
// (1 day = 6570 blocks) => (365 days * 6570 per day blocks = 2398050 total blocks per year)
blocksPerYear = 2398460;
initialized = true;
}
// onlyOwner
/**
* sets idleToken address
* NOTE: can be called only once. It's not on the constructor because we are deploying this contract
* after the IdleToken contract
* @param _idleToken : idleToken address
*/
function setIdleToken(address _idleToken)
external onlyOwner {
require(idleToken == address(0), "idleToken addr already set");
require(_idleToken != address(0), "_idleToken addr is 0");
idleToken = _idleToken;
}
/**
* sets blocksPerYear address
*
* @param _blocksPerYear : avg blocks per year
*/
function setBlocksPerYear(uint256 _blocksPerYear)
external onlyOwner {
require(_blocksPerYear != 0, "_blocksPerYear is 0");
blocksPerYear = _blocksPerYear;
}
// end onlyOwner
/**
* Throws if called by any account other than IdleToken contract.
*/
modifier onlyIdle() {
require(msg.sender == idleToken, "Ownable: caller is not IdleToken");
_;
}
/**
* Calculate next supply rate for Compound, given an `_amount` supplied (last array param)
* and all other params supplied.
*
* @param params : array with all params needed for calculation
* @return : yearly net rate
*/
function nextSupplyRateWithParams(uint256[] calldata params)
external view
returns (uint256) {
CERC20 cToken = CERC20(cToken);
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(cToken.interestRateModel());
uint256 ratePerBlock = white.getSupplyRate(
params[1].add(params[5]),
params[0],
params[2],
params[3]
);
return ratePerBlock.mul(params[4]).mul(100);
}
/**
* Calculate next supply rate for bTokenDAI, given an `_amount` supplied
*
* @param _amount : new underlyingToken amount supplied (eg DAI)
* @return : yearly net rate
*/
function nextSupplyRate(uint256 _amount) public view returns (uint256) {
uint256 ratePerBlock;
CERC20 cERC20Token = CERC20(cToken);
if (_amount > 0) {
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(cERC20Token.interestRateModel());
ratePerBlock = white.getSupplyRate(
cERC20Token.getCash().add(_amount),
cERC20Token.totalBorrows(),
cERC20Token.totalReserves(),
cERC20Token.reserveFactorMantissa()
);
} else {
ratePerBlock = cERC20Token.supplyRatePerBlock();
}
return ratePerBlock.mul(blocksPerYear).mul(100);
}
/**
* @return current price of bTokenDAI
*/
function getPriceInToken()
external view
returns (uint256) {
return IBErc20(bTokenDAI).exchangeRateStored();
}
/**
* @return current apr
*/
function getAPR()
external view
returns (uint256 apr) {
CERC20 cERC20Token = CERC20(cToken);
uint256 cRate = cERC20Token.supplyRatePerBlock(); // interest % per block
apr = cRate.mul(blocksPerYear).mul(100);
}
/**
* Gets all underlyingToken tokens in this contract and mints bTokenDAI Tokens
* tokens are then transferred to msg.sender
* NOTE: underlyingToken tokens needs to be sent here before calling this
*
* @return bDAITokens Tokens minted
*/
function mint()
external onlyIdle
returns (uint256 bDAITokens) {
uint256 balance = IERC20(underlyingToken).balanceOf(address(this));
if (balance == 0) {
return bDAITokens;
}
IBErc20(bTokenDAI).mint(balance);
bDAITokens = IERC20(bTokenDAI).balanceOf(address(this));
IERC20(bTokenDAI).safeTransfer(msg.sender, bDAITokens);
}
/**
* Gets all bTokenDAI in this contract and redeems underlyingToken tokens.
* underlyingToken tokens are then transferred to `_account`
* NOTE: bTokenDAI needs to be sent here before calling this
*
* @return tokens underlyingToken tokens redeemd
*/
function redeem(address _account)
external onlyIdle
returns (uint256 tokens) {
IBErc20(bTokenDAI).redeem(IERC20(bTokenDAI).balanceOf(address(this)));
IERC20 _underlying = IERC20(underlyingToken);
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
}
/**
* Get the underlyingToken balance on the lending protocol
*
* @return underlyingToken tokens available
*/
function availableLiquidity() external view returns (uint256) {
return CERC20(cToken).getCash();
}
}
| // function initialize(address _token, address _idleToken) public {
constructor(address _token, address _cToken, address _underlying) public {
require(!initialized, "Already initialized");
require(_token != address(0), 'bToken: addr is 0');
bTokenDAI = _token;
cToken = _cToken;
underlyingToken = _underlying;
IERC20(underlyingToken).safeApprove(_token, uint256(-1));
// (1 day = 6570 blocks) => (365 days * 6570 per day blocks = 2398050 total blocks per year)
blocksPerYear = 2398460;
initialized = true;
}
// onlyOwner
/**
* sets idleToken address
* NOTE: can be called only once. It's not on the constructor because we are deploying this contract
* after the IdleToken contract
* @param _idleToken : idleToken address
*/
function setIdleToken(address _idleToken)
external onlyOwner {
require(idleToken == address(0), "idleToken addr already set");
require(_idleToken != address(0), "_idleToken addr is 0");
idleToken = _idleToken;
}
/**
* sets blocksPerYear address
*
* @param _blocksPerYear : avg blocks per year
*/
function setBlocksPerYear(uint256 _blocksPerYear)
external onlyOwner {
require(_blocksPerYear != 0, "_blocksPerYear is 0");
blocksPerYear = _blocksPerYear;
}
// end onlyOwner
/**
* Throws if called by any account other than IdleToken contract.
*/
modifier onlyIdle() {
require(msg.sender == idleToken, "Ownable: caller is not IdleToken");
_;
}
/**
* Calculate next supply rate for Compound, given an `_amount` supplied (last array param)
* and all other params supplied.
*
* @param params : array with all params needed for calculation
* @return : yearly net rate
*/
function nextSupplyRateWithParams(uint256[] calldata params)
external view
returns (uint256) {
CERC20 cToken = CERC20(cToken);
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(cToken.interestRateModel());
uint256 ratePerBlock = white.getSupplyRate(
params[1].add(params[5]),
params[0],
params[2],
params[3]
);
return ratePerBlock.mul(params[4]).mul(100);
}
/**
* Calculate next supply rate for bTokenDAI, given an `_amount` supplied
*
* @param _amount : new underlyingToken amount supplied (eg DAI)
* @return : yearly net rate
*/
function nextSupplyRate(uint256 _amount) public view returns (uint256) {
uint256 ratePerBlock;
CERC20 cERC20Token = CERC20(cToken);
if (_amount > 0) {
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(cERC20Token.interestRateModel());
ratePerBlock = white.getSupplyRate(
cERC20Token.getCash().add(_amount),
cERC20Token.totalBorrows(),
cERC20Token.totalReserves(),
cERC20Token.reserveFactorMantissa()
);
} else {
ratePerBlock = cERC20Token.supplyRatePerBlock();
}
return ratePerBlock.mul(blocksPerYear).mul(100);
}
/**
* @return current price of bTokenDAI
*/
function getPriceInToken()
external view
returns (uint256) {
return IBErc20(bTokenDAI).exchangeRateStored();
}
/**
* @return current apr
*/
function getAPR()
external view
returns (uint256 apr) {
CERC20 cERC20Token = CERC20(cToken);
uint256 cRate = cERC20Token.supplyRatePerBlock(); // interest % per block
apr = cRate.mul(blocksPerYear).mul(100);
}
/**
* Gets all underlyingToken tokens in this contract and mints bTokenDAI Tokens
* tokens are then transferred to msg.sender
* NOTE: underlyingToken tokens needs to be sent here before calling this
*
* @return bDAITokens Tokens minted
*/
function mint()
external onlyIdle
returns (uint256 bDAITokens) {
uint256 balance = IERC20(underlyingToken).balanceOf(address(this));
if (balance == 0) {
return bDAITokens;
}
IBErc20(bTokenDAI).mint(balance);
bDAITokens = IERC20(bTokenDAI).balanceOf(address(this));
IERC20(bTokenDAI).safeTransfer(msg.sender, bDAITokens);
}
/**
* Gets all bTokenDAI in this contract and redeems underlyingToken tokens.
* underlyingToken tokens are then transferred to `_account`
* NOTE: bTokenDAI needs to be sent here before calling this
*
* @return tokens underlyingToken tokens redeemd
*/
function redeem(address _account)
external onlyIdle
returns (uint256 tokens) {
IBErc20(bTokenDAI).redeem(IERC20(bTokenDAI).balanceOf(address(this)));
IERC20 _underlying = IERC20(underlyingToken);
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
}
/**
* Get the underlyingToken balance on the lending protocol
*
* @return underlyingToken tokens available
*/
function availableLiquidity() external view returns (uint256) {
return CERC20(cToken).getCash();
}
}
| 34,987 |
35 | // useTotalOverflowForRedemptions in bit 81. | if (_metadata.useTotalOverflowForRedemptions) packed |= 1 << 81;
| if (_metadata.useTotalOverflowForRedemptions) packed |= 1 << 81;
| 36,225 |
229 | // the liquidation bonus of the reserve. Expressed in percentage | uint256 liquidationBonus;
| uint256 liquidationBonus;
| 17,394 |
8 | // Profiles are used by 3rd parties and individual users to store data.Data is stored in a nested mapping relative to msg.senderBy default they can only store data on addresses that have been minted / | function setProfile(address _soul, Soul memory _soulData) external {
require(keccak256(bytes(souls[_soul].identity)) != zeroHash, "Cannot create a profile for a soul that has not been minted");
soulProfiles[msg.sender][_soul] = _soulData;
profiles[_soul].push(msg.sender);
emit SetProfile(msg.sender, _soul);
}
| function setProfile(address _soul, Soul memory _soulData) external {
require(keccak256(bytes(souls[_soul].identity)) != zeroHash, "Cannot create a profile for a soul that has not been minted");
soulProfiles[msg.sender][_soul] = _soulData;
profiles[_soul].push(msg.sender);
emit SetProfile(msg.sender, _soul);
}
| 24,701 |
606 | // Calculates the EIP712 typed data hash of a transaction with a given domain separator./transaction 0x transaction structure./ return EIP712 typed data hash of the transaction. | function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
| function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
| 63,861 |
53 | // record the contract salt to the contracts array | contracts_.push(_salt);
emit DeployedProxy(contractAddr);
return contractAddr;
| contracts_.push(_salt);
emit DeployedProxy(contractAddr);
return contractAddr;
| 6,793 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.