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
|
|---|---|---|---|---|
23
|
// execute event NewProduct
|
emit NewProduct(newID, name, price, quantity, owner);
return newID;
|
emit NewProduct(newID, name, price, quantity, owner);
return newID;
| 38,944
|
39
|
// function _safeTransferFrom( IERC20 token, address sender, address recipient, uint amount
|
// ) private {
// bool sent = token.transferFrom(sender, recipient, amount);
// require(sent, "Token transfer failed");
// }
|
// ) private {
// bool sent = token.transferFrom(sender, recipient, amount);
// require(sent, "Token transfer failed");
// }
| 1,656
|
77
|
// Returns ceil(a / b)./
|
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
}
|
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
}
| 4,856
|
22
|
// 600 million total supply divided into90 million to privatesale address120 million to presale address180 million to crowdsale address90 million to eco supply address120 million to team supply address
|
totalSupply_ = 600000000 * 10**uint(decimals);
privatesaleSupply = 90000000 * 10**uint(decimals);
presaleSupply = 120000000 * 10**uint(decimals);
crowdsaleSupply = 180000000 * 10**uint(decimals);
ecoSupply = 90000000 * 10**uint(decimals);
teamSupply = 120000000 * 10**uint(decimals);
firstVestAmount = teamSupply.div(2);
secondVestAmount = firstVestAmount;
currentVestedAmount = 0;
|
totalSupply_ = 600000000 * 10**uint(decimals);
privatesaleSupply = 90000000 * 10**uint(decimals);
presaleSupply = 120000000 * 10**uint(decimals);
crowdsaleSupply = 180000000 * 10**uint(decimals);
ecoSupply = 90000000 * 10**uint(decimals);
teamSupply = 120000000 * 10**uint(decimals);
firstVestAmount = teamSupply.div(2);
secondVestAmount = firstVestAmount;
currentVestedAmount = 0;
| 31,190
|
4
|
// The ONI TOKEN!
|
OniToken public oni;
|
OniToken public oni;
| 7,905
|
10
|
// Token - is a smart contract interface for managing common functionality of a token./
|
contract TokenInterface {
// total amount of tokens
uint256 totalSupply;
/**
*
* balanceOf() - constant function check concrete tokens balance
*
* @param owner - account owner
*
* @return the value of balance
*/
function balanceOf(address owner) constant returns(uint256 balance);
function transfer(address to, uint256 value) returns(bool success);
function transferFrom(address from, address to, uint256 value) returns(bool success);
/**
*
* approve() - function approves to a person to spend some tokens from
* owner balance.
*
* @param spender - person whom this right been granted.
* @param value - value to spend.
*
* @return true in case of succes, otherwise failure
*
*/
function approve(address spender, uint256 value) returns(bool success);
/**
*
* allowance() - constant function to check how much is
* permitted to spend to 3rd person from owner balance
*
* @param owner - owner of the balance
* @param spender - permitted to spend from this balance person
*
* @return - remaining right to spend
*
*/
function allowance(address owner, address spender) constant returns(uint256 remaining);
// events notifications
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
contract TokenInterface {
// total amount of tokens
uint256 totalSupply;
/**
*
* balanceOf() - constant function check concrete tokens balance
*
* @param owner - account owner
*
* @return the value of balance
*/
function balanceOf(address owner) constant returns(uint256 balance);
function transfer(address to, uint256 value) returns(bool success);
function transferFrom(address from, address to, uint256 value) returns(bool success);
/**
*
* approve() - function approves to a person to spend some tokens from
* owner balance.
*
* @param spender - person whom this right been granted.
* @param value - value to spend.
*
* @return true in case of succes, otherwise failure
*
*/
function approve(address spender, uint256 value) returns(bool success);
/**
*
* allowance() - constant function to check how much is
* permitted to spend to 3rd person from owner balance
*
* @param owner - owner of the balance
* @param spender - permitted to spend from this balance person
*
* @return - remaining right to spend
*
*/
function allowance(address owner, address spender) constant returns(uint256 remaining);
// events notifications
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 29,944
|
25
|
// Performs a Solidity function call using a low level `call`. Aplain`call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ /
|
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
|
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
| 48,591
|
41
|
// The "key" below is the Ethereum Address in string format that is in the "listOfSellers" double-linked list.
|
uint keyCount = 0;
string memory key = EMPTY_STRING;
while (true) {
key = listOfSellers[key][NEXT];
if (keyCount == _index) {
break;
}
|
uint keyCount = 0;
string memory key = EMPTY_STRING;
while (true) {
key = listOfSellers[key][NEXT];
if (keyCount == _index) {
break;
}
| 46,596
|
49
|
// calculates the delta between supply and redeem for tokens and burn or mint them
|
adjustTokenBalance(epochID, supplyInToken, redeemInToken);
|
adjustTokenBalance(epochID, supplyInToken, redeemInToken);
| 31,495
|
4
|
// Validate strike digits
|
uint8 digits = _getDigits(strike);
require(digits > 3, "Strike digits < 3");
|
uint8 digits = _getDigits(strike);
require(digits > 3, "Strike digits < 3");
| 42,875
|
112
|
// require(amount > 0, 'VirtualDepositRewardPool : Cannot withdraw 0');
|
emit Withdrawn(_account, amount);
|
emit Withdrawn(_account, amount);
| 63,605
|
153
|
// Creates `amount` new tokens for `to`.
|
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
|
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
| 7,483
|
0
|
// Sign extend a shorter signed value to the full int32/number signed number to be extended/wordSize number of bits of the signed number, ie, 8 for int8
|
function int32SignExtension(int32 number, uint32 wordSize)
public pure returns(int32)
|
function int32SignExtension(int32 number, uint32 wordSize)
public pure returns(int32)
| 25,910
|
5
|
// Function for start initial farming round (only for `DEFAULT_ADMIN_ROLE`)/
|
function startFarming() external AccessControlUpgradeable.onlyRole(DEFAULT_ADMIN_ROLE) {
FarmingUpgradeable._startFarming();
}
|
function startFarming() external AccessControlUpgradeable.onlyRole(DEFAULT_ADMIN_ROLE) {
FarmingUpgradeable._startFarming();
}
| 21,796
|
23
|
// RightsDigitalAssetObject/ERC721 based token.
|
contract RightsDigitalAssetObject is IRightsDigitalAssetObject, RDDNControl, ERC721Full {
using SafeMath for uint256;
string internal constant name_ = "RithtsDigitalAssets";
string internal constant symbol_ = "RDA";
/*** DATA TYPES ***/
struct DigitalAssetObject {
uint256 specId; // asset spec id
string mediaId; // media file id
string info; //asset's additional information
}
/*** STORAGE ***/
DigitalAssetObject[] public digitalAssetObjects; // all object list (this index is objectId)
// Mapping from spec ID to index of the minted objects list
mapping(uint256 => uint256[]) private mintedObjects;
// Mapping from object id to position in the minted objects array
mapping(uint256 => uint256) private mintedObjectsIndex;
// // Mapping from spec id to count of owned objects
// mapping(uint256 => mapping(address => uint256)) private ownedObjectCount;
RightsDigitalAssetSpec spec;
/*** CONSTRUCTOR ***/
constructor(address specAddr) ERC721Full(name_, symbol_) public {
spec = RightsDigitalAssetSpec(specAddr);
}
/*** EXTERNAL FUNCTIONS ***/
/// @dev Mint a DigitalAsset.
/// @param _to The address that will own the minted token
/// @param _specId spec identifer
/// @param _mediaId mediaId
/// @param _info info
/// @return objectId
function mint(
address _to,
uint256 _specId,
string _mediaId,
string _info
) public whenNotPaused {
require(spec.ownerOf(_specId) == msg.sender);
// check total supply count
require(
spec.totalSupplyLimitOf(_specId) >= mintedObjects[_specId].length
|| spec.totalSupplyLimitOf(_specId) == 0
);
require(
keccak256(abi.encodePacked(_mediaId)) == keccak256(abi.encodePacked(spec.mediaIdOf(_specId)))
|| keccak256(abi.encodePacked(_mediaId)) == keccak256(abi.encodePacked(""))
);
DigitalAssetObject memory digitalAssetObject = DigitalAssetObject({
specId : _specId,
mediaId: _mediaId,
info: _info
});
uint256 objectId = digitalAssetObjects.push(digitalAssetObject).sub(1);
_mint(_to, objectId);
_addObjectTo(_specId, objectId);
emit Mint(
msg.sender,
objectId,
digitalAssetObject.specId
);
}
/// @dev Set MediaId
/// @param _objectId object identifer
/// @param _mediaId mediaId
function setMediaId(uint256 _objectId, string _mediaId) public whenNotPaused {
require(_exists(_objectId));
DigitalAssetObject storage digitalAsset = digitalAssetObjects[_objectId];
require(spec.ownerOf(digitalAsset.specId) == msg.sender);
require(keccak256(abi.encodePacked(digitalAsset.mediaId)) == keccak256(abi.encodePacked("")));
// set mediaId
digitalAsset.mediaId = _mediaId;
emit SetMediaId(msg.sender, _objectId, digitalAsset.mediaId);
}
/// @dev Get DigitalAsset.
/// @param _objectId object identifer
/// @return object info
function getDigitalAssetObject(uint256 _objectId) public view returns (
uint256 objectId,
uint256 specId,
string mediaId,
string info,
address owner,
uint256 objectIndex
) {
require(_exists(_objectId));
DigitalAssetObject storage digitalAsset = digitalAssetObjects[_objectId];
address objectOwner = ownerOf(_objectId);
return (
_objectId,
digitalAsset.specId,
digitalAsset.mediaId,
digitalAsset.info,
objectOwner,
mintedObjectsIndex[_objectId]
);
}
/// @dev Get DigitalAsset.
/// @param _owner address owning the tokens list to be accessed
/// @param _index uint256 representing the index to be accessed of the requested tokens list
/// @return object info
function getDigitalAssetObject(address _owner, uint256 _index) public view returns (
uint256 objectId,
uint256 specId,
string mediaId,
string info,
address owner,
uint256 objectIndex
) {
uint256 id = tokenOfOwnerByIndex(_owner, _index);
return getDigitalAssetObject(id);
}
/// @dev Get DigitalAsset.
/// @param _specId spec identifer
/// @param _index uint256 representing the index to be accessed of the requested tokens list
/// @return object info
function getDigitalAssetObject(uint256 _specId, uint256 _index) public view returns (
uint256 objectId,
uint256 specId,
string mediaId,
string info,
address owner,
uint256 objectIndex
) {
require(spec.ownerOf(_specId) != address(0));
uint256 id = objectOfSpecByIndex(_specId, _index);
return getDigitalAssetObject(id);
}
/// @dev Gets the token ID at a given index of the tokens list of the requested owner
/// @param _specId spec identifer
/// @param _index uint256 representing the index to be accessed of the requested tokens list
/// @return uint256 token ID at the given index of the tokens list owned by the requested address
function objectOfSpecByIndex(uint256 _specId, uint256 _index) public view returns (uint256) {
require(spec.ownerOf(_specId) != address(0));
return mintedObjects[_specId][_index];
}
/// @dev Get specId of DigitalAsset.
/// @param _objectId object identifer
/// @return specId
function specIdOf(uint256 _objectId) public view returns (uint256) {
require(_exists(_objectId));
return digitalAssetObjects[_objectId].specId;
}
/// @dev Get mediaId of DigitalAsset.
/// @param _objectId object identifer
/// @return mediaId
function mediaIdOf(uint256 _objectId) public view returns (string) {
require(_exists(_objectId));
return digitalAssetObjects[_objectId].mediaId;
}
/// @dev Get info of DigitalAsset.
/// @param _objectId object identifer
/// @return info
function infoOf(uint256 _objectId) public view returns (string) {
require(_exists(_objectId));
return digitalAssetObjects[_objectId].info;
}
/// @dev Gets the total amount of objects stored by the contract per spec
/// @param _specId spec identifer
/// @return uint256 representing the total amount of objects per spec
function totalSupplyOf(uint256 _specId) public view returns (uint256) {
require(spec.ownerOf(_specId) != address(0));
return mintedObjects[_specId].length;
}
/// @dev Get objectIndex of DigitalAsset.
/// @param _objectId object identifer
/// @return objectIndex
function objectIndexOf(uint256 _objectId) public view returns (uint256) {
require(_exists(_objectId));
return mintedObjectsIndex[_objectId];
}
/*** INTERNAL FUNCTIONS ***/
/// @dev Internal function to add a object ID to the list of the spec
/// @param _specId uint256 ID of the spec
/// @param _objectId uint256 ID of the token to be added to the tokens list of the given address
function _addObjectTo(uint256 _specId, uint256 _objectId) internal {
mintedObjectsIndex[_objectId] = mintedObjects[_specId].push(_objectId);
}
}
|
contract RightsDigitalAssetObject is IRightsDigitalAssetObject, RDDNControl, ERC721Full {
using SafeMath for uint256;
string internal constant name_ = "RithtsDigitalAssets";
string internal constant symbol_ = "RDA";
/*** DATA TYPES ***/
struct DigitalAssetObject {
uint256 specId; // asset spec id
string mediaId; // media file id
string info; //asset's additional information
}
/*** STORAGE ***/
DigitalAssetObject[] public digitalAssetObjects; // all object list (this index is objectId)
// Mapping from spec ID to index of the minted objects list
mapping(uint256 => uint256[]) private mintedObjects;
// Mapping from object id to position in the minted objects array
mapping(uint256 => uint256) private mintedObjectsIndex;
// // Mapping from spec id to count of owned objects
// mapping(uint256 => mapping(address => uint256)) private ownedObjectCount;
RightsDigitalAssetSpec spec;
/*** CONSTRUCTOR ***/
constructor(address specAddr) ERC721Full(name_, symbol_) public {
spec = RightsDigitalAssetSpec(specAddr);
}
/*** EXTERNAL FUNCTIONS ***/
/// @dev Mint a DigitalAsset.
/// @param _to The address that will own the minted token
/// @param _specId spec identifer
/// @param _mediaId mediaId
/// @param _info info
/// @return objectId
function mint(
address _to,
uint256 _specId,
string _mediaId,
string _info
) public whenNotPaused {
require(spec.ownerOf(_specId) == msg.sender);
// check total supply count
require(
spec.totalSupplyLimitOf(_specId) >= mintedObjects[_specId].length
|| spec.totalSupplyLimitOf(_specId) == 0
);
require(
keccak256(abi.encodePacked(_mediaId)) == keccak256(abi.encodePacked(spec.mediaIdOf(_specId)))
|| keccak256(abi.encodePacked(_mediaId)) == keccak256(abi.encodePacked(""))
);
DigitalAssetObject memory digitalAssetObject = DigitalAssetObject({
specId : _specId,
mediaId: _mediaId,
info: _info
});
uint256 objectId = digitalAssetObjects.push(digitalAssetObject).sub(1);
_mint(_to, objectId);
_addObjectTo(_specId, objectId);
emit Mint(
msg.sender,
objectId,
digitalAssetObject.specId
);
}
/// @dev Set MediaId
/// @param _objectId object identifer
/// @param _mediaId mediaId
function setMediaId(uint256 _objectId, string _mediaId) public whenNotPaused {
require(_exists(_objectId));
DigitalAssetObject storage digitalAsset = digitalAssetObjects[_objectId];
require(spec.ownerOf(digitalAsset.specId) == msg.sender);
require(keccak256(abi.encodePacked(digitalAsset.mediaId)) == keccak256(abi.encodePacked("")));
// set mediaId
digitalAsset.mediaId = _mediaId;
emit SetMediaId(msg.sender, _objectId, digitalAsset.mediaId);
}
/// @dev Get DigitalAsset.
/// @param _objectId object identifer
/// @return object info
function getDigitalAssetObject(uint256 _objectId) public view returns (
uint256 objectId,
uint256 specId,
string mediaId,
string info,
address owner,
uint256 objectIndex
) {
require(_exists(_objectId));
DigitalAssetObject storage digitalAsset = digitalAssetObjects[_objectId];
address objectOwner = ownerOf(_objectId);
return (
_objectId,
digitalAsset.specId,
digitalAsset.mediaId,
digitalAsset.info,
objectOwner,
mintedObjectsIndex[_objectId]
);
}
/// @dev Get DigitalAsset.
/// @param _owner address owning the tokens list to be accessed
/// @param _index uint256 representing the index to be accessed of the requested tokens list
/// @return object info
function getDigitalAssetObject(address _owner, uint256 _index) public view returns (
uint256 objectId,
uint256 specId,
string mediaId,
string info,
address owner,
uint256 objectIndex
) {
uint256 id = tokenOfOwnerByIndex(_owner, _index);
return getDigitalAssetObject(id);
}
/// @dev Get DigitalAsset.
/// @param _specId spec identifer
/// @param _index uint256 representing the index to be accessed of the requested tokens list
/// @return object info
function getDigitalAssetObject(uint256 _specId, uint256 _index) public view returns (
uint256 objectId,
uint256 specId,
string mediaId,
string info,
address owner,
uint256 objectIndex
) {
require(spec.ownerOf(_specId) != address(0));
uint256 id = objectOfSpecByIndex(_specId, _index);
return getDigitalAssetObject(id);
}
/// @dev Gets the token ID at a given index of the tokens list of the requested owner
/// @param _specId spec identifer
/// @param _index uint256 representing the index to be accessed of the requested tokens list
/// @return uint256 token ID at the given index of the tokens list owned by the requested address
function objectOfSpecByIndex(uint256 _specId, uint256 _index) public view returns (uint256) {
require(spec.ownerOf(_specId) != address(0));
return mintedObjects[_specId][_index];
}
/// @dev Get specId of DigitalAsset.
/// @param _objectId object identifer
/// @return specId
function specIdOf(uint256 _objectId) public view returns (uint256) {
require(_exists(_objectId));
return digitalAssetObjects[_objectId].specId;
}
/// @dev Get mediaId of DigitalAsset.
/// @param _objectId object identifer
/// @return mediaId
function mediaIdOf(uint256 _objectId) public view returns (string) {
require(_exists(_objectId));
return digitalAssetObjects[_objectId].mediaId;
}
/// @dev Get info of DigitalAsset.
/// @param _objectId object identifer
/// @return info
function infoOf(uint256 _objectId) public view returns (string) {
require(_exists(_objectId));
return digitalAssetObjects[_objectId].info;
}
/// @dev Gets the total amount of objects stored by the contract per spec
/// @param _specId spec identifer
/// @return uint256 representing the total amount of objects per spec
function totalSupplyOf(uint256 _specId) public view returns (uint256) {
require(spec.ownerOf(_specId) != address(0));
return mintedObjects[_specId].length;
}
/// @dev Get objectIndex of DigitalAsset.
/// @param _objectId object identifer
/// @return objectIndex
function objectIndexOf(uint256 _objectId) public view returns (uint256) {
require(_exists(_objectId));
return mintedObjectsIndex[_objectId];
}
/*** INTERNAL FUNCTIONS ***/
/// @dev Internal function to add a object ID to the list of the spec
/// @param _specId uint256 ID of the spec
/// @param _objectId uint256 ID of the token to be added to the tokens list of the given address
function _addObjectTo(uint256 _specId, uint256 _objectId) internal {
mintedObjectsIndex[_objectId] = mintedObjects[_specId].push(_objectId);
}
}
| 49,462
|
5
|
// validate only guardian can set
|
require(
msg.sender == guardian,
"PriceOracleDispatcher: only guardian may set the address"
);
adapterMockAddress = addressAdapter;
|
require(
msg.sender == guardian,
"PriceOracleDispatcher: only guardian may set the address"
);
adapterMockAddress = addressAdapter;
| 39,613
|
71
|
// Extension of {ERC20} that adds a set of accounts with the {MinterRole},/ See {ERC20-_mint}. Requirements: - the caller must have the {MinterRole}. /
|
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
|
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
| 10,241
|
5
|
// utility functions for uint256 operations /
|
library UintUtils {
error UintUtils__InsufficientHexLength();
bytes16 private constant HEX_SYMBOLS = '0123456789abcdef';
function add(uint256 a, int256 b) internal pure returns (uint256) {
return b < 0 ? sub(a, -b) : a + uint256(b);
}
function sub(uint256 a, int256 b) internal pure returns (uint256) {
return b < 0 ? add(a, -b) : a - uint256(b);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 length = 0;
for (uint256 temp = value; temp != 0; temp >>= 8) {
unchecked {
length++;
}
}
return toHexString(value, length);
}
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
unchecked {
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
}
if (value != 0) revert UintUtils__InsufficientHexLength();
return string(buffer);
}
}
|
library UintUtils {
error UintUtils__InsufficientHexLength();
bytes16 private constant HEX_SYMBOLS = '0123456789abcdef';
function add(uint256 a, int256 b) internal pure returns (uint256) {
return b < 0 ? sub(a, -b) : a + uint256(b);
}
function sub(uint256 a, int256 b) internal pure returns (uint256) {
return b < 0 ? add(a, -b) : a - uint256(b);
}
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 length = 0;
for (uint256 temp = value; temp != 0; temp >>= 8) {
unchecked {
length++;
}
}
return toHexString(value, length);
}
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
unchecked {
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
}
if (value != 0) revert UintUtils__InsufficientHexLength();
return string(buffer);
}
}
| 31,110
|
8
|
// Stores the amount that the admin has mintedThis variable is private because it is not neeeded to be reteived outside of this contract
|
uint16 private adminMintCount;
|
uint16 private adminMintCount;
| 37,702
|
20
|
// Adminable dYdXEIP-1967 Proxy Admin contract. /
|
contract Adminable {
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will revert.
*/
modifier onlyAdmin() {
require(
msg.sender == getAdmin(),
"Adminable: caller is not admin"
);
_;
}
/**
* @return The EIP-1967 proxy admin
*/
function getAdmin()
public
view
returns (address)
{
return address(uint160(uint256(Storage.load(ADMIN_SLOT))));
}
}
|
contract Adminable {
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will revert.
*/
modifier onlyAdmin() {
require(
msg.sender == getAdmin(),
"Adminable: caller is not admin"
);
_;
}
/**
* @return The EIP-1967 proxy admin
*/
function getAdmin()
public
view
returns (address)
{
return address(uint160(uint256(Storage.load(ADMIN_SLOT))));
}
}
| 55,614
|
0
|
// / Highly opinionated token implementation
|
interface IERC20 {
event Approval(address indexed src, address indexed dst, uint256 amt);
event Transfer(address indexed src, address indexed dst, uint256 amt);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address whom) external view returns (uint256);
function allowance(address src, address dst) external view returns (uint256);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
}
|
interface IERC20 {
event Approval(address indexed src, address indexed dst, uint256 amt);
event Transfer(address indexed src, address indexed dst, uint256 amt);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address whom) external view returns (uint256);
function allowance(address src, address dst) external view returns (uint256);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
}
| 15,696
|
88
|
// Initializes the contract by setting a `name` and a `symbol` to the token collection./
|
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
|
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
| 58,341
|
0
|
// ============ Libraries ============
|
using TypedMemView for bytes;
using TypedMemView for bytes29;
using BridgeMessage for bytes29;
|
using TypedMemView for bytes;
using TypedMemView for bytes29;
using BridgeMessage for bytes29;
| 13,995
|
35
|
// NOTE: argument order matters, avoid stack too deep
|
emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, data, proposalCount, msg.sender, memberAddressByDelegateKey[msg.sender]);
proposalCount += 1;
|
emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, data, proposalCount, msg.sender, memberAddressByDelegateKey[msg.sender]);
proposalCount += 1;
| 57,852
|
776
|
// Withdraw `amountInShares` shares from vault
|
uint256 sharePrice = vault.getPricePerFullShare();
uint256 amountInShares = amountInUnderlying.decdiv(sharePrice);
if (amountInShares > 0) {
stakingPool.withdraw(amountInShares);
vault.withdraw(amountInShares);
}
|
uint256 sharePrice = vault.getPricePerFullShare();
uint256 amountInShares = amountInUnderlying.decdiv(sharePrice);
if (amountInShares > 0) {
stakingPool.withdraw(amountInShares);
vault.withdraw(amountInShares);
}
| 13,475
|
133
|
// = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
|
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
)
);
|
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
)
);
| 71,630
|
74
|
// Check whether a valid quantity of listed tokens is being bought.
|
require(
_listing.quantity > 0 && _quantityToBuy > 0 && _quantityToBuy <= _listing.quantity,
"Marketplace: buying invalid amount of tokens."
);
|
require(
_listing.quantity > 0 && _quantityToBuy > 0 && _quantityToBuy <= _listing.quantity,
"Marketplace: buying invalid amount of tokens."
);
| 3,396
|
65
|
// SGR sell Wallets Trading Limiter. /
|
contract SGRSellWalletsTradingLimiter is SGRWalletsTradingLimiter {
string public constant VERSION = "2.0.0";
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) SGRWalletsTradingLimiter(_contractAddressLocator, _SellWalletsTradingDataSource_) public {}
/**
* @dev Get the wallet override trade-limit and class.
* @return The wallet override trade-limit and class.
*/
function getOverrideTradeLimitAndClass(address _wallet) public view returns (uint256, uint256){
return getAuthorizationDataSource().getSellTradeLimitAndClass(_wallet);
}
/**
* @dev Get the wallet trade-limit.
* @return The wallet trade-limit.
*/
function getTradeLimit(uint256 _tradeClassId) public view returns (uint256){
return getTradingClasses().getSellLimit(_tradeClassId);
}
}
|
contract SGRSellWalletsTradingLimiter is SGRWalletsTradingLimiter {
string public constant VERSION = "2.0.0";
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) SGRWalletsTradingLimiter(_contractAddressLocator, _SellWalletsTradingDataSource_) public {}
/**
* @dev Get the wallet override trade-limit and class.
* @return The wallet override trade-limit and class.
*/
function getOverrideTradeLimitAndClass(address _wallet) public view returns (uint256, uint256){
return getAuthorizationDataSource().getSellTradeLimitAndClass(_wallet);
}
/**
* @dev Get the wallet trade-limit.
* @return The wallet trade-limit.
*/
function getTradeLimit(uint256 _tradeClassId) public view returns (uint256){
return getTradingClasses().getSellLimit(_tradeClassId);
}
}
| 10,399
|
14
|
// BlockHash only works for the most 256 recent blocks.
|
uint256 _block_shift = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
_block_shift = 1 + (_block_shift % 255);
|
uint256 _block_shift = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
_block_shift = 1 + (_block_shift % 255);
| 6,896
|
851
|
// set the FeePool contract as it is the only authority to be able to callappendVestingEntry with the onlyFeePool modifer /
|
function setFeePool(IFeePool _feePool) external onlyOwner {
feePool = _feePool;
emit FeePoolUpdated(address(_feePool));
}
|
function setFeePool(IFeePool _feePool) external onlyOwner {
feePool = _feePool;
emit FeePoolUpdated(address(_feePool));
}
| 34,395
|
19
|
// function to submit the CID of the manuscript uploaded on IPFS paramater is the unique CID generated when a document is uploaded on IPFS
|
function submitManuscript(
uint256 _cid,
string memory _title,
string memory _area,
string memory _publisher,
string memory _journal
|
function submitManuscript(
uint256 _cid,
string memory _title,
string memory _area,
string memory _publisher,
string memory _journal
| 6,742
|
2
|
// Vote to remove a keyholder and strip their voting/attesting power. The associated hash in `attestations` will be of the address of the keyholder they are voting to remove.
|
VOTE_TO_REMOVE_KEYHOLDER,
|
VOTE_TO_REMOVE_KEYHOLDER,
| 28,848
|
36
|
// Update payout
|
if (config.payoutAddress != address(0)) {
_updatePayoutAddress(config.payoutAddress);
}
|
if (config.payoutAddress != address(0)) {
_updatePayoutAddress(config.payoutAddress);
}
| 30,981
|
481
|
// Internal function calculating the market index with the shortest maturity that was at least minAmountToMaturity seconds still return uint256 result, the minimum market index the strategy should be entering positions intoreturn uint256 maturity, the minimum market index's maturity the strategy should be entering positions into /
|
function _getMinimumMarketIndex() internal view returns(uint256, uint256) {
MarketParameters[] memory _activeMarkets = nProxy.getActiveMarkets(currencyID);
for(uint256 i = 0; i<_activeMarkets.length; i++) {
if (_activeMarkets[i].maturity - block.timestamp >= minTimeToMaturity) {
return (i+1, uint256(_activeMarkets[i].maturity));
}
}
}
|
function _getMinimumMarketIndex() internal view returns(uint256, uint256) {
MarketParameters[] memory _activeMarkets = nProxy.getActiveMarkets(currencyID);
for(uint256 i = 0; i<_activeMarkets.length; i++) {
if (_activeMarkets[i].maturity - block.timestamp >= minTimeToMaturity) {
return (i+1, uint256(_activeMarkets[i].maturity));
}
}
}
| 2,387
|
245
|
// Deposit all want in sushi chef
|
ISushiChef(chef).deposit(pid, _want);
|
ISushiChef(chef).deposit(pid, _want);
| 83,215
|
103
|
// Pool state that never changes/These parameters are fixed for a pool forever, i.e., the methods will always return the same values
|
interface IUniswapV3PoolImmutables {
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
}
|
interface IUniswapV3PoolImmutables {
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
}
| 21,594
|
27
|
// 锁仓截止日期2
|
uint256 public stepTwoLockEndTime;
|
uint256 public stepTwoLockEndTime;
| 34,555
|
14
|
// Returns the creation code that will result in a contract being deployed with `constructorArgs`. /
|
function _getCreationCodeWithArgs(bytes memory constructorArgs)
private
view
returns (bytes memory code)
|
function _getCreationCodeWithArgs(bytes memory constructorArgs)
private
view
returns (bytes memory code)
| 27,296
|
1
|
// Provides a safe ERC20.symbol version which returns '???' as fallback string./token The address of the ERC-20 token contract./ return (string) Token symbol.
|
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
|
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
| 38,318
|
10
|
// for switching off auction creations, bids and withdrawals
|
bool public isPaused;
|
bool public isPaused;
| 27,953
|
695
|
// Calculate rebalance amount for provide liquidity/wadMiltonErc20BalanceAfterDeposit Milton erc20 balance in wad, Notice: this is balance after provide liquidity operation!/vaultBalance Vault balance in wad, Stanley's accrued balance.
|
function _calculateRebalanceAmountAfterProvideLiquidity(
uint256 wadMiltonErc20BalanceAfterDeposit,
uint256 vaultBalance
|
function _calculateRebalanceAmountAfterProvideLiquidity(
uint256 wadMiltonErc20BalanceAfterDeposit,
uint256 vaultBalance
| 31,474
|
2
|
// require it has enough tokens
|
require(token.balanceOf(address(this))>=tokenAmount);
token.transfer(msg.sender, tokenAmount);
|
require(token.balanceOf(address(this))>=tokenAmount);
token.transfer(msg.sender, tokenAmount);
| 6,321
|
14
|
// Structs/
|
struct TokenInfo {
uint pos; // 0 mens unregistered; if > 0, pos + 1 is the
// token's position in `addresses`.
string symbol; // Symbol of the token
}
|
struct TokenInfo {
uint pos; // 0 mens unregistered; if > 0, pos + 1 is the
// token's position in `addresses`.
string symbol; // Symbol of the token
}
| 30,750
|
56
|
// Freeze the account _accounts Given accounts executed by CRM /
|
function freeze(address[] _accounts) public onlyOwnerOrManager {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
uint i;
for (i = 0; i < _accounts.length; i++) {
require(_accounts[i] != address(0), "Zero address");
require(_accounts[i] != base_wallet, "Freeze self");
}
for (i = 0; i < _accounts.length; i++) {
token.freeze(_accounts[i]);
}
}
|
function freeze(address[] _accounts) public onlyOwnerOrManager {
require(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED, "Bad phase");
uint i;
for (i = 0; i < _accounts.length; i++) {
require(_accounts[i] != address(0), "Zero address");
require(_accounts[i] != base_wallet, "Freeze self");
}
for (i = 0; i < _accounts.length; i++) {
token.freeze(_accounts[i]);
}
}
| 41,616
|
249
|
// Gets the DMM token contract address for the provided DMM token ID. For example, `1` returns the mToken contract address for that token ID. /
|
function getDmmTokenAddressByDmmTokenId(uint dmmTokenId) external view returns (address);
|
function getDmmTokenAddressByDmmTokenId(uint dmmTokenId) external view returns (address);
| 2,495
|
67
|
// Buys single token to an address specified. Accepts ETH as payment and mints a token_to address to mint token to /
|
function buySingleTo(address _to) public payable {
// verify the inputs and transaction value
require(_to != address(0), "recipient not set");
require(msg.value >= itemPrice, "not enough funds");
// verify mint limit
if(mintLimit != 0) {
require(mints[msg.sender] + 1 <= mintLimit, "mint limit reached");
}
// verify sale is in active state
require(isActive(), "inactive sale");
// mint token to the recipient
IMintableERC721(tokenContract).mint(_to, nextId);
// increment `nextId`
nextId++;
// increment `soldCounter`
soldCounter++;
// increment sender mints
mints[msg.sender]++;
// if ETH amount supplied exceeds the price
if(msg.value > itemPrice) {
// send excess amount back to sender
payable(msg.sender).transfer(msg.value - itemPrice);
}
// emit en event
emit Bought(msg.sender, _to, 1, itemPrice);
}
|
function buySingleTo(address _to) public payable {
// verify the inputs and transaction value
require(_to != address(0), "recipient not set");
require(msg.value >= itemPrice, "not enough funds");
// verify mint limit
if(mintLimit != 0) {
require(mints[msg.sender] + 1 <= mintLimit, "mint limit reached");
}
// verify sale is in active state
require(isActive(), "inactive sale");
// mint token to the recipient
IMintableERC721(tokenContract).mint(_to, nextId);
// increment `nextId`
nextId++;
// increment `soldCounter`
soldCounter++;
// increment sender mints
mints[msg.sender]++;
// if ETH amount supplied exceeds the price
if(msg.value > itemPrice) {
// send excess amount back to sender
payable(msg.sender).transfer(msg.value - itemPrice);
}
// emit en event
emit Bought(msg.sender, _to, 1, itemPrice);
}
| 1,722
|
202
|
// An index of contracts that are allowed to mint new tokens. /
|
mapping(address => bool) public minters;
|
mapping(address => bool) public minters;
| 71,581
|
171
|
// List of tokens that cluster holds, called underlyings./Order of addresses is important, as it corresponds with the order in underlyingsShares.
|
address[] public underlyings;
|
address[] public underlyings;
| 42,495
|
29
|
// or 0-9
|
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
|
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
| 28,591
|
133
|
// Sets liquidationIncentiveAdmin function to set liquidationIncentivenewLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 return uint 0=success, otherwise a failure. (See ErrorReporter for details)/
|
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
|
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
| 27,557
|
9
|
// total number of tokens in existence/
|
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
|
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
| 2,881
|
9
|
// ChainlinkScheduler Giancarlo Sanchez Orchestrator for yield distribution and prize pool. /
|
contract ChainlinkScheduler is ChainlinkClient {
bytes32 public currentRequestId;
uint256 public timer = 0;
uint256 public cycles = 0;
address public yieldContractAddress;
address public poolContractAddress;
uint256 public currentCycle;
ChainlinkConfiguration private configuration = new ChainlinkConfiguration();
/**
* Constructor, utilizes ChainlinkConfiguration.sol for data
*/
constructor() public {
setPublicChainlinkToken();
}
/**
* Set timer in seconds for yield distribution and prize pool
**/
function configureSchedule(
uint256 intervalSeconds,
uint256 intervalsPerCycle,
address yieldDistrbutionContractAddress,
address prizePoolDistributionContractAddress
) public {
timer = intervalSeconds;
cycles = intervalsPerCycle;
currentCycle = cycles;
yieldContractAddress = yieldDistrbutionContractAddress;
poolContractAddress = prizePoolDistributionContractAddress;
}
/**
* Create a Chainlink request to start an alarm and after
* the time in seconds is up, return throught the fulfillAlarm
* function
*/
function startTimer() public returns (bytes32 requestId) {
require(timer > 0, "Timer must be set and different than zero");
require(cycles > 0, "Cycles must be set and different than zero");
Chainlink.Request memory request = buildChainlinkRequest(configuration.getJobIdScheduler(), address(this), this.fulfillAlarm.selector);
request.addUint("until", block.timestamp + timer);
currentRequestId = sendChainlinkRequestTo(configuration.getOracle(), request, configuration.getFee());
return getCurrentRequestId();
}
/**
* Get current Chainlink alarm oracle request identifier
**/
function getCurrentRequestId() public view returns (bytes32 requestId) {
return currentRequestId;
}
/**
* Receive the response in the form of uint256
*/
function fulfillAlarm(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId)
{
// Distribute yield
IStakingToken(yieldContractAddress).distributeInterests();
currentCycle -= 1;
if (currentCycle == 0) {
currentCycle = cycles;
// Distribute prize
IWinnerPicker(poolContractAddress).pickWinner(_volume);
}
// Loop again next cycle
startTimer();
}
}
|
contract ChainlinkScheduler is ChainlinkClient {
bytes32 public currentRequestId;
uint256 public timer = 0;
uint256 public cycles = 0;
address public yieldContractAddress;
address public poolContractAddress;
uint256 public currentCycle;
ChainlinkConfiguration private configuration = new ChainlinkConfiguration();
/**
* Constructor, utilizes ChainlinkConfiguration.sol for data
*/
constructor() public {
setPublicChainlinkToken();
}
/**
* Set timer in seconds for yield distribution and prize pool
**/
function configureSchedule(
uint256 intervalSeconds,
uint256 intervalsPerCycle,
address yieldDistrbutionContractAddress,
address prizePoolDistributionContractAddress
) public {
timer = intervalSeconds;
cycles = intervalsPerCycle;
currentCycle = cycles;
yieldContractAddress = yieldDistrbutionContractAddress;
poolContractAddress = prizePoolDistributionContractAddress;
}
/**
* Create a Chainlink request to start an alarm and after
* the time in seconds is up, return throught the fulfillAlarm
* function
*/
function startTimer() public returns (bytes32 requestId) {
require(timer > 0, "Timer must be set and different than zero");
require(cycles > 0, "Cycles must be set and different than zero");
Chainlink.Request memory request = buildChainlinkRequest(configuration.getJobIdScheduler(), address(this), this.fulfillAlarm.selector);
request.addUint("until", block.timestamp + timer);
currentRequestId = sendChainlinkRequestTo(configuration.getOracle(), request, configuration.getFee());
return getCurrentRequestId();
}
/**
* Get current Chainlink alarm oracle request identifier
**/
function getCurrentRequestId() public view returns (bytes32 requestId) {
return currentRequestId;
}
/**
* Receive the response in the form of uint256
*/
function fulfillAlarm(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId)
{
// Distribute yield
IStakingToken(yieldContractAddress).distributeInterests();
currentCycle -= 1;
if (currentCycle == 0) {
currentCycle = cycles;
// Distribute prize
IWinnerPicker(poolContractAddress).pickWinner(_volume);
}
// Loop again next cycle
startTimer();
}
}
| 37,849
|
5
|
// ----------MODIFIERS--------------------
|
modifier byPlayer(){
require(msg.sender != notary);
_;
}
|
modifier byPlayer(){
require(msg.sender != notary);
_;
}
| 33,794
|
28
|
// Update the price for rerolling radbro art. /
|
function setRadrollPrice(uint128 _radrollPrice) external onlyOwner {
radrollPrice = _radrollPrice;
}
|
function setRadrollPrice(uint128 _radrollPrice) external onlyOwner {
radrollPrice = _radrollPrice;
}
| 38,813
|
7
|
// Add ETH reward to the staking pool/ntoken The address of NToken
|
function addETHReward(address ntoken) external payable;
|
function addETHReward(address ntoken) external payable;
| 17,388
|
27
|
// Event: 移転承認
|
event ApproveTransfer(
uint256 indexed index,
address from,
address to,
string data
);
|
event ApproveTransfer(
uint256 indexed index,
address from,
address to,
string data
);
| 43,248
|
11
|
// Update the treeBalances and treeOwner mappings We add the tree to the same array position to find it easier
|
ownerTreesIds[defaultTreesOwner].push(newTreeId);
treeDetails[newTreeId] = newTree;
treesOnSale.push(newTreeId);
totalTreePower += defaultTreesPower;
|
ownerTreesIds[defaultTreesOwner].push(newTreeId);
treeDetails[newTreeId] = newTree;
treesOnSale.push(newTreeId);
totalTreePower += defaultTreesPower;
| 49,297
|
138
|
// Encodes the argument json bytes into base64-data uri format/json Raw json to base64 and turn into a data-uri
|
function encodeMetadataJSON(bytes memory json)
public
pure
override
returns (string memory)
{
return
string(
abi.encodePacked(
"data:application/json;base64,",
|
function encodeMetadataJSON(bytes memory json)
public
pure
override
returns (string memory)
{
return
string(
abi.encodePacked(
"data:application/json;base64,",
| 42,404
|
523
|
// Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, or to insert a new one replacing the old.
|
uint256 private constant _MASK_1 = 2**(1) - 1;
uint256 private constant _MASK_10 = 2**(10) - 1;
uint256 private constant _MASK_22 = 2**(22) - 1;
uint256 private constant _MASK_31 = 2**(31) - 1;
uint256 private constant _MASK_53 = 2**(53) - 1;
uint256 private constant _MASK_64 = 2**(64) - 1;
|
uint256 private constant _MASK_1 = 2**(1) - 1;
uint256 private constant _MASK_10 = 2**(10) - 1;
uint256 private constant _MASK_22 = 2**(22) - 1;
uint256 private constant _MASK_31 = 2**(31) - 1;
uint256 private constant _MASK_53 = 2**(53) - 1;
uint256 private constant _MASK_64 = 2**(64) - 1;
| 15,089
|
96
|
// Capture BAL tokens or any other tokens
|
function capture(address _token, uint amount) onlyOwner external {
require(_token != address(_token0), "capture: can not capture staking tokens");
require(_token != address(_token1), "capture: can not capture reward tokens");
require(beneficial != address(this), "capture: can not send to self");
require(beneficial != address(0), "capture: can not burn tokens");
IERC20(_token).safeTransfer(beneficial, amount);
}
|
function capture(address _token, uint amount) onlyOwner external {
require(_token != address(_token0), "capture: can not capture staking tokens");
require(_token != address(_token1), "capture: can not capture reward tokens");
require(beneficial != address(this), "capture: can not send to self");
require(beneficial != address(0), "capture: can not burn tokens");
IERC20(_token).safeTransfer(beneficial, amount);
}
| 58,609
|
32
|
// states - waiting, initial state - collecting, after waiting, before collection stopped - failed, after collecting, if softcap missed - closed, after collecting, if softcap reached - complete, after closed or failed, when job done
|
enum EventState { Waiting, Collecting, Closed, Failed, Complete }
EventState public state;
uint256 public RATE_FACTOR = 1000000;
// Terms
uint256 public startTime;
uint256 public minDuration;
uint256 public maxDuration;
uint256 public softCap;
uint256 public hardCap;
uint256 public discountRate; // if rate 30%, this will be 300,000
uint256 public amountPower;
address[] public milestoneRecipients;
uint256[] public milestoneShares;
// Params
address public controllerAddr;
address public powerAddr;
address public nutzAddr;
uint256 public initialReserve;
uint256 public initialSupply;
function PowerEvent(address _controllerAddr, uint256 _startTime, uint256 _minDuration, uint256 _maxDuration, uint256 _softCap, uint256 _hardCap, uint256 _discount, uint256 _amountPower, address[] _milestoneRecipients, uint256[] _milestoneShares)
areValidMileStones(_milestoneRecipients, _milestoneShares) {
require(_minDuration <= _maxDuration);
require(_softCap <= _hardCap);
controllerAddr = _controllerAddr;
startTime = _startTime;
minDuration = _minDuration;
maxDuration = _maxDuration;
softCap = _softCap;
hardCap = _hardCap;
discountRate = _discount;
amountPower = _amountPower;
state = EventState.Waiting;
milestoneRecipients = _milestoneRecipients;
milestoneShares = _milestoneShares;
}
|
enum EventState { Waiting, Collecting, Closed, Failed, Complete }
EventState public state;
uint256 public RATE_FACTOR = 1000000;
// Terms
uint256 public startTime;
uint256 public minDuration;
uint256 public maxDuration;
uint256 public softCap;
uint256 public hardCap;
uint256 public discountRate; // if rate 30%, this will be 300,000
uint256 public amountPower;
address[] public milestoneRecipients;
uint256[] public milestoneShares;
// Params
address public controllerAddr;
address public powerAddr;
address public nutzAddr;
uint256 public initialReserve;
uint256 public initialSupply;
function PowerEvent(address _controllerAddr, uint256 _startTime, uint256 _minDuration, uint256 _maxDuration, uint256 _softCap, uint256 _hardCap, uint256 _discount, uint256 _amountPower, address[] _milestoneRecipients, uint256[] _milestoneShares)
areValidMileStones(_milestoneRecipients, _milestoneShares) {
require(_minDuration <= _maxDuration);
require(_softCap <= _hardCap);
controllerAddr = _controllerAddr;
startTime = _startTime;
minDuration = _minDuration;
maxDuration = _maxDuration;
softCap = _softCap;
hardCap = _hardCap;
discountRate = _discount;
amountPower = _amountPower;
state = EventState.Waiting;
milestoneRecipients = _milestoneRecipients;
milestoneShares = _milestoneShares;
}
| 41,890
|
59
|
// Load the rune into the MSBs of b
|
assembly {
word := mload(mload(add(self, 32)))
}
|
assembly {
word := mload(mload(add(self, 32)))
}
| 33,101
|
442
|
// checks if a user is allowed to borrow at a stable rate_reserve the reserve address_user the user_amount the amount the the user wants to borrow return true if the user is allowed to borrow at a stable rate, false otherwise/
|
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (!reserve.isStableBorrowRateEnabled) return false;
return
!user.useAsCollateral ||
!reserve.usageAsCollateralEnabled ||
_amount > getUserUnderlyingAssetBalance(_reserve, _user);
}
|
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (!reserve.isStableBorrowRateEnabled) return false;
return
!user.useAsCollateral ||
!reserve.usageAsCollateralEnabled ||
_amount > getUserUnderlyingAssetBalance(_reserve, _user);
}
| 81,142
|
19
|
// Change the symbol of the token. Only the owner may call this.
|
function changeSymbol(string calldata _newSymbol)
onlyOwner()
external
|
function changeSymbol(string calldata _newSymbol)
onlyOwner()
external
| 26,497
|
28
|
// Gets the maximum amount of MATIC a user could deposit into the vault./ return The amount of MATIC.
|
function maxDeposit(address) public view override returns (uint256) {
return cap - totalStaked();
}
|
function maxDeposit(address) public view override returns (uint256) {
return cap - totalStaked();
}
| 13,305
|
32
|
// See _setStages /
|
function setStages(StageData[] calldata stages, uint256 startId) external {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert UnauthorisedUser();
_setStages(stages, startId);
}
|
function setStages(StageData[] calldata stages, uint256 startId) external {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert UnauthorisedUser();
_setStages(stages, startId);
}
| 25,997
|
9
|
// binds a token to the compliance contract_token address of the token to bind Emits a TokenBound event /
|
function bindToken(address _token) external;
|
function bindToken(address _token) external;
| 30,319
|
4
|
// Enable recovery of ether sent by mistake to this contract's address.
|
function drainStrayEther(uint _amount)
external
onlyBeneficiary
returns (bool)
|
function drainStrayEther(uint _amount)
external
onlyBeneficiary
returns (bool)
| 20,546
|
10
|
// only vest those accounts that are not yet vested. We dont want to merge vestings
|
if(_vesting[accounts[i]].vestingAmount == 0) {
_vestedBalance += amounts[i];
_vesting[accounts[i]] = VestingParams(amounts[i], _vestingDuration, 0);
emit Vested(accounts[i], amounts[i], _vestingDuration);
}
|
if(_vesting[accounts[i]].vestingAmount == 0) {
_vestedBalance += amounts[i];
_vesting[accounts[i]] = VestingParams(amounts[i], _vestingDuration, 0);
emit Vested(accounts[i], amounts[i], _vestingDuration);
}
| 49,023
|
69
|
// Function for allowing bidder to unlock his ERC1155s in case of buyout success/ERC1155s can be accumulated by the underlying ERC721 in the vault as royalty or airdrops /_asset the address of asset to be unlocked/_assetID the ID of asset to be unlocked/_to the address where unlocked NFT will be sent
|
function withdrawERC1155(address _asset, uint256 _assetID, address _to) external override boughtOut {
require(msg.sender == bidder, "NibblVault: Only winner");
uint256 balance = IERC1155(_asset).balanceOf(address(this), _assetID);
IERC1155(_asset).safeTransferFrom(address(this), _to, _assetID, balance, "0");
}
|
function withdrawERC1155(address _asset, uint256 _assetID, address _to) external override boughtOut {
require(msg.sender == bidder, "NibblVault: Only winner");
uint256 balance = IERC1155(_asset).balanceOf(address(this), _assetID);
IERC1155(_asset).safeTransferFrom(address(this), _to, _assetID, balance, "0");
}
| 43,555
|
83
|
// 28 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT
|
string inPI_edit_28 = " une première phrase " ;
|
string inPI_edit_28 = " une première phrase " ;
| 69,744
|
50
|
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that the target address contains contract code and also asserts for success in the low-level call.
|
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
|
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
| 303
|
29
|
// function balanceOf(address _owner) view returns (uint256 balance) EIP
|
return balances[_owner];
|
return balances[_owner];
| 4,016
|
55
|
// Fee Whitelist
|
mapping(address => bool) public feelessSender;
mapping(address => bool) public feelessReciever;
|
mapping(address => bool) public feelessSender;
mapping(address => bool) public feelessReciever;
| 17,184
|
33
|
// Returns price that the sender is selling the current sig for (or 0 if not)
|
function getMySalePrice(bytes32 sig) public view returns (uint256) {
return _addressToSigToSalePrice[msg.sender][sig];
}
|
function getMySalePrice(bytes32 sig) public view returns (uint256) {
return _addressToSigToSalePrice[msg.sender][sig];
}
| 43,538
|
131
|
// Claim rewards and swaps them to FXS for restaking/Can be called by anyone against an incentive in FXS/Harvest logic in the strategy contract
|
function harvest() public {
uint256 _harvested = IStrategy(strategy).harvest(msg.sender);
emit Harvest(msg.sender, _harvested);
}
|
function harvest() public {
uint256 _harvested = IStrategy(strategy).harvest(msg.sender);
emit Harvest(msg.sender, _harvested);
}
| 63,004
|
124
|
// Reverts if the request is already pending requestId The request ID for fulfillment /
|
modifier notPendingRequest(bytes32 requestId) {
require(s_pendingRequests[requestId] == address(0), "Request is already pending");
_;
}
|
modifier notPendingRequest(bytes32 requestId) {
require(s_pendingRequests[requestId] == address(0), "Request is already pending");
_;
}
| 35,253
|
324
|
// Token Ids that will determine the VIPs (using ownerof)
|
uint256 [] private VIPTokens;
bool private VIPTokensSet=false;
|
uint256 [] private VIPTokens;
bool private VIPTokensSet=false;
| 76,605
|
28
|
// TotalSupply of vote token which must be implemented through inheritance. /
|
function totalSupply() public view virtual returns (uint256);
|
function totalSupply() public view virtual returns (uint256);
| 8,814
|
20
|
// Loop over all ilks
|
IlkRegistryAbstract registry = IlkRegistryAbstract(ILK_REGISTRY);
bytes32[] memory ilks = registry.list();
for (uint i = 0; i < ilks.length; i++) {
|
IlkRegistryAbstract registry = IlkRegistryAbstract(ILK_REGISTRY);
bytes32[] memory ilks = registry.list();
for (uint i = 0; i < ilks.length; i++) {
| 47,494
|
114
|
// Returns bounds for value of binaryLog(x) given x/x logarithm argument in fixed point
|
/// @return {
/// "lower": "lower bound of binaryLog(x) in fixed point",
/// "upper": "upper bound of binaryLog(x) in fixed point"
/// }
|
/// @return {
/// "lower": "lower bound of binaryLog(x) in fixed point",
/// "upper": "upper bound of binaryLog(x) in fixed point"
/// }
| 49,060
|
6
|
// Modifier that only allows account that is not linked to identity. /
|
modifier onlyUnlinkedAccount(bytes32 account) {
require(
identities[account] == address(0),
"Account is linked to an identity"
);
_;
}
|
modifier onlyUnlinkedAccount(bytes32 account) {
require(
identities[account] == address(0),
"Account is linked to an identity"
);
_;
}
| 36,928
|
50
|
// Bilateral escrow for ETH and ERC-20/721 tokens with BentoBox integration./LexDAO LLC.
|
contract LexLocker {
IBentoBoxMinimal immutable bento;
address public lexDAO;
address immutable wETH;
uint256 lockerCount;
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant INVOICE_HASH = keccak256("DepositInvoiceSig(address depositor,address receiver,address resolver,string details)");
mapping(uint256 => string) public agreements;
mapping(uint256 => Locker) public lockers;
mapping(address => Resolver) public resolvers;
constructor(IBentoBoxMinimal _bento, address _lexDAO, address _wETH) {
bento = _bento;
bento.registerProtocol();
lexDAO = _lexDAO;
wETH = _wETH;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("LexLocker")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
/// @dev Events to assist web3 applications.
event Deposit(
bool bento,
bool nft,
address indexed depositor,
address indexed receiver,
address resolver,
address token,
uint256 value,
uint256 indexed registration,
string details);
event DepositInvoiceSig(address indexed depositor, address indexed receiver);
event Release(uint256 indexed registration);
event Withdraw(uint256 indexed registration);
event Lock(uint256 indexed registration, string details);
event Resolve(uint256 indexed registration, uint256 indexed depositorAward, uint256 indexed receiverAward, string details);
event RegisterResolver(address indexed resolver, bool indexed active, uint256 indexed fee);
event RegisterAgreement(uint256 indexed index, string agreement);
event UpdateLexDAO(address indexed lexDAO);
/// @dev Tracks registered escrow status.
struct Locker {
bool bento;
bool nft;
bool locked;
address depositor;
address receiver;
address resolver;
address token;
uint256 value;
uint256 termination;
}
/// @dev Tracks registered resolver status.
struct Resolver {
bool active;
uint8 fee;
}
// **** ESCROW PROTOCOL **** //
// ------------------------ //
/// @notice Deposits tokens (ERC-20/721) into escrow
// - locked funds can be released by `msg.sender` `depositor`
// - both parties can {lock} for `resolver`.
/// @param receiver The account that receives funds.
/// @param resolver The account that unlock funds.
/// @param token The asset used for funds.
/// @param value The amount of funds - if `nft`, the 'tokenId' in first value is used.
/// @param termination Unix time upon which `depositor` can claim back funds.
/// @param nft If 'false', ERC-20 is assumed, otherwise, non-fungible asset.
/// @param details Describes context of escrow - stamped into event.
function deposit(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool nft,
string memory details
) public payable returns (uint256 registration) {
require(resolvers[resolver].active, "resolver not active");
require(resolver != msg.sender && resolver != receiver, "resolver cannot be party"); /// @dev Avoid conflicts.
/// @dev Handle ETH/ERC-20/721 deposit.
if (msg.value != 0) {
require(msg.value == value, "wrong msg.value");
/// @dev Overrides to clarify ETH is used.
if (token != address(0)) token = address(0);
if (nft) nft = false;
} else {
safeTransferFrom(token, msg.sender, address(this), value);
}
/// @dev Increment registered lockers and assign # to escrow deposit.
unchecked {
lockerCount++;
}
registration = lockerCount;
lockers[registration] = Locker(false, nft, false, msg.sender, receiver, resolver, token, value, termination);
emit Deposit(false, nft, msg.sender, receiver, resolver, token, value, registration, details);
}
/// @notice Deposits tokens (ERC-20/721) into BentoBox escrow
// - locked funds can be released by `msg.sender` `depositor`
// - both parties can {lock} for `resolver`.
/// @param receiver The account that receives funds.
/// @param resolver The account that unlock funds.
/// @param token The asset used for funds (note: NFT not supported in BentoBox).
/// @param value The amount of funds (note: locker converts to 'shares').
/// @param termination Unix time upon which `depositor` can claim back funds.
/// @param wrapBento If 'false', raw ERC-20 is assumed, otherwise, BentoBox 'shares'.
/// @param details Describes context of escrow - stamped into event.
function depositBento(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool wrapBento,
string memory details
) public payable returns (uint256 registration) {
require(resolvers[resolver].active, "resolver not active");
require(resolver != msg.sender && resolver != receiver, "resolver cannot be party"); /// @dev Avoid conflicts.
/// @dev Handle ETH/ERC-20 deposit.
if (msg.value != 0) {
require(msg.value == value, "wrong msg.value");
/// @dev Override to clarify wETH is used in BentoBox for ETH.
if (token != wETH) token = wETH;
(, value) = bento.deposit{value: msg.value}(address(0), address(this), address(this), msg.value, 0);
} else if (wrapBento) {
safeTransferFrom(token, msg.sender, address(bento), value);
(, value) = bento.deposit(token, address(bento), address(this), value, 0);
} else {
bento.transfer(token, msg.sender, address(this), value);
}
/// @dev Increment registered lockers and assign # to escrow deposit.
unchecked {
lockerCount++;
}
registration = lockerCount;
lockers[registration] = Locker(true, false, false, msg.sender, receiver, resolver, token, value, termination);
emit Deposit(true, false, msg.sender, receiver, resolver, token, value, registration, details);
}
/// @notice Validates deposit request 'invoice' for locker escrow.
/// @param receiver The account that receives funds.
/// @param resolver The account that unlock funds.
/// @param token The asset used for funds.
/// @param value The amount of funds - if `nft`, the 'tokenId'.
/// @param termination Unix time upon which `depositor` can claim back funds.
/// @param bentoBoxed If 'false', regular deposit is assumed, otherwise, BentoBox.
/// @param nft If 'false', ERC-20 is assumed, otherwise, non-fungible asset.
/// @param wrapBento If 'false', raw ERC-20 is assumed, otherwise, BentoBox 'shares'.
/// @param details Describes context of escrow - stamped into event.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function depositInvoiceSig(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool bentoBoxed,
bool nft,
bool wrapBento,
string memory details,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
/// @dev Validate basic elements of invoice.
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
INVOICE_HASH,
msg.sender,
receiver,
resolver,
details
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress == receiver, "invalid invoice");
/// @dev Perform deposit.
if (!bentoBoxed) {
deposit(receiver, resolver, token, value, termination, nft, details);
} else {
depositBento(receiver, resolver, token, value, termination, wrapBento, details);
}
emit DepositInvoiceSig(msg.sender, receiver);
}
/// @notice Releases escrowed assets to designated `receiver`
// - can only be called by `depositor` if not `locked`
// - can be called after `termination` as optional extension.
/// @param registration The index of escrow deposit.
function release(uint256 registration) external {
Locker storage locker = lockers[registration];
require(!locker.locked, "locked");
require(msg.sender == locker.depositor, "not depositor");
/// @dev Handle asset transfer.
if (locker.token == address(0)) { /// @dev Release ETH.
safeTransferETH(locker.receiver, locker.value);
} else if (locker.bento) { /// @dev Release BentoBox shares.
bento.transfer(locker.token, address(this), locker.receiver, locker.value);
} else if (!locker.nft) { /// @dev Release ERC-20.
safeTransfer(locker.token, locker.receiver, locker.value);
} else { /// @dev Release NFT.
safeTransferFrom(locker.token, address(this), locker.receiver, locker.value);
}
delete lockers[registration];
emit Release(registration);
}
/// @notice Releases escrowed assets back to designated `depositor`
// - can only be called by `depositor` if `termination` reached.
/// @param registration The index of escrow deposit.
function withdraw(uint256 registration) external {
Locker storage locker = lockers[registration];
require(msg.sender == locker.depositor, "not depositor");
require(!locker.locked, "locked");
require(block.timestamp >= locker.termination, "not terminated");
/// @dev Handle asset transfer.
if (locker.token == address(0)) { /// @dev Release ETH.
safeTransferETH(locker.depositor, locker.value);
} else if (locker.bento) { /// @dev Release BentoBox shares.
bento.transfer(locker.token, address(this), locker.depositor, locker.value);
} else if (!locker.nft) { /// @dev Release ERC-20.
safeTransfer(locker.token, locker.depositor, locker.value);
} else { /// @dev Release NFT.
safeTransferFrom(locker.token, address(this), locker.depositor, locker.value);
}
delete lockers[registration];
emit Withdraw(registration);
}
// **** DISPUTE PROTOCOL **** //
// ------------------------- //
/// @notice Locks escrowed assets for resolution - can only be called by locker parties.
/// @param registration The index of escrow deposit.
/// @param details Description of lock action (note: can link to secure dispute details, etc.).
function lock(uint256 registration, string calldata details) external {
Locker storage locker = lockers[registration];
require(msg.sender == locker.depositor || msg.sender == locker.receiver, "not party");
locker.locked = true;
emit Lock(registration, details);
}
/// @notice Resolves locked escrow deposit in split between parties - if NFT, must be complete award (so, one party receives '0')
// - `resolverFee` is automatically deducted from both parties' awards.
/// @param registration The registration index of escrow deposit.
/// @param depositorAward The sum given to `depositor`.
/// @param receiverAward The sum given to `receiver`.
/// @param details Description of resolution (note: can link to secure judgment details, etc.).
function resolve(uint256 registration, uint256 depositorAward, uint256 receiverAward, string calldata details) external {
Locker storage locker = lockers[registration];
require(msg.sender == locker.resolver, "not resolver");
require(locker.locked, "not locked");
require(depositorAward + receiverAward == locker.value, "not remainder");
/// @dev Calculate resolution fee and apply to awards.
uint256 resolverFee = locker.value / resolvers[locker.resolver].fee;
depositorAward -= resolverFee / 2;
receiverAward -= resolverFee / 2;
/// @dev Handle asset transfers.
if (locker.token == address(0)) { /// @dev Split ETH.
safeTransferETH(locker.depositor, depositorAward);
safeTransferETH(locker.receiver, receiverAward);
safeTransferETH(locker.resolver, resolverFee);
} else if (locker.bento) { /// @dev ...BentoBox shares.
bento.transfer(locker.token, address(this), locker.depositor, depositorAward);
bento.transfer(locker.token, address(this), locker.receiver, receiverAward);
bento.transfer(locker.token, address(this), locker.resolver, resolverFee);
} else if (!locker.nft) { /// @dev ...ERC20.
safeTransfer(locker.token, locker.depositor, depositorAward);
safeTransfer(locker.token, locker.receiver, receiverAward);
safeTransfer(locker.token, locker.resolver, resolverFee);
} else { /// @dev Award NFT.
if (depositorAward != 0) {
safeTransferFrom(locker.token, address(this), locker.depositor, locker.value);
} else {
safeTransferFrom(locker.token, address(this), locker.receiver, locker.value);
}
}
delete lockers[registration];
emit Resolve(registration, depositorAward, receiverAward, details);
}
/// @notice Registers an account to serve as a potential `resolver`.
/// @param active Tracks willingness to serve - if 'true', can be joined to a locker.
/// @param fee The divisor to determine resolution fee - e.g., if '20', fee is 5% of locker.
function registerResolver(bool active, uint8 fee) external {
require(fee != 0, "fee must be greater than zero");
resolvers[msg.sender] = Resolver(active, fee);
emit RegisterResolver(msg.sender, active, fee);
}
// **** LEXDAO PROTOCOL **** //
// ------------------------ //
/// @notice Protocol for LexDAO to maintain agreements that can be stamped into lockers.
/// @param index # to register agreement under.
/// @param agreement Text or link to agreement, etc. - this allows for amendments.
function registerAgreement(uint256 index, string calldata agreement) external {
require(msg.sender == lexDAO, "not LexDAO");
agreements[index] = agreement;
emit RegisterAgreement(index, agreement);
}
/// @notice Protocol for LexDAO to update role.
/// @param _lexDAO Account to assign role to.
function updateLexDAO(address _lexDAO) external {
require(msg.sender == lexDAO, "not LexDAO");
lexDAO = _lexDAO;
emit UpdateLexDAO(_lexDAO);
}
// **** BATCHER UTILITIES **** //
// -------------------------- //
/// @notice Enables calling multiple methods in a single call to this contract.
function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
results = new bytes[](data.length);
unchecked {
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
if (result.length < 68) revert();
assembly { result := add(result, 0x04) }
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
/// @notice Provides EIP-2612 signed approval for this contract to spend user tokens.
/// @param token Address of ERC-20 token.
/// @param amount Token amount to grant spending right over.
/// @param deadline Termination for signed approval in Unix time.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function permitThis(
address token,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
/// @dev permit(address,address,uint256,uint256,uint8,bytes32,bytes32).
(bool success, ) = token.call(abi.encodeWithSelector(0xd505accf, msg.sender, address(this), amount, deadline, v, r, s));
require(success, "permit failed");
}
/// @notice Provides DAI-derived signed approval for this contract to spend user tokens.
/// @param token Address of ERC-20 token.
/// @param nonce Token owner's nonce - increases at each call to {permit}.
/// @param expiry Termination for signed approval in Unix time.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function permitThisAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
/// @dev permit(address,address,uint256,uint256,bool,uint8,bytes32,bytes32).
(bool success, ) = token.call(abi.encodeWithSelector(0x8fcbaf0c, msg.sender, address(this), nonce, expiry, true, v, r, s));
require(success, "permit failed");
}
/// @dev Provides way to sign approval for `bento` spends by locker.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function setBentoApproval(uint8 v, bytes32 r, bytes32 s) external {
bento.setMasterContractApproval(msg.sender, address(this), true, v, r, s);
}
// **** TRANSFER HELPERS **** //
// ------------------------- //
/// @notice Provides 'safe' ERC-20 {transfer} for tokens that don't consistently return 'true/false'.
/// @param token Address of ERC-20 token.
/// @param recipient Account to send tokens to.
/// @param value Token amount to send.
function safeTransfer(address token, address recipient, uint256 value) private {
/// @dev transfer(address,uint256).
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, recipient, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "transfer failed");
}
/// @notice Provides 'safe' ERC-20/721 {transferFrom} for tokens that don't consistently return 'true/false'.
/// @param token Address of ERC-20/721 token.
/// @param sender Account to send tokens from.
/// @param recipient Account to send tokens to.
/// @param value Token amount to send - if NFT, 'tokenId'.
function safeTransferFrom(address token, address sender, address recipient, uint256 value) private {
/// @dev transferFrom(address,address,uint256).
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, sender, recipient, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "pull failed");
}
/// @notice Provides 'safe' ETH transfer.
/// @param recipient Account to send ETH to.
/// @param value ETH amount to send.
function safeTransferETH(address recipient, uint256 value) private {
(bool success, ) = recipient.call{value: value}("");
require(success, "eth transfer failed");
}
}
|
contract LexLocker {
IBentoBoxMinimal immutable bento;
address public lexDAO;
address immutable wETH;
uint256 lockerCount;
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant INVOICE_HASH = keccak256("DepositInvoiceSig(address depositor,address receiver,address resolver,string details)");
mapping(uint256 => string) public agreements;
mapping(uint256 => Locker) public lockers;
mapping(address => Resolver) public resolvers;
constructor(IBentoBoxMinimal _bento, address _lexDAO, address _wETH) {
bento = _bento;
bento.registerProtocol();
lexDAO = _lexDAO;
wETH = _wETH;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("LexLocker")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
/// @dev Events to assist web3 applications.
event Deposit(
bool bento,
bool nft,
address indexed depositor,
address indexed receiver,
address resolver,
address token,
uint256 value,
uint256 indexed registration,
string details);
event DepositInvoiceSig(address indexed depositor, address indexed receiver);
event Release(uint256 indexed registration);
event Withdraw(uint256 indexed registration);
event Lock(uint256 indexed registration, string details);
event Resolve(uint256 indexed registration, uint256 indexed depositorAward, uint256 indexed receiverAward, string details);
event RegisterResolver(address indexed resolver, bool indexed active, uint256 indexed fee);
event RegisterAgreement(uint256 indexed index, string agreement);
event UpdateLexDAO(address indexed lexDAO);
/// @dev Tracks registered escrow status.
struct Locker {
bool bento;
bool nft;
bool locked;
address depositor;
address receiver;
address resolver;
address token;
uint256 value;
uint256 termination;
}
/// @dev Tracks registered resolver status.
struct Resolver {
bool active;
uint8 fee;
}
// **** ESCROW PROTOCOL **** //
// ------------------------ //
/// @notice Deposits tokens (ERC-20/721) into escrow
// - locked funds can be released by `msg.sender` `depositor`
// - both parties can {lock} for `resolver`.
/// @param receiver The account that receives funds.
/// @param resolver The account that unlock funds.
/// @param token The asset used for funds.
/// @param value The amount of funds - if `nft`, the 'tokenId' in first value is used.
/// @param termination Unix time upon which `depositor` can claim back funds.
/// @param nft If 'false', ERC-20 is assumed, otherwise, non-fungible asset.
/// @param details Describes context of escrow - stamped into event.
function deposit(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool nft,
string memory details
) public payable returns (uint256 registration) {
require(resolvers[resolver].active, "resolver not active");
require(resolver != msg.sender && resolver != receiver, "resolver cannot be party"); /// @dev Avoid conflicts.
/// @dev Handle ETH/ERC-20/721 deposit.
if (msg.value != 0) {
require(msg.value == value, "wrong msg.value");
/// @dev Overrides to clarify ETH is used.
if (token != address(0)) token = address(0);
if (nft) nft = false;
} else {
safeTransferFrom(token, msg.sender, address(this), value);
}
/// @dev Increment registered lockers and assign # to escrow deposit.
unchecked {
lockerCount++;
}
registration = lockerCount;
lockers[registration] = Locker(false, nft, false, msg.sender, receiver, resolver, token, value, termination);
emit Deposit(false, nft, msg.sender, receiver, resolver, token, value, registration, details);
}
/// @notice Deposits tokens (ERC-20/721) into BentoBox escrow
// - locked funds can be released by `msg.sender` `depositor`
// - both parties can {lock} for `resolver`.
/// @param receiver The account that receives funds.
/// @param resolver The account that unlock funds.
/// @param token The asset used for funds (note: NFT not supported in BentoBox).
/// @param value The amount of funds (note: locker converts to 'shares').
/// @param termination Unix time upon which `depositor` can claim back funds.
/// @param wrapBento If 'false', raw ERC-20 is assumed, otherwise, BentoBox 'shares'.
/// @param details Describes context of escrow - stamped into event.
function depositBento(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool wrapBento,
string memory details
) public payable returns (uint256 registration) {
require(resolvers[resolver].active, "resolver not active");
require(resolver != msg.sender && resolver != receiver, "resolver cannot be party"); /// @dev Avoid conflicts.
/// @dev Handle ETH/ERC-20 deposit.
if (msg.value != 0) {
require(msg.value == value, "wrong msg.value");
/// @dev Override to clarify wETH is used in BentoBox for ETH.
if (token != wETH) token = wETH;
(, value) = bento.deposit{value: msg.value}(address(0), address(this), address(this), msg.value, 0);
} else if (wrapBento) {
safeTransferFrom(token, msg.sender, address(bento), value);
(, value) = bento.deposit(token, address(bento), address(this), value, 0);
} else {
bento.transfer(token, msg.sender, address(this), value);
}
/// @dev Increment registered lockers and assign # to escrow deposit.
unchecked {
lockerCount++;
}
registration = lockerCount;
lockers[registration] = Locker(true, false, false, msg.sender, receiver, resolver, token, value, termination);
emit Deposit(true, false, msg.sender, receiver, resolver, token, value, registration, details);
}
/// @notice Validates deposit request 'invoice' for locker escrow.
/// @param receiver The account that receives funds.
/// @param resolver The account that unlock funds.
/// @param token The asset used for funds.
/// @param value The amount of funds - if `nft`, the 'tokenId'.
/// @param termination Unix time upon which `depositor` can claim back funds.
/// @param bentoBoxed If 'false', regular deposit is assumed, otherwise, BentoBox.
/// @param nft If 'false', ERC-20 is assumed, otherwise, non-fungible asset.
/// @param wrapBento If 'false', raw ERC-20 is assumed, otherwise, BentoBox 'shares'.
/// @param details Describes context of escrow - stamped into event.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function depositInvoiceSig(
address receiver,
address resolver,
address token,
uint256 value,
uint256 termination,
bool bentoBoxed,
bool nft,
bool wrapBento,
string memory details,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
/// @dev Validate basic elements of invoice.
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
INVOICE_HASH,
msg.sender,
receiver,
resolver,
details
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress == receiver, "invalid invoice");
/// @dev Perform deposit.
if (!bentoBoxed) {
deposit(receiver, resolver, token, value, termination, nft, details);
} else {
depositBento(receiver, resolver, token, value, termination, wrapBento, details);
}
emit DepositInvoiceSig(msg.sender, receiver);
}
/// @notice Releases escrowed assets to designated `receiver`
// - can only be called by `depositor` if not `locked`
// - can be called after `termination` as optional extension.
/// @param registration The index of escrow deposit.
function release(uint256 registration) external {
Locker storage locker = lockers[registration];
require(!locker.locked, "locked");
require(msg.sender == locker.depositor, "not depositor");
/// @dev Handle asset transfer.
if (locker.token == address(0)) { /// @dev Release ETH.
safeTransferETH(locker.receiver, locker.value);
} else if (locker.bento) { /// @dev Release BentoBox shares.
bento.transfer(locker.token, address(this), locker.receiver, locker.value);
} else if (!locker.nft) { /// @dev Release ERC-20.
safeTransfer(locker.token, locker.receiver, locker.value);
} else { /// @dev Release NFT.
safeTransferFrom(locker.token, address(this), locker.receiver, locker.value);
}
delete lockers[registration];
emit Release(registration);
}
/// @notice Releases escrowed assets back to designated `depositor`
// - can only be called by `depositor` if `termination` reached.
/// @param registration The index of escrow deposit.
function withdraw(uint256 registration) external {
Locker storage locker = lockers[registration];
require(msg.sender == locker.depositor, "not depositor");
require(!locker.locked, "locked");
require(block.timestamp >= locker.termination, "not terminated");
/// @dev Handle asset transfer.
if (locker.token == address(0)) { /// @dev Release ETH.
safeTransferETH(locker.depositor, locker.value);
} else if (locker.bento) { /// @dev Release BentoBox shares.
bento.transfer(locker.token, address(this), locker.depositor, locker.value);
} else if (!locker.nft) { /// @dev Release ERC-20.
safeTransfer(locker.token, locker.depositor, locker.value);
} else { /// @dev Release NFT.
safeTransferFrom(locker.token, address(this), locker.depositor, locker.value);
}
delete lockers[registration];
emit Withdraw(registration);
}
// **** DISPUTE PROTOCOL **** //
// ------------------------- //
/// @notice Locks escrowed assets for resolution - can only be called by locker parties.
/// @param registration The index of escrow deposit.
/// @param details Description of lock action (note: can link to secure dispute details, etc.).
function lock(uint256 registration, string calldata details) external {
Locker storage locker = lockers[registration];
require(msg.sender == locker.depositor || msg.sender == locker.receiver, "not party");
locker.locked = true;
emit Lock(registration, details);
}
/// @notice Resolves locked escrow deposit in split between parties - if NFT, must be complete award (so, one party receives '0')
// - `resolverFee` is automatically deducted from both parties' awards.
/// @param registration The registration index of escrow deposit.
/// @param depositorAward The sum given to `depositor`.
/// @param receiverAward The sum given to `receiver`.
/// @param details Description of resolution (note: can link to secure judgment details, etc.).
function resolve(uint256 registration, uint256 depositorAward, uint256 receiverAward, string calldata details) external {
Locker storage locker = lockers[registration];
require(msg.sender == locker.resolver, "not resolver");
require(locker.locked, "not locked");
require(depositorAward + receiverAward == locker.value, "not remainder");
/// @dev Calculate resolution fee and apply to awards.
uint256 resolverFee = locker.value / resolvers[locker.resolver].fee;
depositorAward -= resolverFee / 2;
receiverAward -= resolverFee / 2;
/// @dev Handle asset transfers.
if (locker.token == address(0)) { /// @dev Split ETH.
safeTransferETH(locker.depositor, depositorAward);
safeTransferETH(locker.receiver, receiverAward);
safeTransferETH(locker.resolver, resolverFee);
} else if (locker.bento) { /// @dev ...BentoBox shares.
bento.transfer(locker.token, address(this), locker.depositor, depositorAward);
bento.transfer(locker.token, address(this), locker.receiver, receiverAward);
bento.transfer(locker.token, address(this), locker.resolver, resolverFee);
} else if (!locker.nft) { /// @dev ...ERC20.
safeTransfer(locker.token, locker.depositor, depositorAward);
safeTransfer(locker.token, locker.receiver, receiverAward);
safeTransfer(locker.token, locker.resolver, resolverFee);
} else { /// @dev Award NFT.
if (depositorAward != 0) {
safeTransferFrom(locker.token, address(this), locker.depositor, locker.value);
} else {
safeTransferFrom(locker.token, address(this), locker.receiver, locker.value);
}
}
delete lockers[registration];
emit Resolve(registration, depositorAward, receiverAward, details);
}
/// @notice Registers an account to serve as a potential `resolver`.
/// @param active Tracks willingness to serve - if 'true', can be joined to a locker.
/// @param fee The divisor to determine resolution fee - e.g., if '20', fee is 5% of locker.
function registerResolver(bool active, uint8 fee) external {
require(fee != 0, "fee must be greater than zero");
resolvers[msg.sender] = Resolver(active, fee);
emit RegisterResolver(msg.sender, active, fee);
}
// **** LEXDAO PROTOCOL **** //
// ------------------------ //
/// @notice Protocol for LexDAO to maintain agreements that can be stamped into lockers.
/// @param index # to register agreement under.
/// @param agreement Text or link to agreement, etc. - this allows for amendments.
function registerAgreement(uint256 index, string calldata agreement) external {
require(msg.sender == lexDAO, "not LexDAO");
agreements[index] = agreement;
emit RegisterAgreement(index, agreement);
}
/// @notice Protocol for LexDAO to update role.
/// @param _lexDAO Account to assign role to.
function updateLexDAO(address _lexDAO) external {
require(msg.sender == lexDAO, "not LexDAO");
lexDAO = _lexDAO;
emit UpdateLexDAO(_lexDAO);
}
// **** BATCHER UTILITIES **** //
// -------------------------- //
/// @notice Enables calling multiple methods in a single call to this contract.
function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
results = new bytes[](data.length);
unchecked {
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
if (result.length < 68) revert();
assembly { result := add(result, 0x04) }
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
/// @notice Provides EIP-2612 signed approval for this contract to spend user tokens.
/// @param token Address of ERC-20 token.
/// @param amount Token amount to grant spending right over.
/// @param deadline Termination for signed approval in Unix time.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function permitThis(
address token,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
/// @dev permit(address,address,uint256,uint256,uint8,bytes32,bytes32).
(bool success, ) = token.call(abi.encodeWithSelector(0xd505accf, msg.sender, address(this), amount, deadline, v, r, s));
require(success, "permit failed");
}
/// @notice Provides DAI-derived signed approval for this contract to spend user tokens.
/// @param token Address of ERC-20 token.
/// @param nonce Token owner's nonce - increases at each call to {permit}.
/// @param expiry Termination for signed approval in Unix time.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function permitThisAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
/// @dev permit(address,address,uint256,uint256,bool,uint8,bytes32,bytes32).
(bool success, ) = token.call(abi.encodeWithSelector(0x8fcbaf0c, msg.sender, address(this), nonce, expiry, true, v, r, s));
require(success, "permit failed");
}
/// @dev Provides way to sign approval for `bento` spends by locker.
/// @param v The recovery byte of the signature.
/// @param r Half of the ECDSA signature pair.
/// @param s Half of the ECDSA signature pair.
function setBentoApproval(uint8 v, bytes32 r, bytes32 s) external {
bento.setMasterContractApproval(msg.sender, address(this), true, v, r, s);
}
// **** TRANSFER HELPERS **** //
// ------------------------- //
/// @notice Provides 'safe' ERC-20 {transfer} for tokens that don't consistently return 'true/false'.
/// @param token Address of ERC-20 token.
/// @param recipient Account to send tokens to.
/// @param value Token amount to send.
function safeTransfer(address token, address recipient, uint256 value) private {
/// @dev transfer(address,uint256).
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, recipient, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "transfer failed");
}
/// @notice Provides 'safe' ERC-20/721 {transferFrom} for tokens that don't consistently return 'true/false'.
/// @param token Address of ERC-20/721 token.
/// @param sender Account to send tokens from.
/// @param recipient Account to send tokens to.
/// @param value Token amount to send - if NFT, 'tokenId'.
function safeTransferFrom(address token, address sender, address recipient, uint256 value) private {
/// @dev transferFrom(address,address,uint256).
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, sender, recipient, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "pull failed");
}
/// @notice Provides 'safe' ETH transfer.
/// @param recipient Account to send ETH to.
/// @param value ETH amount to send.
function safeTransferETH(address recipient, uint256 value) private {
(bool success, ) = recipient.call{value: value}("");
require(success, "eth transfer failed");
}
}
| 1,646
|
249
|
// Toggle the Attachment Switch_stateThe state /
|
function toggleAttachedEnforcement (bool _state) public onlyManager {
attachedSystemActive = _state;
}
|
function toggleAttachedEnforcement (bool _state) public onlyManager {
attachedSystemActive = _state;
}
| 31,035
|
121
|
// Powers the meta transactions for `unsafeTransferFrom` - EIP-3009 `transferWithAuthorization` and `receiveWithAuthorization`See `unsafeTransferFrom` and `transferFrom` soldoc for details_by an address executing the transfer, it can be token owner itself, or an operator previously approved with `approve()` _from token sender, token owner which approved caller (transaction sender) to transfer `_value` of tokens on its behalf _to token receiver, an address to transfer tokens to _value amount of tokens to be transferred,, zero value is allowed /
|
function __transferFrom(address _by, address _from, address _to, uint256 _value) private {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == _by && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != _by && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == _by? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "transfer from the zero address");
// non-zero recipient address check
require(_to != address(0), "transfer to the zero address");
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != _by) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][_by];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "transfer amount exceeds allowance");
// we treat max uint256 allowance value as an "unlimited" and
// do not decrease allowance when it is set to "unlimited" value
if(_allowance < type(uint256).max) {
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][_by] = _allowance;
// emit an improved atomic approve event
emit Approval(_from, _by, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, _by, _allowance);
}
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "transfer amount exceeds balance");
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(_by, votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event (arXiv:1907.00903)
emit Transfer(_by, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
|
function __transferFrom(address _by, address _from, address _to, uint256 _value) private {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == _by && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != _by && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == _by? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "transfer from the zero address");
// non-zero recipient address check
require(_to != address(0), "transfer to the zero address");
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != _by) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][_by];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "transfer amount exceeds allowance");
// we treat max uint256 allowance value as an "unlimited" and
// do not decrease allowance when it is set to "unlimited" value
if(_allowance < type(uint256).max) {
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][_by] = _allowance;
// emit an improved atomic approve event
emit Approval(_from, _by, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, _by, _allowance);
}
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "transfer amount exceeds balance");
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(_by, votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event (arXiv:1907.00903)
emit Transfer(_by, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
| 18,913
|
49
|
// Function to set the mean,deviation and formula constants for log normals curve mean_ New log normal mean deviation_ New log normal deviation oneDivDeviationSqrtTwoPi_ New Result of 1/(DeviationSqrt(2pi)) twoDeviationSquare_ New Result of 2(Deviation)^2 /
|
function setMeanAndDeviationWithFormulaConstants(
bytes16 mean_,
bytes16 deviation_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
|
function setMeanAndDeviationWithFormulaConstants(
bytes16 mean_,
bytes16 deviation_,
bytes16 oneDivDeviationSqrtTwoPi_,
bytes16 twoDeviationSquare_
| 15,592
|
93
|
// A distinct URI (RFC 3986) for a given NFT. _tokenId Id for which we want uri.return URI of _tokenId. /
|
function tokenURI(uint256 _tokenId)
external
view
override
validNFToken(_tokenId)
returns (string memory)
|
function tokenURI(uint256 _tokenId)
external
view
override
validNFToken(_tokenId)
returns (string memory)
| 5,356
|
52
|
// e.g. 8e181e18 = 8e36
|
uint256 z = x.mul(FULL_SCALE);
|
uint256 z = x.mul(FULL_SCALE);
| 13,267
|
13
|
// Sets the `name()` record for the reverse ENS record associated withthe account provided. First updates the resolver to the default reverseresolver if necessary.Only callable by controllers and authorised users addr The reverse record to set owner The owner of the reverse node name The name to set for this address.return The ENS node hash of the reverse record. /
|
function setNameForAddr(
address addr,
address owner,
string memory name
|
function setNameForAddr(
address addr,
address owner,
string memory name
| 26,724
|
141
|
// To see the voting mappings, go to GovernancePowerWithSnapshot.sol
|
mapping(address => address) internal _votingDelegates;
mapping(address => mapping(uint256 => Snapshot)) internal _propositionPowerSnapshots;
mapping(address => uint256) internal _propositionPowerSnapshotsCounts;
mapping(address => address) internal _propositionPowerDelegates;
bytes32 public DOMAIN_SEPARATOR;
bytes public constant EIP712_REVISION = bytes('1');
bytes32 internal constant EIP712_DOMAIN =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
|
mapping(address => address) internal _votingDelegates;
mapping(address => mapping(uint256 => Snapshot)) internal _propositionPowerSnapshots;
mapping(address => uint256) internal _propositionPowerSnapshotsCounts;
mapping(address => address) internal _propositionPowerDelegates;
bytes32 public DOMAIN_SEPARATOR;
bytes public constant EIP712_REVISION = bytes('1');
bytes32 internal constant EIP712_DOMAIN =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
| 12,337
|
89
|
// Compute remainder as before
|
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
|
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
| 32,528
|
39
|
// blacklist address
|
mapping(address => bool) public isBlacklisted;
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SendMarketing(uint256 bnbSend);
|
mapping(address => bool) public isBlacklisted;
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SendMarketing(uint256 bnbSend);
| 30,740
|
4
|
// There is minimum and maximum bets.
|
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
|
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
| 74,996
|
111
|
// Update the stored timestamp.
|
vpBound.timeLastUpdated = uint64(block.timestamp);
|
vpBound.timeLastUpdated = uint64(block.timestamp);
| 3,713
|
47
|
// Approves another address to transfer the given token IDThe zero address indicates there is no approved address.There can only be one approved address per token at a given time.Can only be called by the token owner or an approved operator. _to address to be approved for the given token ID _tokenId uint256 ID of the token to be approved /
|
function approve(address _to, uint256 _tokenId) override public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
|
function approve(address _to, uint256 _tokenId) override public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
| 49,759
|
187
|
// current owned liquidity
|
require(
farmingPosition.creationBlock != 0 &&
removedLiquidity <= farmingPosition.liquidityPoolTokenAmount &&
farmingPosition.uniqueOwner == msg.sender,
"Invalid withdraw"
);
_withdrawReward(positionId, removedLiquidity);
_setups[farmingPosition.setupIndex].totalSupply -= removedLiquidity;
farmingPosition.liquidityPoolTokenAmount -= removedLiquidity;
|
require(
farmingPosition.creationBlock != 0 &&
removedLiquidity <= farmingPosition.liquidityPoolTokenAmount &&
farmingPosition.uniqueOwner == msg.sender,
"Invalid withdraw"
);
_withdrawReward(positionId, removedLiquidity);
_setups[farmingPosition.setupIndex].totalSupply -= removedLiquidity;
farmingPosition.liquidityPoolTokenAmount -= removedLiquidity;
| 24,982
|
61
|
// uint256 stakedTotal = state.stakedTotal;
|
{
uint256 stakedBalance = state.stakedBalance;
if (stakingCap > 0 && remaining > (stakingCap.sub(stakedBalance))) {
remaining = stakingCap.sub(stakedBalance);
}
|
{
uint256 stakedBalance = state.stakedBalance;
if (stakingCap > 0 && remaining > (stakingCap.sub(stakedBalance))) {
remaining = stakingCap.sub(stakedBalance);
}
| 20,627
|
29
|
// Check health before allowing member to propose borrowing more
|
require(isHealthy(), "AP::Not healthy enough");
|
require(isHealthy(), "AP::Not healthy enough");
| 19,575
|
4
|
// return the number of token units a buyer gets per swapToken unit. /
|
function swapRate(address _swapTokenAddr) public view returns (uint256) {
return _swapRates[_swapTokenAddr];
}
|
function swapRate(address _swapTokenAddr) public view returns (uint256) {
return _swapRates[_swapTokenAddr];
}
| 24,678
|
36
|
// ----------------REBALANCING LOGIC------------------
|
function rebalance(uint256 srcChainId, uint256 dstChainId, uint256 shareToRebalance, uint8 slippage)
external
onlyRebalancer
|
function rebalance(uint256 srcChainId, uint256 dstChainId, uint256 shareToRebalance, uint8 slippage)
external
onlyRebalancer
| 16,571
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.