contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorStorage | contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
} | /**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/ | NatSpecMultiLine | isValidator | function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
| /**
* @notice does validator exist?
* @return true if yes, false if no
**/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
4967,
5088
]
} | 58,461 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorStorage | contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
} | /**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/ | NatSpecMultiLine | isPermission | function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
| /**
* @notice does permission exist?
* @return true if yes, false if no
**/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
5187,
5328
]
} | 58,462 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorStorage | contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
} | /**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/ | NatSpecMultiLine | getPermission | function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
| /**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
5513,
5936
]
} | 58,463 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorStorage | contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
} | /**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/ | NatSpecMultiLine | hasUserPermission | function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
| /**
* @notice does permission exist?
* @return true if yes, false if no
**/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
6035,
6198
]
} | 58,464 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorProxy | contract RegulatorProxy is UpgradeabilityProxy, RegulatorStorage {
/**
* @dev CONSTRUCTOR
* @param _implementation the contract who's logic the proxy will initially delegate functionality to
**/
constructor(address _implementation) public UpgradeabilityProxy(_implementation) {}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) public onlyOwner {
_upgradeTo(newImplementation);
}
/**
* @return The address of the implementation.
*/
function implementation() public view returns (address) {
return _implementation();
}
} | /**
* @title RegulatorProxy
* @dev A RegulatorProxy is a proxy contract that acts identically to a Regulator from the
* user's point of view. A proxy can change its data storage locations and can also
* change its implementation contract location. A call to RegulatorProxy delegates the function call
* to the latest implementation contract's version of the function and the proxy then
* calls that function in the context of the proxy's data storage
*
*/ | NatSpecMultiLine | upgradeTo | function upgradeTo(address newImplementation) public onlyOwner {
_upgradeTo(newImplementation);
}
| /**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
506,
624
]
} | 58,465 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorProxy | contract RegulatorProxy is UpgradeabilityProxy, RegulatorStorage {
/**
* @dev CONSTRUCTOR
* @param _implementation the contract who's logic the proxy will initially delegate functionality to
**/
constructor(address _implementation) public UpgradeabilityProxy(_implementation) {}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) public onlyOwner {
_upgradeTo(newImplementation);
}
/**
* @return The address of the implementation.
*/
function implementation() public view returns (address) {
return _implementation();
}
} | /**
* @title RegulatorProxy
* @dev A RegulatorProxy is a proxy contract that acts identically to a Regulator from the
* user's point of view. A proxy can change its data storage locations and can also
* change its implementation contract location. A call to RegulatorProxy delegates the function call
* to the latest implementation contract's version of the function and the proxy then
* calls that function in the context of the proxy's data storage
*
*/ | NatSpecMultiLine | implementation | function implementation() public view returns (address) {
return _implementation();
}
| /**
* @return The address of the implementation.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
696,
800
]
} | 58,466 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | setMinter | function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
| /**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
972,
1066
]
} | 58,467 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | removeMinter | function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
| /**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
1246,
1346
]
} | 58,468 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | setBlacklistSpender | function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
| /**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
1550,
1864
]
} | 58,469 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | removeBlacklistSpender | function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
| /**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
2076,
2400
]
} | 58,470 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | setBlacklistDestroyer | function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
| /**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
2606,
2915
]
} | 58,471 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | removeBlacklistDestroyer | function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
| /**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
3131,
3450
]
} | 58,472 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | setBlacklistedUser | function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
| /**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
3730,
3842
]
} | 58,473 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | removeBlacklistedUser | function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
| /**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
4126,
4244
]
} | 58,474 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | isBlacklistedUser | function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
| /** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
4441,
4582
]
} | 58,475 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | isBlacklistSpender | function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
| /** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
4797,
4961
]
} | 58,476 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | isBlacklistDestroyer | function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
| /** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
5178,
5335
]
} | 58,477 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | isMinter | function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
| /** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
5526,
5693
]
} | 58,478 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | Regulator | contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
} | /**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/ | NatSpecMultiLine | _setMinter | function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
| /** Internal Functions **/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
5730,
6078
]
} | 58,479 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorProxyFactory | contract RegulatorProxyFactory {
// TODO: Instead of a single array of addresses, this should be a mapping or an array
// of objects of type { address: ...new_regulator, type: whitelisted_or_cusd }
address[] public regulators;
// Events
event CreatedRegulatorProxy(address newRegulator, uint256 index);
/**
*
* @dev generate a new proxyaddress that users can cast to a Regulator or RegulatorProxy. The
* proxy has empty data storage contracts connected to it and it is set with an initial logic contract
* to which it will delegate functionality
* @notice the method caller will have to claim ownership of regulators since regulators are claimable
* @param regulatorImplementation the address of the logic contract that the proxy will initialize its implementation to
*
**/
function createRegulatorProxy(address regulatorImplementation) public {
// Store new data storage contracts for regulator proxy
address proxy = address(new RegulatorProxy(regulatorImplementation));
Regulator newRegulator = Regulator(proxy);
// Testing: Add msg.sender as a validator, add all permissions
newRegulator.addValidator(msg.sender);
addAllPermissions(newRegulator);
// The function caller should own the proxy contract, so they will need to claim ownership
RegulatorProxy(proxy).transferOwnership(msg.sender);
regulators.push(proxy);
emit CreatedRegulatorProxy(proxy, getCount()-1);
}
/**
*
* @dev Add all permission signatures to regulator
*
**/
function addAllPermissions(Regulator regulator) public {
// Make this contract a temporary validator to add all permissions
regulator.addValidator(this);
regulator.addPermission(regulator.MINT_SIG(), "", "", "" );
regulator.addPermission(regulator.DESTROY_BLACKLISTED_TOKENS_SIG(), "", "", "" );
regulator.addPermission(regulator.APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG(), "", "", "" );
regulator.addPermission(regulator.BLACKLISTED_SIG(), "", "", "" );
regulator.addPermission(regulator.MINT_CUSD_SIG(), "", "", "" );
regulator.removeValidator(this);
}
// Return number of proxies created
function getCount() public view returns (uint256) {
return regulators.length;
}
// Return the i'th created proxy. The most recently created proxy will be at position getCount()-1.
function getRegulatorProxy(uint256 i) public view returns(address) {
require((i < regulators.length) && (i >= 0), "Invalid index");
return regulators[i];
}
} | /**
*
* @dev RegulatorProxyFactory creates new RegulatorProxy contracts with new data storage sheets, properly configured
* with ownership, and the proxy logic implementations are based on a user-specified Regulator.
*
**/ | NatSpecMultiLine | createRegulatorProxy | function createRegulatorProxy(address regulatorImplementation) public {
// Store new data storage contracts for regulator proxy
address proxy = address(new RegulatorProxy(regulatorImplementation));
Regulator newRegulator = Regulator(proxy);
// Testing: Add msg.sender as a validator, add all permissions
newRegulator.addValidator(msg.sender);
addAllPermissions(newRegulator);
// The function caller should own the proxy contract, so they will need to claim ownership
RegulatorProxy(proxy).transferOwnership(msg.sender);
regulators.push(proxy);
emit CreatedRegulatorProxy(proxy, getCount()-1);
}
| /**
*
* @dev generate a new proxyaddress that users can cast to a Regulator or RegulatorProxy. The
* proxy has empty data storage contracts connected to it and it is set with an initial logic contract
* to which it will delegate functionality
* @notice the method caller will have to claim ownership of regulators since regulators are claimable
* @param regulatorImplementation the address of the logic contract that the proxy will initialize its implementation to
*
**/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
851,
1553
]
} | 58,480 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorProxyFactory | contract RegulatorProxyFactory {
// TODO: Instead of a single array of addresses, this should be a mapping or an array
// of objects of type { address: ...new_regulator, type: whitelisted_or_cusd }
address[] public regulators;
// Events
event CreatedRegulatorProxy(address newRegulator, uint256 index);
/**
*
* @dev generate a new proxyaddress that users can cast to a Regulator or RegulatorProxy. The
* proxy has empty data storage contracts connected to it and it is set with an initial logic contract
* to which it will delegate functionality
* @notice the method caller will have to claim ownership of regulators since regulators are claimable
* @param regulatorImplementation the address of the logic contract that the proxy will initialize its implementation to
*
**/
function createRegulatorProxy(address regulatorImplementation) public {
// Store new data storage contracts for regulator proxy
address proxy = address(new RegulatorProxy(regulatorImplementation));
Regulator newRegulator = Regulator(proxy);
// Testing: Add msg.sender as a validator, add all permissions
newRegulator.addValidator(msg.sender);
addAllPermissions(newRegulator);
// The function caller should own the proxy contract, so they will need to claim ownership
RegulatorProxy(proxy).transferOwnership(msg.sender);
regulators.push(proxy);
emit CreatedRegulatorProxy(proxy, getCount()-1);
}
/**
*
* @dev Add all permission signatures to regulator
*
**/
function addAllPermissions(Regulator regulator) public {
// Make this contract a temporary validator to add all permissions
regulator.addValidator(this);
regulator.addPermission(regulator.MINT_SIG(), "", "", "" );
regulator.addPermission(regulator.DESTROY_BLACKLISTED_TOKENS_SIG(), "", "", "" );
regulator.addPermission(regulator.APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG(), "", "", "" );
regulator.addPermission(regulator.BLACKLISTED_SIG(), "", "", "" );
regulator.addPermission(regulator.MINT_CUSD_SIG(), "", "", "" );
regulator.removeValidator(this);
}
// Return number of proxies created
function getCount() public view returns (uint256) {
return regulators.length;
}
// Return the i'th created proxy. The most recently created proxy will be at position getCount()-1.
function getRegulatorProxy(uint256 i) public view returns(address) {
require((i < regulators.length) && (i >= 0), "Invalid index");
return regulators[i];
}
} | /**
*
* @dev RegulatorProxyFactory creates new RegulatorProxy contracts with new data storage sheets, properly configured
* with ownership, and the proxy logic implementations are based on a user-specified Regulator.
*
**/ | NatSpecMultiLine | addAllPermissions | function addAllPermissions(Regulator regulator) public {
// Make this contract a temporary validator to add all permissions
regulator.addValidator(this);
regulator.addPermission(regulator.MINT_SIG(), "", "", "" );
regulator.addPermission(regulator.DESTROY_BLACKLISTED_TOKENS_SIG(), "", "", "" );
regulator.addPermission(regulator.APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG(), "", "", "" );
regulator.addPermission(regulator.BLACKLISTED_SIG(), "", "", "" );
regulator.addPermission(regulator.MINT_CUSD_SIG(), "", "", "" );
regulator.removeValidator(this);
}
| /**
*
* @dev Add all permission signatures to regulator
*
**/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
1643,
2280
]
} | 58,481 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorProxyFactory | contract RegulatorProxyFactory {
// TODO: Instead of a single array of addresses, this should be a mapping or an array
// of objects of type { address: ...new_regulator, type: whitelisted_or_cusd }
address[] public regulators;
// Events
event CreatedRegulatorProxy(address newRegulator, uint256 index);
/**
*
* @dev generate a new proxyaddress that users can cast to a Regulator or RegulatorProxy. The
* proxy has empty data storage contracts connected to it and it is set with an initial logic contract
* to which it will delegate functionality
* @notice the method caller will have to claim ownership of regulators since regulators are claimable
* @param regulatorImplementation the address of the logic contract that the proxy will initialize its implementation to
*
**/
function createRegulatorProxy(address regulatorImplementation) public {
// Store new data storage contracts for regulator proxy
address proxy = address(new RegulatorProxy(regulatorImplementation));
Regulator newRegulator = Regulator(proxy);
// Testing: Add msg.sender as a validator, add all permissions
newRegulator.addValidator(msg.sender);
addAllPermissions(newRegulator);
// The function caller should own the proxy contract, so they will need to claim ownership
RegulatorProxy(proxy).transferOwnership(msg.sender);
regulators.push(proxy);
emit CreatedRegulatorProxy(proxy, getCount()-1);
}
/**
*
* @dev Add all permission signatures to regulator
*
**/
function addAllPermissions(Regulator regulator) public {
// Make this contract a temporary validator to add all permissions
regulator.addValidator(this);
regulator.addPermission(regulator.MINT_SIG(), "", "", "" );
regulator.addPermission(regulator.DESTROY_BLACKLISTED_TOKENS_SIG(), "", "", "" );
regulator.addPermission(regulator.APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG(), "", "", "" );
regulator.addPermission(regulator.BLACKLISTED_SIG(), "", "", "" );
regulator.addPermission(regulator.MINT_CUSD_SIG(), "", "", "" );
regulator.removeValidator(this);
}
// Return number of proxies created
function getCount() public view returns (uint256) {
return regulators.length;
}
// Return the i'th created proxy. The most recently created proxy will be at position getCount()-1.
function getRegulatorProxy(uint256 i) public view returns(address) {
require((i < regulators.length) && (i >= 0), "Invalid index");
return regulators[i];
}
} | /**
*
* @dev RegulatorProxyFactory creates new RegulatorProxy contracts with new data storage sheets, properly configured
* with ownership, and the proxy logic implementations are based on a user-specified Regulator.
*
**/ | NatSpecMultiLine | getCount | function getCount() public view returns (uint256) {
return regulators.length;
}
| // Return number of proxies created | LineComment | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
2325,
2423
]
} | 58,482 |
|
RegulatorProxyFactory | RegulatorProxyFactory.sol | 0x8180522f083bf9a1f756745e5decff48e007d370 | Solidity | RegulatorProxyFactory | contract RegulatorProxyFactory {
// TODO: Instead of a single array of addresses, this should be a mapping or an array
// of objects of type { address: ...new_regulator, type: whitelisted_or_cusd }
address[] public regulators;
// Events
event CreatedRegulatorProxy(address newRegulator, uint256 index);
/**
*
* @dev generate a new proxyaddress that users can cast to a Regulator or RegulatorProxy. The
* proxy has empty data storage contracts connected to it and it is set with an initial logic contract
* to which it will delegate functionality
* @notice the method caller will have to claim ownership of regulators since regulators are claimable
* @param regulatorImplementation the address of the logic contract that the proxy will initialize its implementation to
*
**/
function createRegulatorProxy(address regulatorImplementation) public {
// Store new data storage contracts for regulator proxy
address proxy = address(new RegulatorProxy(regulatorImplementation));
Regulator newRegulator = Regulator(proxy);
// Testing: Add msg.sender as a validator, add all permissions
newRegulator.addValidator(msg.sender);
addAllPermissions(newRegulator);
// The function caller should own the proxy contract, so they will need to claim ownership
RegulatorProxy(proxy).transferOwnership(msg.sender);
regulators.push(proxy);
emit CreatedRegulatorProxy(proxy, getCount()-1);
}
/**
*
* @dev Add all permission signatures to regulator
*
**/
function addAllPermissions(Regulator regulator) public {
// Make this contract a temporary validator to add all permissions
regulator.addValidator(this);
regulator.addPermission(regulator.MINT_SIG(), "", "", "" );
regulator.addPermission(regulator.DESTROY_BLACKLISTED_TOKENS_SIG(), "", "", "" );
regulator.addPermission(regulator.APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG(), "", "", "" );
regulator.addPermission(regulator.BLACKLISTED_SIG(), "", "", "" );
regulator.addPermission(regulator.MINT_CUSD_SIG(), "", "", "" );
regulator.removeValidator(this);
}
// Return number of proxies created
function getCount() public view returns (uint256) {
return regulators.length;
}
// Return the i'th created proxy. The most recently created proxy will be at position getCount()-1.
function getRegulatorProxy(uint256 i) public view returns(address) {
require((i < regulators.length) && (i >= 0), "Invalid index");
return regulators[i];
}
} | /**
*
* @dev RegulatorProxyFactory creates new RegulatorProxy contracts with new data storage sheets, properly configured
* with ownership, and the proxy logic implementations are based on a user-specified Regulator.
*
**/ | NatSpecMultiLine | getRegulatorProxy | function getRegulatorProxy(uint256 i) public view returns(address) {
require((i < regulators.length) && (i >= 0), "Invalid index");
return regulators[i];
}
| // Return the i'th created proxy. The most recently created proxy will be at position getCount()-1. | LineComment | v0.4.24+commit.e67f0147 | bzzr://43c565c53a5f21e4fba0b6a07ed7b6c78c6b5925e8398f8ba818b96a82b672f3 | {
"func_code_index": [
2531,
2714
]
} | 58,483 |
|
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | name | function name() external view returns (string memory) {
return _name;
}
| /**
* @dev Gets the token name.
* @return string representing the token name
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
1040,
1127
]
} | 58,484 |
||
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | symbol | function symbol() external view returns (string memory) {
return _symbol;
}
| /**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
1232,
1323
]
} | 58,485 |
||
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | tokenURI | function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
| /**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
1622,
2205
]
} | 58,486 |
||
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | baseURI | function baseURI() external view returns (string memory) {
return _baseURI;
}
| /**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
2395,
2488
]
} | 58,487 |
||
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | _setTokenURI | function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
| /**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
2808,
3050
]
} | 58,488 |
||
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | _setBaseURI | function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
| /**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
3259,
3351
]
} | 58,489 |
||
fragmentClaimer | ERC721Metadata.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | ERC721Metadata | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
} | _burn | function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
| /**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/ | NatSpecMultiLine | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
3640,
3884
]
} | 58,490 |
||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
60,
124
]
} | 58,491 |
|||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
232,
309
]
} | 58,492 |
|||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
546,
623
]
} | 58,493 |
|||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
946,
1042
]
} | 58,494 |
|||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
1326,
1407
]
} | 58,495 |
|||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
1615,
1712
]
} | 58,496 |
|||
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Galleon | contract Galleon is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function Galleon(
) {
balances[msg.sender] = 70000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 70000000000000; // Update total supply (100000 for example)
name = "Galleon"; // Set the name for display purposes
decimals = 7; // Amount of decimals for display purposes
symbol = "GLN"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | Galleon | function Galleon(
) {
balances[msg.sender] = 70000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 70000000000000; // Update total supply (100000 for example)
name = "Galleon"; // Set the name for display purposes
decimals = 7; // Amount of decimals for display purposes
symbol = "GLN"; // Set the symbol for display purposes
}
| //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
1156,
1711
]
} | 58,497 |
|
Galleon | Galleon.sol | 0xd9ccdc9da2c4665b2752bde64e528ebc2eb92314 | Solidity | Galleon | contract Galleon is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function Galleon(
) {
balances[msg.sender] = 70000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 70000000000000; // Update total supply (100000 for example)
name = "Galleon"; // Set the name for display purposes
decimals = 7; // Amount of decimals for display purposes
symbol = "GLN"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://1b80de98252c72342f8f612979cffd4e27f2f9f22c8e9098347f8259d7d208c5 | {
"func_code_index": [
1772,
2577
]
} | 58,498 |
|
fragmentClaimer | FragmentClaimer.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | fragmentClaimer | contract fragmentClaimer {
event UpdateWhitelist(address _account, bool _value);
event aTokenWasClaimed(uint _tokenNumber, address _tokenClaimer);
event yeeeeeeaaaaaahThxCoeurCoeurCoeur(address _tipper);
event withdrawFunds(address _withdrawer, uint _funds);
mapping(address => bool) public whitelist;
mapping(uint => bool) public tokensThatWereClaimed;
uint maxTokenId;
uint totalFunds;
address ERC721address;
constructor(uint _maxTokenId, address _ERC721address) public {
whitelist[msg.sender] = true;
maxTokenId = _maxTokenId;
ERC721address = _ERC721address;
}
function () external payable {
if (msg.value > 0) {
totalFunds += msg.value;
emit yeeeeeeaaaaaahThxCoeurCoeurCoeur(msg.sender);
}
}
function claimAToken(uint _tokenToClaim, string memory _tokenURI, bytes memory _signature)
public
payable
returns (bool)
{
// Checking if the token has already been claimed
require(!tokensThatWereClaimed[_tokenToClaim], "Claim: token already claimed");
// Not sure this is useful but oh well
require(_tokenToClaim <= maxTokenId, "Claim: tokenId outbounds");
// Creating a hash unique to this token number, and this token contract
bytes32 _hash = keccak256(abi.encode(ERC721address, _tokenToClaim, _tokenURI));
// Making sure that the signer has been whitelisted
require(signerIsWhitelisted(_hash, _signature), "Claim: signer not whitelisted");
// All should be good, so we mint a token yeah
ERC721MetadataMintable targetERC721Contract = ERC721MetadataMintable(ERC721address);
targetERC721Contract.mintWithTokenURI(msg.sender, _tokenToClaim, _tokenURI);
// Registering that the token was claimed
// Note that there is a check in the ERC721 for this too
tokensThatWereClaimed[_tokenToClaim] = true;
// Emitting an event
emit aTokenWasClaimed(_tokenToClaim, msg.sender);
// If a tip was included, thank the tipper
if (msg.value > 0) {
emit yeeeeeeaaaaaahThxCoeurCoeurCoeur(msg.sender);
totalFunds += msg.value;
}
}
function withdrawTips() public onlyWhitelisted {
msg.sender.transfer(totalFunds);
emit withdrawFunds(msg.sender, totalFunds );
}
// 20/02/27: Borrowed from https://github.com/austintgriffith/bouncer-proxy/blob/master/BouncerProxy/BouncerProxy.sol
//borrowed from OpenZeppelin's ESDA stuff:
//https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/ECDSA.sol
function signerIsWhitelisted(bytes32 _hash, bytes memory _signature) internal view returns (bool) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (_signature.length != 65) {
return false;
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return false;
} else {
// solium-disable-next-line arg-overflow
return whitelist[ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s)];
}
}
// 20/02/27: Borrowed from https://github.com/rocksideio/contracts/blob/master/contracts/Identity.sol
function updateWhitelist(address _account, bool _value) onlyWhitelisted public returns (bool) {
whitelist[_account] = _value;
emit UpdateWhitelist(_account, _value);
return true;
}
modifier onlyWhitelisted() {
require(whitelist[msg.sender], "Account Not Whitelisted");
_;
}
} | signerIsWhitelisted | function signerIsWhitelisted(bytes32 _hash, bytes memory _signature) internal view returns (bool) {
tes32 r;
tes32 s;
nt8 v;
Check the signature length
(_signature.length != 65) {
eturn false;
Divide the signature in r, s and v variables
ecrecover takes the signature parameters, and the only way to get them
currently is to use assembly.
solium-disable-next-line security/no-inline-assembly
sembly {
:= mload(add(_signature, 32))
:= mload(add(_signature, 64))
:= byte(0, mload(add(_signature, 96)))
Version of signature should be 27 or 28, but 0 and 1 are also possible versions
(v < 27) {
+= 27;
If the version is correct return the signer address
(v != 27 && v != 28) {
eturn false;
else {
/ solium-disable-next-line arg-overflow
eturn whitelist[ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s)];
}
| // 20/02/27: Borrowed from https://github.com/austintgriffith/bouncer-proxy/blob/master/BouncerProxy/BouncerProxy.sol
//borrowed from OpenZeppelin's ESDA stuff:
//https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/ECDSA.sol | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
2664,
3650
]
} | 58,499 |
||
fragmentClaimer | FragmentClaimer.sol | 0xee30651c467d40a1cf09011168e3c21c7ae7a59c | Solidity | fragmentClaimer | contract fragmentClaimer {
event UpdateWhitelist(address _account, bool _value);
event aTokenWasClaimed(uint _tokenNumber, address _tokenClaimer);
event yeeeeeeaaaaaahThxCoeurCoeurCoeur(address _tipper);
event withdrawFunds(address _withdrawer, uint _funds);
mapping(address => bool) public whitelist;
mapping(uint => bool) public tokensThatWereClaimed;
uint maxTokenId;
uint totalFunds;
address ERC721address;
constructor(uint _maxTokenId, address _ERC721address) public {
whitelist[msg.sender] = true;
maxTokenId = _maxTokenId;
ERC721address = _ERC721address;
}
function () external payable {
if (msg.value > 0) {
totalFunds += msg.value;
emit yeeeeeeaaaaaahThxCoeurCoeurCoeur(msg.sender);
}
}
function claimAToken(uint _tokenToClaim, string memory _tokenURI, bytes memory _signature)
public
payable
returns (bool)
{
// Checking if the token has already been claimed
require(!tokensThatWereClaimed[_tokenToClaim], "Claim: token already claimed");
// Not sure this is useful but oh well
require(_tokenToClaim <= maxTokenId, "Claim: tokenId outbounds");
// Creating a hash unique to this token number, and this token contract
bytes32 _hash = keccak256(abi.encode(ERC721address, _tokenToClaim, _tokenURI));
// Making sure that the signer has been whitelisted
require(signerIsWhitelisted(_hash, _signature), "Claim: signer not whitelisted");
// All should be good, so we mint a token yeah
ERC721MetadataMintable targetERC721Contract = ERC721MetadataMintable(ERC721address);
targetERC721Contract.mintWithTokenURI(msg.sender, _tokenToClaim, _tokenURI);
// Registering that the token was claimed
// Note that there is a check in the ERC721 for this too
tokensThatWereClaimed[_tokenToClaim] = true;
// Emitting an event
emit aTokenWasClaimed(_tokenToClaim, msg.sender);
// If a tip was included, thank the tipper
if (msg.value > 0) {
emit yeeeeeeaaaaaahThxCoeurCoeurCoeur(msg.sender);
totalFunds += msg.value;
}
}
function withdrawTips() public onlyWhitelisted {
msg.sender.transfer(totalFunds);
emit withdrawFunds(msg.sender, totalFunds );
}
// 20/02/27: Borrowed from https://github.com/austintgriffith/bouncer-proxy/blob/master/BouncerProxy/BouncerProxy.sol
//borrowed from OpenZeppelin's ESDA stuff:
//https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/ECDSA.sol
function signerIsWhitelisted(bytes32 _hash, bytes memory _signature) internal view returns (bool) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (_signature.length != 65) {
return false;
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return false;
} else {
// solium-disable-next-line arg-overflow
return whitelist[ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s)];
}
}
// 20/02/27: Borrowed from https://github.com/rocksideio/contracts/blob/master/contracts/Identity.sol
function updateWhitelist(address _account, bool _value) onlyWhitelisted public returns (bool) {
whitelist[_account] = _value;
emit UpdateWhitelist(_account, _value);
return true;
}
modifier onlyWhitelisted() {
require(whitelist[msg.sender], "Account Not Whitelisted");
_;
}
} | updateWhitelist | function updateWhitelist(address _account, bool _value) onlyWhitelisted public returns (bool) {
whitelist[_account] = _value;
emit UpdateWhitelist(_account, _value);
return true;
}
| // 20/02/27: Borrowed from https://github.com/rocksideio/contracts/blob/master/contracts/Identity.sol | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://45f1717a79bde92515920374a30077a127b7f7e73088c98aa39d9dadf20483c0 | {
"func_code_index": [
3756,
3965
]
} | 58,500 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} | totalSupply | function totalSupply() constant returns (uint supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
60,
121
]
} | 58,501 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
229,
303
]
} | 58,502 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} | transfer | function transfer(address _to, uint _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
540,
614
]
} | 58,503 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} | transferFrom | function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
937,
1030
]
} | 58,504 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} | approve | function approve(address _spender, uint _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
1314,
1392
]
} | 58,505 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
1600,
1694
]
} | 58,506 |
||
Martian | Martian.sol | 0x5970849dc4a10020830649e3d014f67329217255 | Solidity | UnboundedRegularToken | contract UnboundedRegularToken is RegularToken {
uint constant MAX_UINT = 2**256 - 1;
/// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited amount.
/// @param _from Address to transfer from.
/// @param _to Address to transfer to.
/// @param _value Amount to transfer.
/// @return Success of transfer.
function transferFrom(address _from, address _to, uint _value)
public
returns (bool)
{
uint allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value
&& allowance >= _value
&& balances[_to] + _value >= balances[_to]
) {
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
} | transferFrom | function transferFrom(address _from, address _to, uint _value)
public
returns (bool)
{
uint allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value
&& allowance >= _value
&& balances[_to] + _value >= balances[_to]
) {
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
| /// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited amount.
/// @param _from Address to transfer from.
/// @param _to Address to transfer to.
/// @param _value Amount to transfer.
/// @return Success of transfer. | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | None | bzzr://b152938db181568dba3615f82c106d6ea9f79d917690d64f7917750906659123 | {
"func_code_index": [
383,
1016
]
} | 58,507 |
||
WDXSale | WDXSale.sol | 0x401542ff8a723b6b6124ada9aaeeca5de723b3c2 | Solidity | WDXSale | contract WDXSale {
IERC20Token public tokenContract; // the token being sold
uint256 public price; // the price, in wei, per token
address owner;
uint256 public tokensSold;
event Sold(address buyer, uint256 amount);
constructor(IERC20Token _tokenContract, uint256 _price) public {
owner = msg.sender;
tokenContract = _tokenContract;
price = _price;
}
// Guards against integer overflows
function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
} else {
uint256 c = a * b;
assert(c / a == b);
return c;
}
}
function safeDivision(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function buyTokens(uint256 numberOfTokens) public payable {
require(msg.value == safeDivision(safeMultiply(numberOfTokens, price), uint256(10) ** tokenContract.decimals()));
require(tokenContract.balanceOf(address(this)) >= numberOfTokens);
emit Sold(msg.sender, numberOfTokens);
tokensSold += numberOfTokens;
tokenContract.transfer(msg.sender, numberOfTokens);
}
function() external payable {
uint256 numberOfTokens = safeMultiply(safeDivision(msg.value, price), uint256(10) ** tokenContract.decimals());
emit Sold(msg.sender, numberOfTokens);
tokensSold += numberOfTokens;
tokenContract.transfer(msg.sender, numberOfTokens);
}
function endSale() public {
require(msg.sender == owner);
// Send unsold tokens to the owner.
require(tokenContract.transfer(owner, tokenContract.balanceOf(address(this))));
msg.sender.transfer(address(this).balance);
}
function getEther() public {
require(msg.sender == owner);
msg.sender.transfer(address(this).balance);
}
} | safeMultiply | function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
} else {
uint256 c = a * b;
assert(c / a == b);
return c;
}
}
| // Guards against integer overflows | LineComment | v0.5.8+commit.23d335f2 | None | bzzr://bf69d91d1faf1d592665e09f2418bc7084b2e09a67df2b5c9341c6ee4d54e76b | {
"func_code_index": [
477,
729
]
} | 58,508 |
||
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | PersepolisCoin | function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
| // ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
461,
810
]
} | 58,509 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | totalSupply | function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
998,
1119
]
} | 58,510 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | balanceOf | function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
1339,
1468
]
} | 58,511 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transfer | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
1812,
2089
]
} | 58,512 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approve | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
2596,
2804
]
} | 58,513 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
3334,
3692
]
} | 58,514 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | allowance | function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| // ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
3975,
4131
]
} | 58,515 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approveAndCall | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
4486,
4803
]
} | 58,516 |
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | function () public payable {
revert();
}
| // ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
4995,
5054
]
} | 58,517 |
|
PersepolisCoin | PersepolisCoin.sol | 0xf2139ebfd1532564a74f6836ecb0080355264768 | Solidity | PersepolisCoin | contract PersepolisCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function PersepolisCoin() public {
symbol = "PPC";
name = "Persepolis Coin";
decimals = 18;
_totalSupply = 25000000000000000000000000;
balances[0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3] = _totalSupply;
Transfer(address(0), 0x99928c79Fe7aadff1aFC9a15296B9c2a686f10B3, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferAnyERC20Token | function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
| // ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------ | LineComment | v0.4.20+commit.3155dd80 | None | bzzr://227de64d4b1dc1e103d22fe4f3a1e73edf5f5b35bf1403ae78cb96321d4f73a9 | {
"func_code_index": [
5287,
5476
]
} | 58,518 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | initializeCustom | function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
| /// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
4304,
5258
]
} | 58,519 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | /// @notice Allow fund transfers to DAO contract. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
5738,
5793
]
} | 58,520 |
||
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | daoCreator | function daoCreator() public override view returns (address) {
return _creator;
}
| /// @notice Address of DAO creator.
/// @return DAO creator address. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
5893,
5985
]
} | 58,521 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | voteWeight | function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
| /// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
6083,
6327
]
} | 58,522 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | votesOf | function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
| /// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
6455,
6599
]
} | 58,523 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | tokenAddress | function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
| /// @notice Address of the governing token.
/// @return address of the governing token. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
6696,
6806
]
} | 58,524 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | holdings | function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
| /// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
6915,
7228
]
} | 58,525 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | liquidities | function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
| /// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
7348,
7687
]
} | 58,526 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | liquidityToken | function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
| /// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
7887,
8056
]
} | 58,527 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | liquidityHoldings | function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
| /// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
8228,
8718
]
} | 58,528 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | admins | function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
| /// @notice DAO admins.
/// @return Array of admin addresses. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
8789,
9084
]
} | 58,529 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | tokenBalance | function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
| /// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
9228,
9367
]
} | 58,530 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | liquidityBalance | function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
| /// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
9532,
9672
]
} | 58,531 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | availableBalance | function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
| /// @notice DAO ethereum balance.
/// @return uint256 wei balance. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
9748,
9859
]
} | 58,532 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | maxCost | function maxCost() public override view returns (uint256) {
return _maxCost;
}
| /// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
9964,
10053
]
} | 58,533 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | executeMinPct | function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
| /// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
10181,
10282
]
} | 58,534 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | votingMinHours | function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
| /// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
10417,
10520
]
} | 58,535 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | isPublic | function isPublic() public override view returns (bool) {
return _isPublic;
}
| /// @notice Whether DAO is public or private.
/// @return bool true if public. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
10608,
10696
]
} | 58,536 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | hasAdmins | function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
| /// @notice Whether DAO has admins.
/// @return bool true if DAO has admins. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
10782,
10872
]
} | 58,537 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | getProposalIds | function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
| /// @notice Proposal ids of DAO.
/// @return array of proposal ids. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
10949,
11283
]
} | 58,538 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | getProposal | function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
| /// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
12014,
12764
]
} | 58,539 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | canVote | function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
| /// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
13004,
13312
]
} | 58,540 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | canRemove | function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
| /// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
13549,
13876
]
} | 58,541 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | canExecute | function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
| /// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
14117,
16097
]
} | 58,542 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | isAdmin | function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
| /// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such). | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
16290,
16446
]
} | 58,543 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | addHoldingsAddresses | function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
| /// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
16595,
16926
]
} | 58,544 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | addLiquidityAddresses | function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
| /// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
17050,
17403
]
} | 58,545 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | propose | function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
| /// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
17864,
19605
]
} | 58,546 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | unpropose | function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
| /// @notice Removes existing proposal.
/// @param id_ id of proposal to remove. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
19694,
20453
]
} | 58,547 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | vote | function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
| /// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
20608,
21857
]
} | 58,548 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | execute | function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
| /// @notice Executes a proposal.
/// @param id_ id of proposal to be executed. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
21945,
24264
]
} | 58,549 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | buy | function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
| /// @notice Buying tokens for cloned DAO. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
24312,
24898
]
} | 58,550 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | sell | function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
| /// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
24996,
25755
]
} | 58,551 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _supplyShare | function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
| /// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
25952,
26660
]
} | 58,552 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _circulatingMaxCost | function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
| /// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
26923,
27103
]
} | 58,553 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _circulatingSupply | function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
| /// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
27284,
27538
]
} | 58,554 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeBuy | function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
| /// @notice Execution of BUY proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
27647,
28785
]
} | 58,555 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeSell | function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
| /// @notice Execution of SELL proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
28865,
29963
]
} | 58,556 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeAddLiquidity | function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
| /// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
30052,
31362
]
} | 58,557 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeRemoveLiquidity | function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
| /// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
31454,
32339
]
} | 58,558 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeAddAdmin | function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
| /// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
32423,
32956
]
} | 58,559 |
TorroDao | TorroDao.sol | 0x3cf9e9d45380b6ab61bde46b2e6cfcd7d8f6cdc1 | Solidity | TorroDao | contract TorroDao is ITorroDao, OwnableUpgradeSafe {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeMath for uint256;
// Structs.
/// @notice General proposal structure.
struct Proposal {
uint256 id;
address proposalAddress;
address investTokenAddress;
DaoFunction daoFunction;
uint256 amount;
address creator;
uint256 endLifetime;
EnumerableSet.AddressSet voterAddresses;
uint256 votesFor;
uint256 votesAgainst;
bool executed;
}
// Events.
/// @notice Event for dispatching on new proposal creation.
/// @param id id of the new proposal.
event NewProposal(uint256 id);
/// @notice Event for dispatching when proposal has been removed.
/// @param id id of the removed proposal.
event RemoveProposal(uint256 id);
/// @notice Event for dispatching when someone voted on a proposal.
/// @param id id of the voted proposal.
event Vote(uint256 id);
/// @notice Event for dispatching when an admin has been added to the DAO.
/// @param admin address of the admin that's been added.
event AddAdmin(address admin);
/// @notice Event for dispatching when an admin has been removed from the DAO.
/// @param admin address of the admin that's been removed.
event RemoveAdmin(address admin);
/// @notice Event for dispatching when a proposal has been executed.
/// @param id id of the executed proposal.
event ExecutedProposal(uint256 id);
/// @notice Event for dispatching when cloned DAO tokens have been bought.
event Buy();
/// @notice Event for dispatching when cloned DAO tokens have been sold.
event Sell();
/// @notice Event for dispatching when new holdings addresses have been changed.
event HoldingsAddressesChanged();
/// @notice Event for dipatching when new liquidity addresses have been changed.
event LiquidityAddressesChanged();
// Constants.
// Private data.
address private _creator;
EnumerableSet.AddressSet private _holdings;
EnumerableSet.AddressSet private _liquidityAddresses;
EnumerableSet.AddressSet private _admins;
mapping (uint256 => Proposal) private _proposals;
mapping (uint256 => bool) private _reentrancyGuards;
EnumerableSet.UintSet private _proposalIds;
ITorro private _torroToken;
ITorro private _governingToken;
address private _factory;
uint256 private _latestProposalId;
uint256 private _timeout;
uint256 private _maxCost;
uint256 private _executeMinPct;
uint256 private _votingMinHours;
uint256 private _voteWeightDivider;
uint256 private _lastWithdraw;
uint256 private _spendDivider;
bool private _isPublic;
bool private _isMain;
bool private _hasAdmins;
// ===============
IUniswapV2Router02 private _router;
// Constructor.
/// @notice Constructor for original Torro DAO.
/// @param governingToken_ Torro token address.
constructor(address governingToken_) public {
__Ownable_init();
_torroToken = ITorro(governingToken_);
_governingToken = ITorro(governingToken_);
_factory = address(0x0);
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = 0;
_executeMinPct = 5;
_votingMinHours = 6;
_voteWeightDivider = 10000;
_lastWithdraw = block.timestamp.add(1 * 1 weeks);
_spendDivider = 10;
_isMain = true;
_isPublic = true;
_hasAdmins = true;
_creator = msg.sender;
}
/// @notice Initializer for DAO clones.
/// @param torroToken_ main torro token address.
/// @param governingToken_ torro token clone that's governing this dao.
/// @param factory_ torro factory address.
/// @param creator_ creator of cloned DAO.
/// @param maxCost_ maximum cost of all governing tokens for cloned DAO.
/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.
/// @param votingMinHours_ minimum lifetime of proposal before it closes.
/// @param isPublic_ whether cloned DAO has public visibility.
/// @param hasAdmins_ whether cloned DAO has admins, otherwise all stakers are treated as admins.
function initializeCustom(
address torroToken_,
address governingToken_,
address factory_,
address creator_,
uint256 maxCost_,
uint256 executeMinPct_,
uint256 votingMinHours_,
bool isPublic_,
bool hasAdmins_
) public override initializer {
__Ownable_init();
_torroToken = ITorro(torroToken_);
_governingToken = ITorro(governingToken_);
_factory = factory_;
_latestProposalId = 0;
_timeout = uint256(5).mul(1 minutes);
_router = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
_maxCost = maxCost_;
_voteWeightDivider = 0;
_executeMinPct = executeMinPct_;
_votingMinHours = votingMinHours_;
_lastWithdraw = block.timestamp;
_spendDivider = 0;
_isMain = false;
_isPublic = isPublic_;
_hasAdmins = hasAdmins_;
_creator = creator_;
if (_hasAdmins) {
_admins.add(creator_);
}
}
// Modifiers.
/// @notice Stops double execution of proposals.
/// @param id_ proposal id that's executing.
modifier nonReentrant(uint256 id_) {
// check that it's already not executing
require(!_reentrancyGuards[id_]);
// toggle state that proposal is currently executing
_reentrancyGuards[id_] = true;
_;
// toggle state back
_reentrancyGuards[id_] = false;
}
/// @notice Allow fund transfers to DAO contract.
receive() external payable {
// do nothing
}
// Public calls.
/// @notice Address of DAO creator.
/// @return DAO creator address.
function daoCreator() public override view returns (address) {
return _creator;
}
/// @notice Amount of tokens needed for a single vote.
/// @return uint256 token amount.
function voteWeight() public override view returns (uint256) {
uint256 weight;
if (_isMain) {
weight = _governingToken.totalSupply() / _voteWeightDivider;
} else {
weight = 10**18;
}
return weight;
}
/// @notice Amount of votes that holder has.
/// @param sender_ address of the holder.
/// @return number of votes.
function votesOf(address sender_) public override view returns (uint256) {
return _governingToken.stakedOf(sender_) / voteWeight();
}
/// @notice Address of the governing token.
/// @return address of the governing token.
function tokenAddress() public override view returns (address) {
return address(_governingToken);
}
/// @notice Saved addresses of tokens that DAO is holding.
/// @return array of holdings addresses.
function holdings() public override view returns (address[] memory) {
uint256 length = _holdings.length();
address[] memory holdingsAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
holdingsAddresses[i] = _holdings.at(i);
}
return holdingsAddresses;
}
/// @notice Saved addresses of liquidity tokens that DAO is holding.
/// @return array of liquidity addresses.
function liquidities() public override view returns (address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory liquidityAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
liquidityAddresses[i] = _liquidityAddresses.at(i);
}
return liquidityAddresses;
}
/// @notice Calculates address of liquidity token from ERC-20 token address.
/// @param token_ token address to calculate liquidity address from.
/// @return address of liquidity token.
function liquidityToken(address token_) public override view returns (address) {
return UniswapV2Library.pairFor(_router.factory(), token_, _router.WETH());
}
/// @notice Gets tokens and liquidity token addresses of DAO's liquidity holdings.
/// @return Arrays of tokens and liquidity tokens, should have the same length.
function liquidityHoldings() public override view returns (address[] memory, address[] memory) {
uint256 length = _liquidityAddresses.length();
address[] memory tokens = new address[](length);
address[] memory liquidityTokens = new address[](length);
for (uint256 i = 0; i < length; i++) {
address token = _liquidityAddresses.at(i);
tokens[i] = token;
liquidityTokens[i] = liquidityToken(token);
}
return (tokens, liquidityTokens);
}
/// @notice DAO admins.
/// @return Array of admin addresses.
function admins() public override view returns (address[] memory) {
uint256 length = _admins.length();
address[] memory currentAdmins = new address[](length);
for (uint256 i = 0; i < length; i++) {
currentAdmins[i] = _admins.at(i);
}
return currentAdmins;
}
/// @notice DAO balance for specified token.
/// @param token_ token address to get balance for.
/// @return uint256 token balance.
function tokenBalance(address token_) public override view returns (uint256) {
return IERC20(token_).balanceOf(address(this));
}
/// @notice DAO balance for liquidity token.
/// @param token_ token address to get liquidity balance for.
/// @return uin256 token liquidity balance.
function liquidityBalance(address token_) public override view returns (uint256) {
return tokenBalance(liquidityToken(token_));
}
/// @notice DAO ethereum balance.
/// @return uint256 wei balance.
function availableBalance() public override view returns (uint256) {
return address(this).balance;
}
/// @notice Maximum cost for all tokens of cloned DAO.
/// @return uint256 maximum cost in wei.
function maxCost() public override view returns (uint256) {
return _maxCost;
}
/// @notice Minimum percentage of votes needed to execute a proposal.
/// @return uint256 minimum percentage of votes.
function executeMinPct() public override view returns (uint256) {
return _executeMinPct;
}
/// @notice Minimum lifetime of proposal before it closes.
/// @return uint256 minimum number of hours for proposal lifetime.
function votingMinHours() public override view returns (uint256) {
return _votingMinHours;
}
/// @notice Whether DAO is public or private.
/// @return bool true if public.
function isPublic() public override view returns (bool) {
return _isPublic;
}
/// @notice Whether DAO has admins.
/// @return bool true if DAO has admins.
function hasAdmins() public override view returns (bool) {
return _hasAdmins;
}
/// @notice Proposal ids of DAO.
/// @return array of proposal ids.
function getProposalIds() public override view returns (uint256[] memory) {
uint256 proposalsLength = _proposalIds.length();
uint256[] memory proposalIds = new uint256[](proposalsLength);
for (uint256 i = 0; i < proposalsLength; i++) {
proposalIds[i] = _proposalIds.at(i);
}
return proposalIds;
}
/// @notice Gets proposal info for proposal id.
/// @param id_ id of proposal to get info for.
/// @return proposalAddress address for proposal execution.
/// @return investTokenAddress secondary address for proposal execution, used for investment proposals if ICO and token addresses differ.
/// @return daoFunction proposal type.
/// @return amount proposal amount eth/token to use during execution.
/// @return creator address of proposal creator.
/// @return endLifetime epoch time when proposal voting ends.
/// @return votesFor amount of votes for the proposal.
/// @return votesAgainst amount of votes against the proposal.
/// @return executed whether proposal has been executed or not.
function getProposal(uint256 id_) public override view returns (
address proposalAddress,
address investTokenAddress,
DaoFunction daoFunction,
uint256 amount,
address creator,
uint256 endLifetime,
uint256 votesFor,
uint256 votesAgainst,
bool executed
) {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
return (
currentProposal.proposalAddress,
currentProposal.investTokenAddress,
currentProposal.daoFunction,
currentProposal.amount,
currentProposal.creator,
currentProposal.endLifetime,
currentProposal.votesFor,
currentProposal.votesAgainst,
currentProposal.executed
);
}
/// @notice Whether a holder is allowed to vote for a proposal.
/// @param id_ proposal id to check whether holder is allowed to vote for.
/// @param sender_ address of the holder.
/// @return bool true if voting is allowed.
function canVote(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.creator != sender_ && !proposal.voterAddresses.contains(sender_);
}
/// @notice Whether a holder is allowed to remove a proposal.
/// @param id_ proposal id to check whether holder is allowed to remove.
/// @param sender_ address of the holder.
/// @return bool true if removal is allowed.
function canRemove(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
return proposal.endLifetime >= block.timestamp && proposal.voterAddresses.length() == 1 && (proposal.creator == sender_ || owner() == sender_);
}
/// @notice Whether a holder is allowed to execute a proposal.
/// @param id_ proposal id to check whether holder is allowed to execute.
/// @param sender_ address of the holder.
/// @return bool true if execution is allowed.
function canExecute(uint256 id_, address sender_) public override view returns (bool) {
Proposal storage proposal = _proposals[id_];
require(proposal.id == id_);
// check that proposal hasn't been executed yet.
if (proposal.executed) {
return false;
}
// if custom pool has admins then only admins can execute proposals
if (!_isMain && _hasAdmins) {
if (!isAdmin(sender_)) {
return false;
}
}
if (proposal.daoFunction == DaoFunction.INVEST) {
// for invest functions only admins can execute
if (sender_ != _creator && !_admins.contains(sender_)) {
return false;
}
// check that sender is proposal creator or admin
} else if (proposal.creator != sender_ && !isAdmin(sender_)) {
return false;
}
// For main pool Buy and Sell dao functions allow instant executions if at least 10% of staked supply has voted for it
if (_isMain && (proposal.daoFunction == DaoFunction.BUY || proposal.daoFunction == DaoFunction.SELL)) {
if (proposal.votesFor.mul(voteWeight()) >= _governingToken.stakedSupply() / 10) {
if (proposal.votesFor > proposal.votesAgainst) {
// only allow admins to execute buy and sell proposals early
return isAdmin(sender_);
}
}
}
// check that proposal voting lifetime has run out.
if (proposal.endLifetime > block.timestamp) {
return false;
}
// check that votes for outweigh votes against.
bool currentCanExecute = proposal.votesFor > proposal.votesAgainst;
if (currentCanExecute && _executeMinPct > 0) {
// Check that proposal has at least _executeMinPct% of staked votes.
uint256 minVotes = _governingToken.stakedSupply() / (100 / _executeMinPct);
currentCanExecute = minVotes <= proposal.votesFor.add(proposal.votesAgainst).mul(voteWeight());
}
return currentCanExecute;
}
/// @notice Whether a holder is an admin.
/// @param sender_ address of holder.
/// @return bool true if holder is an admin (in DAO without admins all holders are treated as such).
function isAdmin(address sender_) public override view returns (bool) {
return !_hasAdmins || sender_ == _creator || _admins.contains(sender_);
}
// Public transactions.
/// @notice Saves new holdings addresses for DAO.
/// @param tokens_ token addresses that DAO has holdings of.
function addHoldingsAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_holdings.contains(token)) {
_holdings.add(token);
}
}
emit HoldingsAddressesChanged();
}
/// @notice Saves new liquidity addresses for DAO.
/// @param tokens_ token addresses that DAO has liquidities of.
function addLiquidityAddresses(address[] memory tokens_) public override {
require(isAdmin(msg.sender));
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i];
if (!_liquidityAddresses.contains(token)) {
_liquidityAddresses.add(token);
}
}
emit LiquidityAddressesChanged();
}
/// @notice Creates new proposal.
/// @param proposalAddress_ main address of the proposal, in investment proposals this is the address funds are sent to.
/// @param investTokenAddress_ secondary address of the proposal, used in investment proposals to specify token address.
/// @param daoFunction_ type of the proposal.
/// @param amount_ amount of funds to use in the proposal.
/// @param hoursLifetime_ voting lifetime of the proposal.
function propose(address proposalAddress_, address investTokenAddress_, DaoFunction daoFunction_, uint256 amount_, uint256 hoursLifetime_) public override {
// check that lifetime is at least equals to min hours set for DAO.
require(hoursLifetime_ >= _votingMinHours);
// Check that proposal creator is allowed to create a proposal.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// For main DAO.
if (_isMain) {
if (daoFunction_ == DaoFunction.WITHDRAW || daoFunction_ == DaoFunction.INVEST || daoFunction_ == DaoFunction.BUY) {
// Limit each buy, investment and withdraw proposals to 10% of ETH funds.
require(amount_ <= (availableBalance() / _spendDivider));
}
}
// Increment proposal id counter.
_latestProposalId++;
uint256 currentId = _latestProposalId;
// Calculate end lifetime of the proposal.
uint256 endLifetime = block.timestamp.add(hoursLifetime_.mul(1 hours));
// Declare voter addresses set.
EnumerableSet.AddressSet storage voterAddresses;
// Save proposal struct.
_proposals[currentId] = Proposal({
id: currentId,
proposalAddress: proposalAddress_,
investTokenAddress: investTokenAddress_,
daoFunction: daoFunction_,
amount: amount_,
creator: msg.sender,
endLifetime: endLifetime,
voterAddresses: voterAddresses,
votesFor: balance / weight,
votesAgainst: 0,
executed: false
});
// Save id of new proposal.
_proposalIds.add(currentId);
// Emit event that new proposal has been created.
emit NewProposal(currentId);
}
/// @notice Removes existing proposal.
/// @param id_ id of proposal to remove.
function unpropose(uint256 id_) public override {
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
// Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal.
if (msg.sender != _creator) {
require(currentProposal.voterAddresses.length() == 1);
}
// Remove proposal.
delete _proposals[id_];
_proposalIds.remove(id_);
// Emit event that a proposal has been removed.
emit RemoveProposal(id_);
}
/// @notice Voting for multiple proposals.
/// @param ids_ ids of proposals to vote for.
/// @param votes_ for or against votes for proposals.
function vote(uint256[] memory ids_, bool[] memory votes_) public override {
// Check that arrays of the same length have been supplied.
require(ids_.length == votes_.length);
// Check that voter has enough tokens staked to vote.
uint256 balance = _governingToken.stakedOf(msg.sender);
uint256 weight = voteWeight();
require(balance >= weight);
// Get number of votes that msg.sender has.
uint256 votesCount = balance / weight;
// Iterate over voted proposals.
for (uint256 i = 0; i < ids_.length; i++) {
uint256 id = ids_[i];
bool currentVote = votes_[i];
Proposal storage proposal = _proposals[id];
// Check that proposal hasn't been voted for by msg.sender and that it's still active.
if (!proposal.voterAddresses.contains(msg.sender) && proposal.endLifetime >= block.timestamp) {
// Add votes.
proposal.voterAddresses.add(msg.sender);
if (currentVote) {
proposal.votesFor = proposal.votesFor.add(votesCount);
} else {
proposal.votesAgainst = proposal.votesAgainst.add(votesCount);
}
}
// Emit event that a proposal has been voted for.
emit Vote(id);
}
}
/// @notice Executes a proposal.
/// @param id_ id of proposal to be executed.
function execute(uint256 id_) public override nonReentrant(id_) {
// save gas at the start of execution
uint256 remainingGasStart = gasleft();
// check whether proposal can be executed by the sender
require(canExecute(id_, msg.sender));
Proposal storage currentProposal = _proposals[id_];
require(currentProposal.id == id_);
// Check that msg.sender has balance for at least 1 vote to execute a proposal.
uint256 balance = _governingToken.totalOf(msg.sender);
if (balance < voteWeight()) {
// Remove admin if his balance is not high enough.
if (_admins.contains(msg.sender)) {
_admins.remove(msg.sender);
}
revert();
}
// Call private function for proposal execution depending on the type.
if (currentProposal.daoFunction == DaoFunction.BUY) {
_executeBuy(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.SELL) {
_executeSell(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_LIQUIDITY) {
_executeAddLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_LIQUIDITY) {
_executeRemoveLiquidity(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.ADD_ADMIN) {
_executeAddAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.REMOVE_ADMIN) {
_executeRemoveAdmin(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.INVEST) {
_executeInvest(currentProposal);
} else if (currentProposal.daoFunction == DaoFunction.WITHDRAW) {
_executeWithdraw(currentProposal);
}
// Mark proposal as executed.
currentProposal.executed = true;
// calculate gas used during execution
uint256 remainingGasEnd = gasleft();
uint256 usedGas = remainingGasStart.sub(remainingGasEnd).add(35000);
// max gas price allowed for refund is 200gwei
uint256 gasPrice;
if (tx.gasprice > 200000000000) {
gasPrice = 200000000000;
} else {
gasPrice = tx.gasprice;
}
// refund used gas
payable(msg.sender).transfer(usedGas.mul(gasPrice));
// Emit event that proposal has been executed.
emit ExecutedProposal(id_);
}
/// @notice Buying tokens for cloned DAO.
function buy() public override payable {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender is not sending more money than max cost of dao.
require(msg.value <= _maxCost);
// Check that DAO has enough tokens to sell to msg.sender.
uint256 portion = _governingToken.totalSupply().mul(msg.value) / _maxCost;
require(_governingToken.balanceOf(address(this)) >= portion);
// Transfer tokens.
_governingToken.transfer(msg.sender, portion);
// Emit event that tokens have been bought.
emit Buy();
}
/// @notice Sell tokens back to cloned DAO.
/// @param amount_ amount of tokens to sell.
function sell(uint256 amount_) public override {
// Check that it's not the main DAO.
require(!_isMain);
// Check that msg.sender has enough tokens to sell.
require(_governingToken.balanceOf(msg.sender) >= amount_);
// Calculate the eth share holder should get back and whether pool has enough funds.
uint256 share = _supplyShare(amount_);
// Approve token transfer for DAO.
_governingToken.approveDao(msg.sender, amount_);
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
// Refund eth back to the msg.sender.
payable(msg.sender).transfer(share);
// Emit event that tokens have been sold back to DAO.
emit Sell();
}
// Private calls.
/// @notice Calculates cost of share of the supply.
/// @param amount_ amount of tokens to calculate eth share for.
/// @return price for specified amount share.
function _supplyShare(uint256 amount_) private view returns (uint256) {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingSupply = _circulatingSupply(totalSupply);
uint256 circulatingMaxCost = _circulatingMaxCost(circulatingSupply, totalSupply);
// Check whether available balance is higher than circulating max cost.
if (availableBalance() > circulatingMaxCost) {
// If true then share will equal to buy price.
return circulatingMaxCost.mul(amount_) / circulatingSupply;
} else {
// Otherwise calculate share price based on currently available balance.
return availableBalance().mul(amount_) / circulatingSupply;
}
}
/// @notice Calculates max cost for currently circulating supply.
/// @param circulatingSupply_ governing token circulating supply.
/// @param totalSupply_ governing token total supply.
/// @return uint256 eth cost of currently circulating supply.
function _circulatingMaxCost(uint256 circulatingSupply_, uint256 totalSupply_) private view returns (uint256) {
return _maxCost.mul(circulatingSupply_) / totalSupply_;
}
/// @notice Calculates circulating supply of governing token.
/// @param totalSupply_ governing token total supply.
/// @return uint256 number of tokens in circulation.
function _circulatingSupply(uint256 totalSupply_) private view returns (uint256) {
uint256 balance = _governingToken.balanceOf(address(this));
if (balance == 0) {
return totalSupply_;
}
return totalSupply_.sub(balance);
}
// Private transactions.
/// @notice Execution of BUY proposal.
/// @param proposal_ proposal.
function _executeBuy(Proposal storage proposal_) private {
// Check that DAO has enough funds to execute buy proposal.
require(availableBalance() >= proposal_.amount);
// Deposit eth funds to Uniswap router.
IWETH weth = IWETH(_router.WETH());
weth.deposit{value: proposal_.amount}();
// Create path for buying, buying is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = proposal_.proposalAddress;
// Execute uniswap buy.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactETHForTokens{value: proposal_.amount}(amountOut, path, address(this), block.timestamp.add(_timeout));
// If new token then save it holdings addresses.
if (!_holdings.contains(proposal_.proposalAddress)) {
_holdings.add(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of SELL proposal.
/// @param proposal_ proposal.
function _executeSell(Proposal storage proposal_) private {
// Approve uniswap router to sell tokens.
IERC20 token = IERC20(proposal_.proposalAddress);
require(token.approve(address(_router), proposal_.amount));
// Create path for selling, selling is only for Token-ETH pair.
address[] memory path = new address[](2);
path[0] = proposal_.proposalAddress;
path[1] = _router.WETH();
// Execute uniswap sell.
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), path[0], path[1]);
uint256 amountOut = UniswapV2Library.getAmountOut(proposal_.amount, reserveA, reserveB);
_router.swapExactTokensForETH(proposal_.amount, amountOut, path, address(this), block.timestamp.add(_timeout));
// If sold all tokens then remove it from holdings.
if (token.balanceOf(address(this)) == 0 && _holdings.contains(proposal_.proposalAddress)) {
_holdings.remove(proposal_.proposalAddress);
// Emit event that holdings addresses changed.
emit HoldingsAddressesChanged();
}
}
/// @notice Execution of ADD_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeAddLiquidity(Proposal storage proposal_) private {
// Approve uniswap route to transfer tokens.
require(IERC20(proposal_.proposalAddress).approve(address(_router), proposal_.amount));
// Calculate amount of tokens and eth needed for liquidity.
IWETH weth = IWETH(_router.WETH());
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(_router.factory(), proposal_.proposalAddress, address(weth));
uint256 wethAmount = UniswapV2Library.quote(proposal_.amount, reserveA, reserveB);
// Check that DAO has sufficient eth balance for liquidity.
require (availableBalance() > wethAmount);
// Deposit eth for liqudity.
weth.deposit{value: wethAmount}();
// Execute uniswap add liquidity.
_router.addLiquidityETH{value: wethAmount}(
proposal_.proposalAddress,
proposal_.amount,
(proposal_.amount / 100).mul(98),
(wethAmount / 100).mul(98),
address(this),
block.timestamp.add(_timeout)
);
// If new liquidity token then save it.
if (!_liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.add(proposal_.proposalAddress);
// Emit event that liquidity addresses changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of REMOVE_LIQUIDITY proposal.
/// @param proposal_ proposal.
function _executeRemoveLiquidity(Proposal storage proposal_) private {
// Approve uniswap router to transfer liquidity tokens.
address liquidityTokenAddress = liquidityToken(proposal_.proposalAddress);
require(IERC20(liquidityTokenAddress).approve(address(_router), proposal_.amount));
// Execute uniswap liquidity removal.
_router.removeLiquidityETH(
proposal_.proposalAddress,
proposal_.amount,
0,
0,
address(this),
block.timestamp.add(_timeout)
);
// If all tokens have been sold then remove liquidty address.
if (tokenBalance(liquidityTokenAddress) == 0 && _liquidityAddresses.contains(proposal_.proposalAddress)) {
_liquidityAddresses.remove(proposal_.proposalAddress);
// Emit event that liquidity addresses have changed.
emit LiquidityAddressesChanged();
}
}
/// @notice Execution of ADD_ADMIN proposal.
/// @param proposal_ propsal.
function _executeAddAdmin(Proposal storage proposal_) private {
// Check that address is not an admin already.
require(!_admins.contains(proposal_.proposalAddress));
// Check that holder has sufficient balance to be an admin.
uint256 balance = _governingToken.totalOf(proposal_.proposalAddress);
require(balance >= voteWeight());
// Add admin.
_admins.add(proposal_.proposalAddress);
// Emit event that new admin has been added.
emit AddAdmin(proposal_.proposalAddress);
}
/// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal.
function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
/// @notice Execution of INVEST proposal.
/// @param proposal_ proposal.
function _executeInvest(Proposal storage proposal_) private {
// Check that DAO has sufficient balance for investment.
require(availableBalance() >= proposal_.amount);
// Transfer funds.
payable(proposal_.proposalAddress).call{value: proposal_.amount}("");
// If secondary address for invest token is specified then save it to holdings.
if(proposal_.investTokenAddress != address(0x0)) {
if (!_holdings.contains(proposal_.investTokenAddress)) {
_holdings.add(proposal_.investTokenAddress);
// Emit event that holdings addresses have changed.
emit HoldingsAddressesChanged();
}
}
}
/// @notice Execution of WITHDRAW proposal.
/// @param proposal_ proposal.
function _executeWithdraw(Proposal storage proposal_) private {
if (_isMain) {
// Main DAO only allows withdrawal once a week.
require(block.timestamp > _lastWithdraw.add(1 * 1 weeks));
_lastWithdraw = block.timestamp;
}
uint256 amount;
uint256 mainAmount;
uint256 currentBalance = availableBalance();
if (_isMain) {
mainAmount = 0;
amount = proposal_.amount;
// Check that withdrawal amount is not more than 10% of main DAO balance.
require(currentBalance / 10 >= amount);
} else {
uint256 totalSupply = _governingToken.totalSupply();
uint256 circulatingMaxCost = _circulatingMaxCost(_circulatingSupply(totalSupply), totalSupply);
// Check that cloned DAO balance is higher than circulating max cost.
require(currentBalance > circulatingMaxCost);
// Check that cloned DAO gains are enough to cover withdrawal.
require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
// 0.25% of withdrawal will be transfered to Main DAO stakers.
mainAmount = proposal_.amount / 400;
amount = proposal_.amount.sub(mainAmount);
}
// Transfer all withdrawal funds to Torro Factory.
ITorroFactory(_factory).depositBenefits{value: proposal_.amount}(address(_governingToken));
// Divide withdrawal between governing token stakers.
_governingToken.addBenefits(amount);
// If cloned DAO withdrawal then divide 0.25% of withdrawal between main token stakers.
if (mainAmount > 0) {
_torroToken.addBenefits(mainAmount);
}
}
// Owner calls.
// Owner transactions.
/// @notice Sets factory address.
/// @param factory_ address of TorroFactory.
function setFactoryAddress(address factory_) public override onlyOwner {
_factory = factory_;
}
/// @notice Sets vote weight divider.
/// @param weight_ weight divider for a single vote.
function setVoteWeightDivider(uint256 weight_) public override onlyOwner {
_voteWeightDivider = weight_;
}
/// @notice Sets new address for router.
/// @param router_ address for router.
function setRouter(address router_) public override onlyOwner {
_router = IUniswapV2Router02(router_);
}
/// @notice Sets divider for BUY, INVEST, WITHDAW proposals.
/// @param divider_ divider for BUY, INVEST, WITHDRAW proposals.
function setSpendDivider(uint256 divider_) public override onlyOwner {
_spendDivider = divider_;
}
/// @notice Migrates balances of current DAO to a new DAO.
/// @param newDao_ address of the new DAO to migrate to.
function migrate(address newDao_) public override onlyOwner {
ITorroDao dao = ITorroDao(newDao_);
// Migrate holdings.
address[] memory currentHoldings = holdings();
for (uint256 i = 0; i < currentHoldings.length; i++) {
_migrateTransferBalance(currentHoldings[i], newDao_);
}
dao.addHoldingsAddresses(currentHoldings);
// Migrate liquidities.
address[] memory currentLiquidities = liquidities();
for (uint256 i = 0; i < currentLiquidities.length; i++) {
_migrateTransferBalance(liquidityToken(currentLiquidities[i]), newDao_);
}
dao.addLiquidityAddresses(currentLiquidities);
// Send over ETH balance.
payable(newDao_).call{value: availableBalance()}("");
}
// Private owner calls.
/// @notice Private function for migrating token balance to a new address.
/// @param token_ address of ERC-20 token to migrate.
/// @param target_ migration end point address.
function _migrateTransferBalance(address token_, address target_) private {
if (token_ != address(0x0)) {
IERC20 erc20 = IERC20(token_);
uint256 balance = erc20.balanceOf(address(this));
if (balance > 0) {
erc20.transfer(target_, balance);
}
}
}
} | /// @title DAO for proposals, voting and execution.
/// @notice Contract for creation, voting and execution of proposals.
/// @author ORayskiy - @robitnik_TorroDao | NatSpecSingleLine | _executeRemoveAdmin | function _executeRemoveAdmin(Proposal storage proposal_) private {
// Check that address is an admin.
require(_admins.contains(proposal_.proposalAddress));
// Remove admin.
_admins.remove(proposal_.proposalAddress);
// Emit event that an admin has been removed.
emit RemoveAdmin(proposal_.proposalAddress);
}
| /// @notice Execution of REMOVE_ADMIN proposal.
/// @param proposal_ proposal. | NatSpecSingleLine | v0.6.6+commit.6c089d02 | Unknown | ipfs://d1c6095fcf143d951c9754f00fe8cd59d29ab460461efe53b91eb289fd0fe5ac | {
"func_code_index": [
33044,
33392
]
} | 58,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.