Transaction Hash:
Block:
11311302 at Nov-23-2020 12:35:49 AM +UTC
Transaction Fee:
0.004790175 ETH
$10.25
Gas Used:
73,695 Gas / 65 Gwei
Emitted Events:
| 268 |
OwnedUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000008362f1771b178e5e62efacf792084773520fdd0f, 0x0000000000000000000000000000000000000000000000000000000000000000, 000000000000000000000000000000000000000000005c9b8aa619fbfca01504 )
|
| 269 |
OwnedUpgradeabilityProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000a1e72267084192db7387c8cc1328fade470e4149, 0x0000000000000000000000008362f1771b178e5e62efacf792084773520fdd0f, 000000000000000000000000000000000000000000005c9b8aa6fa5bd0ad5227 )
|
| 270 |
OwnedUpgradeabilityProxy.0x920bb94eb3842a728db98228c375ff6b00c5bc5a54fac6736155517a0a20a61a( 0x920bb94eb3842a728db98228c375ff6b00c5bc5a54fac6736155517a0a20a61a, 0x0000000000000000000000008362f1771b178e5e62efacf792084773520fdd0f, 000000000000000000000000000000000000000000005c9b8aa619fbfca01504 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x00000000...ecd22b376 | |||||
|
0x5A0b54D5...D3E029c4c
Miner
| (Spark Pool) | 3.394545696853766737 Eth | 3.399335871853766737 Eth | 0.004790175 | |
| 0x8362f177...3520fDd0F |
2.499546813542182656 Eth
Nonce: 648
|
2.494756638542182656 Eth
Nonce: 649
| 0.004790175 | ||
| 0xa1e72267...E470e4149 |
Execution Trace
OwnedUpgradeabilityProxy.7f8661a1( )
TrueFiPool.exit( amount=437326952456825774019844 )
OwnedUpgradeabilityProxy.70a08231( )
-
TrueUSD.balanceOf( account=0xa1e72267084192Db7387c8CC1328fadE470e4149 ) => ( 30986857080493163196639252 )
-
-
Vyper_contract.balanceOf( arg0=0xa1e72267084192Db7387c8CC1328fadE470e4149 ) => ( 0 ) -
Vyper_contract.STATICCALL( ) -
Vyper_contract.balanceOf( arg0=0xa1e72267084192Db7387c8CC1328fadE470e4149 ) => ( out=0 )
0x16d02dc67eb237c387023339356b25d1d54b0922.e2c92a52( )-
0x886cf5bf695f975a939d49dfb29581db1dad9a89.e2c92a52( )
-
OwnedUpgradeabilityProxy.a9059cbb( )
-
TrueUSD.transfer( recipient=0x8362f1771B178e5e62efaCf792084773520fDd0F, amount=437326952703527958172199 ) => ( True )
-
exit[TrueFiPool (ln:1288)]
balanceOf[TrueFiPool (ln:1289)]totalSupply[TrueFiPool (ln:1291)]div[TrueFiPool (ln:1294)]mul[TrueFiPool (ln:1294)]currencyBalance[TrueFiPool (ln:1295)]sub[TrueFiPool (ln:1464)]balanceOf[TrueFiPool (ln:1464)]
div[TrueFiPool (ln:1298)]mul[TrueFiPool (ln:1298)]yTokenBalance[TrueFiPool (ln:1299)]add[TrueFiPool (ln:1219)]balanceOf[TrueFiPool (ln:1219)]token[TrueFiPool (ln:1219)]balanceOf[TrueFiPool (ln:1219)]
_burn[TrueFiPool (ln:1302)]distribute[TrueFiPool (ln:1305)]transfer[TrueFiPool (ln:1309)]ensureEnoughTokensAreAvailable[TrueFiPool (ln:1313)]balanceOf[TrueFiPool (ln:1245)]token[TrueFiPool (ln:1245)]withdraw[TrueFiPool (ln:1247)]sub[TrueFiPool (ln:1247)]
transfer[TrueFiPool (ln:1314)]token[TrueFiPool (ln:1314)]Exited[TrueFiPool (ln:1317)]
File 1 of 7: OwnedUpgradeabilityProxy
File 2 of 7: OwnedUpgradeabilityProxy
File 3 of 7: TrueFiPool
File 4 of 7: TrueUSD
File 5 of 7: Vyper_contract
File 6 of 7: Vyper_contract
File 7 of 7: Vyper_contract
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// SPDX-License-Identifier: MIT
// File: contracts/proxy/OwnedUpgradeabilityProxy.sol
pragma solidity 0.6.10;
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Event to show ownership transfer is pending
* @param currentOwner representing the address of the current owner
* @param pendingOwner representing the address of the pending owner
*/
event NewPendingOwner(address currentOwner, address pendingOwner);
// Storage position of the owner and pendingOwner of the contract
bytes32 private constant proxyOwnerPosition = 0x6279e8199720cf3557ecd8b58d667c8edc486bd1cf3ad59ea9ebdfcae0d0dfac; //keccak256("trueUSD.proxy.owner");
bytes32 private constant pendingProxyOwnerPosition = 0x8ddbac328deee8d986ec3a7b933a196f96986cb4ee030d86cc56431c728b83f4; //keccak256("trueUSD.pending.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
_setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "only Proxy Owner");
_;
}
/**
* @dev Throws if called by any account other than the pending owner.
*/
modifier onlyPendingProxyOwner() {
require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner");
_;
}
/**
* @dev Tells the address of the owner
* @return owner the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Tells the address of the owner
* @return pendingOwner the address of the pending owner
*/
function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
/**
* @dev Sets the address of the owner
*/
function _setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Sets the address of the owner
*/
function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal {
bytes32 position = pendingProxyOwnerPosition;
assembly {
sstore(position, newPendingProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
*changes the pending owner to newOwner. But doesn't actually transfer
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
_setPendingUpgradeabilityOwner(newOwner);
emit NewPendingOwner(proxyOwner(), newOwner);
}
/**
* @dev Allows the pendingOwner to claim ownership of the proxy
*/
function claimProxyOwnership() external onlyPendingProxyOwner {
emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner());
_setUpgradeabilityOwner(pendingProxyOwner());
_setPendingUpgradeabilityOwner(address(0));
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public virtual onlyProxyOwner {
address currentImplementation;
bytes32 position = implementationPosition;
assembly {
currentImplementation := sload(position)
}
require(currentImplementation != implementation);
assembly {
sstore(position, implementation)
}
emit Upgraded(implementation);
}
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
// Storage position of the address of the current implementation
bytes32 private constant implementationPosition = 0x6e41e0fbe643dfdb6043698bf865aada82dc46b953f754a3468eaa272a362dc7; //keccak256("trueUSD.proxy.implementation");
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Fallback functions allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
proxyCall();
}
receive() external payable {
proxyCall();
}
function proxyCall() internal {
bytes32 position = implementationPosition;
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, returndatasize(), calldatasize())
let result := delegatecall(gas(), sload(position), ptr, calldatasize(), returndatasize(), returndatasize())
returndatacopy(ptr, 0, returndatasize())
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
}File 2 of 7: OwnedUpgradeabilityProxy
pragma solidity ^0.4.23;
// This is the proxy contract for the TrustToken Registry
// File: contracts/Proxy/Proxy.sol
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function() external payable {
address _impl = implementation();
require(_impl != address(0), "implementation contract not set");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File: contracts/Proxy/UpgradeabilityProxy.sol
/**
* @title UpgradeabilityProxy
* @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
// Storage position of the address of the current implementation
bytes32 private constant implementationPosition = keccak256("trueUSD.proxy.implementation");
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Sets the address of the current implementation
* @param newImplementation address representing the new implementation to be set
*/
function _setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
/**
* @dev Upgrades the implementation address
* @param newImplementation representing the address of the new implementation to be set
*/
function _upgradeTo(address newImplementation) internal {
address currentImplementation = implementation();
require(currentImplementation != newImplementation);
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
// File: contracts/Proxy/OwnedUpgradeabilityProxy.sol
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Event to show ownership transfer is pending
* @param currentOwner representing the address of the current owner
* @param pendingOwner representing the address of the pending owner
*/
event NewPendingOwner(address currentOwner, address pendingOwner);
// Storage position of the owner and pendingOwner of the contract
bytes32 private constant proxyOwnerPosition = keccak256("trueUSD.proxy.owner");
bytes32 private constant pendingProxyOwnerPosition = keccak256("trueUSD.pending.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
_setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "only Proxy Owner");
_;
}
/**
* @dev Throws if called by any account other than the pending owner.
*/
modifier onlyPendingProxyOwner() {
require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner");
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
/**
* @dev Sets the address of the owner
*/
function _setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Sets the address of the owner
*/
function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal {
bytes32 position = pendingProxyOwnerPosition;
assembly {
sstore(position, newPendingProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
*changes the pending owner to newOwner. But doesn't actually transfer
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
_setPendingUpgradeabilityOwner(newOwner);
emit NewPendingOwner(proxyOwner(), newOwner);
}
/**
* @dev Allows the pendingOwner to claim ownership of the proxy
*/
function claimProxyOwnership() external onlyPendingProxyOwner {
emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner());
_setUpgradeabilityOwner(pendingProxyOwner());
_setPendingUpgradeabilityOwner(address(0));
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) external onlyProxyOwner {
_upgradeTo(implementation);
}
}File 3 of 7: TrueFiPool
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/truefi/common/Initializable.sol
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
pragma solidity 0.6.10;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/truefi/common/UpgradeableERC20.sol
pragma solidity 0.6.10;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_initialize(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public virtual override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/truefi/common/UpgradeableOwnable.sol
pragma solidity 0.6.10;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/truefi/interface/IYToken.sol
pragma solidity 0.6.10;
interface IYToken is IERC20 {
function getPricePerFullShare() external view returns (uint256);
}
// File: contracts/truefi/interface/ICurve.sol
pragma solidity 0.6.10;
interface ICurve {
function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
}
interface ICurveGauge {
function balanceOf(address depositor) external view returns (uint256);
function minter() external returns (ICurveMinter);
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
interface ICurveMinter {
function mint(address gauge) external;
function token() external view returns (IERC20);
}
interface ICurvePool {
function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount,
bool donate_dust
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function token() external view returns (IERC20);
function curve() external view returns (ICurve);
function coins(int128 id) external view returns (IYToken);
}
// File: contracts/truefi/interface/ITrueFiPool.sol
pragma solidity 0.6.10;
/**
* TruePool is an ERC20 which represents a share of a pool
*
* This contract can be used to wrap opportunities to be compatible
* with TrueFi and allow users to directly opt-in through the TUSD contract
*
* Each TruePool is also a staking opportunity for TRU
*/
interface ITrueFiPool is IERC20 {
/// @dev pool token (TUSD)
function currencyToken() external view returns (IERC20);
/**
* @dev join pool
* 1. Transfer TUSD from sender
* 2. Mint pool tokens based on value to sender
*/
function join(uint256 amount) external;
/**
* @dev exit pool
* 1. Transfer pool tokens from sender
* 2. Burn pool tokens
* 3. Transfer value of pool tokens in TUSD to sender
*/
function exit(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount, uint256 amountWithoutFee) external;
/**
* @dev join pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 amount) external;
}
// File: contracts/truefi/interface/ITrueLender.sol
pragma solidity 0.6.10;
interface ITrueLender {
function value() external view returns (uint256);
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
}
// File: contracts/truefi/interface/IUniswapRouter.sol
pragma solidity 0.6.10;
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// File: contracts/truefi/TrueFiPool.sol
pragma solidity 0.6.10;
/**
* @title TrueFi Pool
* @dev Lending pool which uses curve.fi to store idle funds
* Earn high interest rates on currency deposits through uncollateralized loans
*
* Funds deposited in this pool are NOT LIQUID!
* Exiting the pool will withdraw a basket of LoanTokens backing the pool
* After exiting, an account will need to wait for LoanTokens to expire and burn them
* It is recommended to perform a zap or swap tokens on Uniswap for liquidity
*
* Funds are managed through an external function to save gas on deposits
*/
contract TrueFiPool is ITrueFiPool, ERC20, ReentrancyGuard, Ownable {
using SafeMath for uint256;
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
ICurvePool public _curvePool;
ICurveGauge public _curveGauge;
IERC20 public _currencyToken;
ITrueLender public _lender;
ICurveMinter public _minter;
IUniswapRouter public _uniRouter;
// fee for deposits
uint256 public joiningFee = 25;
// track claimable fees
uint256 public claimableFees;
// ======= STORAGE DECLARATION END ============
// curve.fi data
uint8 constant N_TOKENS = 4;
uint8 constant TUSD_INDEX = 3;
/**
* @dev Emitted when fee is changed
* @param newFee New fee
*/
event JoiningFeeChanged(uint256 newFee);
/**
* @dev Emitted when someone joins the pool
* @param staker Account staking
* @param deposited Amount deposited
* @param minted Amount of pool tokens minted
*/
event Joined(address indexed staker, uint256 deposited, uint256 minted);
/**
* @dev Emitted when someone exits the pool
* @param staker Account exiting
* @param amount Amount unstaking
*/
event Exited(address indexed staker, uint256 amount);
/**
* @dev Emitted when funds are flushed into curve.fi
* @param currencyAmount Amount of tokens deposited
*/
event Flushed(uint256 currencyAmount);
/**
* @dev Emitted when funds are pulled from curve.fi
* @param yAmount Amount of pool tokens
*/
event Pulled(uint256 yAmount);
/**
* @dev Emitted when funds are borrowed from pool
* @param borrower Borrower address
* @param amount Amount of funds borrowed from pool
* @param fee Fees collected from this transaction
*/
event Borrow(address borrower, uint256 amount, uint256 fee);
/**
* @dev Emitted when borrower repays the pool
* @param payer Address of borrower
* @param amount Amount repaid
*/
event Repaid(address indexed payer, uint256 amount);
/**
* @dev Emitted when fees are collected
* @param beneficiary Account to receive fees
* @param amount Amount of fees collected
*/
event Collected(address indexed beneficiary, uint256 amount);
/**
* @dev Initialize pool
* @param __curvePool curve pool address
* @param __curveGauge curve gauge address
* @param __currencyToken curve pool underlying token
* @param __lender TrueLender address
* @param __uniRouter Uniswap router
*/
function initialize(
ICurvePool __curvePool,
ICurveGauge __curveGauge,
IERC20 __currencyToken,
ITrueLender __lender,
IUniswapRouter __uniRouter
) public initializer {
ERC20.__ERC20_initialize("TrueFi LP", "TFI-LP");
Ownable.initialize();
_curvePool = __curvePool;
_curveGauge = __curveGauge;
_currencyToken = __currencyToken;
_lender = __lender;
_minter = _curveGauge.minter();
_uniRouter = __uniRouter;
_currencyToken.approve(address(_curvePool), uint256(-1));
_curvePool.token().approve(address(_curvePool), uint256(-1));
}
/**
* @dev get currency token address
* @return currency token address
*/
function currencyToken() public override view returns (IERC20) {
return _currencyToken;
}
/**
* @dev Get total balance of curve.fi pool tokens
*/
function yTokenBalance() public view returns (uint256) {
return _curvePool.token().balanceOf(address(this)).add(_curveGauge.balanceOf(address(this)));
}
/**
* @dev Calculate pool value in TUSD
* "virtual price" of entire pool - LoanTokens, TUSD, curve y pool tokens
* @return pool value in TUSD
*/
function poolValue() public view returns (uint256) {
// prettier-ignore
return
currencyBalance()
.add(_lender.value())
.add(
yTokenBalance()
.mul(_curvePool.curve().get_virtual_price())
.div(1 ether));
}
/**
* @dev ensure enough curve.fi pool tokens are available
* Check if current available amount of TUSD is enough and
* withdraw remainder from gauge
* @param neededAmount amount required
*/
function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this));
if (currentlyAvailableAmount < neededAmount) {
_curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount));
}
}
/**
* @dev set pool join fee
* @param fee new fee
*/
function setJoiningFee(uint256 fee) external onlyOwner {
joiningFee = fee;
emit JoiningFeeChanged(fee);
}
/**
* @dev Join the pool by depositing currency tokens
* @param amount amount of currency token to deposit
*/
function join(uint256 amount) external override {
uint256 fee = amount.mul(joiningFee).div(10000);
uint256 amountToDeposit = amount.sub(fee);
uint256 amountToMint = amountToDeposit;
// first staker mints same amount deposited
if (totalSupply() > 0) {
amountToMint = totalSupply().mul(amountToDeposit).div(poolValue());
}
// mint pool tokens
_mint(msg.sender, amountToMint);
claimableFees = claimableFees.add(fee);
require(_currencyToken.transferFrom(msg.sender, address(this), amount));
emit Joined(msg.sender, amount, amountToMint);
}
// prettier-ignore
/**
* @dev Exit pool
* This function will withdraw a basket of currencies backing the pool value
* @param amount amount of pool tokens to redeem for underlying tokens
*/
function exit(uint256 amount) external override nonReentrant {
require(amount <= balanceOf(msg.sender), "CurvePool: insufficient funds");
uint256 _totalSupply = totalSupply();
// get share of currency tokens kept in the pool
uint256 currencyAmountToTransfer = amount.mul(
currencyBalance()).div(_totalSupply);
// calculate amount of curve.fi pool tokens
uint256 curveLiquidityAmountToTransfer = amount.mul(
yTokenBalance()).div(_totalSupply);
// burn tokens sent
_burn(msg.sender, amount);
// withdraw basket of loan tokens
_lender.distribute(msg.sender, amount, _totalSupply);
// if currency remaining, transfer
if (currencyAmountToTransfer > 0) {
require(_currencyToken.transfer(msg.sender, currencyAmountToTransfer));
}
// if curve tokens remaining, transfer
if (curveLiquidityAmountToTransfer > 0) {
ensureEnoughTokensAreAvailable(curveLiquidityAmountToTransfer);
require(_curvePool.token().transfer(msg.sender, curveLiquidityAmountToTransfer));
}
emit Exited(msg.sender, amount);
}
/**
* @dev Deposit idle funds into curve.fi pool and stake in gauge
* Called by owner to help manage funds in pool and save on gas for deposits
* @param currencyAmount Amount of funds to deposit into curve
* @param minMintAmount Minimum amount to mint
*/
function flush(uint256 currencyAmount, uint256 minMintAmount) external onlyOwner {
require(currencyAmount <= currencyBalance(), "CurvePool: Insufficient currency balance");
uint256[N_TOKENS] memory amounts = [0, 0, 0, currencyAmount];
// add TUSD to curve
_curvePool.add_liquidity(amounts, minMintAmount);
// stake yCurve tokens in gauge
_curveGauge.deposit(_curvePool.token().balanceOf(address(this)));
emit Flushed(currencyAmount);
}
/**
* @dev Remove liquidity from curve
* @param yAmount amount of curve pool tokens
* @param minCurrencyAmount minimum amount of tokens to withdraw
*/
function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwner {
require(yAmount <= yTokenBalance(), "CurvePool: Insufficient Curve liquidity balance");
// unstake in gauge
ensureEnoughTokensAreAvailable(yAmount);
// remove TUSD from curve
_curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false);
emit Pulled(yAmount);
}
// prettier-ignore
/**
* @dev Remove liquidity from curve and transfer to borrower
* @param expectedAmount expected amount to borrow
*/
function borrow(uint256 expectedAmount, uint256 amountWithoutFee) external override nonReentrant {
require(expectedAmount >= amountWithoutFee, "CurvePool: Fee cannot be negative");
// TODO: create modifier for onlyLender
require(msg.sender == address(_lender), "CurvePool: Only lender can borrow");
// if there is not enough TUSD, withdraw from curve
if (expectedAmount > currencyBalance()) {
// get rough estimate of how much TUSD we'll get back from curve
uint256 amountToWithdraw = expectedAmount.sub(currencyBalance());
uint256 roughCurveTokenAmount = calcTokenAmount(amountToWithdraw).mul(1005).div(1000);
require(
roughCurveTokenAmount <= yTokenBalance(),
"CurvePool: Not enough Curve y tokens in pool to cover borrow"
);
// pull tokens from gauge
ensureEnoughTokensAreAvailable(roughCurveTokenAmount);
// remove TUSD from curve
_curvePool.remove_liquidity_one_coin(roughCurveTokenAmount, TUSD_INDEX, 0, false);
require(expectedAmount <= currencyBalance(), "CurvePool: Not enough funds in pool to cover borrow");
}
// calculate fees and transfer remainder
uint256 fee = expectedAmount.sub(amountWithoutFee);
claimableFees = claimableFees.add(fee);
require(_currencyToken.transfer(msg.sender, amountWithoutFee));
emit Borrow(msg.sender, expectedAmount, fee);
}
/**
* @dev repay debt by transferring tokens to the contract
* @param currencyAmount amount to repay
*/
function repay(uint256 currencyAmount) external override {
require(_currencyToken.transferFrom(msg.sender, address(this), currencyAmount));
emit Repaid(msg.sender, currencyAmount);
}
/**
* @dev Collect CRV tokens minted by staking at gauge and sell them on Uniswap
* - Selling CRV is managed by the contract owner
* - Calculations can be made off-chain and called based on market conditions
* - Need to pass path of exact pairs to go through while executing exchange
* For example, CRV -> WETH -> TUSD
*
* @param amountOutMin see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens
* @param path see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens
*/
function collectCrv(uint256 amountOutMin, address[] calldata path) external onlyOwner {
_minter.mint(address(_curveGauge));
_uniRouter.swapExactTokensForTokens(
_minter.token().balanceOf(address(this)),
amountOutMin,
path,
address(this),
block.timestamp + 1 days
);
}
/**
* @dev Claim fees from the pool
* @param beneficiary account to send funds to
*/
function collectFees(address beneficiary) external onlyOwner {
uint256 amount = claimableFees;
claimableFees = 0;
if (amount > 0) {
require(_currencyToken.transfer(beneficiary, amount));
}
emit Collected(beneficiary, amount);
}
/**
* @notice Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens.
* Can be used to control slippage
* Called in flush() function
* @param currencyAmount amount to calculate for
*/
function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) {
// prettier-ignore
uint256 yTokenAmount = currencyAmount.mul(1e18).div(
_curvePool.coins(TUSD_INDEX).getPricePerFullShare());
uint256[N_TOKENS] memory yAmounts = [0, 0, 0, yTokenAmount];
return _curvePool.curve().calc_token_amount(yAmounts, true);
}
/**
* @dev Converts the value of a single yCRV into an underlying asset
* @param yAmount amount of curve pool tokens to calculate for
* @return Value of one y pool token
*/
function calcWithdrawOneCoin(uint256 yAmount) public view returns (uint256) {
return _curvePool.calc_withdraw_one_coin(yAmount, TUSD_INDEX);
}
/**
* @dev Currency token balance
* @return Currency token balance
*/
function currencyBalance() internal view returns (uint256) {
return _currencyToken.balanceOf(address(this)).sub(claimableFees);
}
}File 4 of 7: TrueUSD
/**
* :::==== :::==== ::: === :::===== ::: === :::=== :::====
* :::==== ::: === ::: === ::: ::: === ::: ::: ===
* === ======= === === ====== === === ===== === ===
* === === === === === === === === === === ===
* === === === ====== ======== ====== ====== =======
*/
pragma solidity 0.6.10;
/**
* Defines the storage layout of the token implementation contract. Any
* newly declared state variables in future upgrades should be appended
* to the bottom. Never remove state variables from this list, however variables
* can be renamed. Please add _Deprecated to deprecated variables.
*/
contract ProxyStorage {
address public owner;
address public pendingOwner;
bool initialized;
address balances_Deprecated;
address allowances_Deprecated;
uint256 _totalSupply;
bool private paused_Deprecated = false;
address private globalPause_Deprecated;
uint256 public burnMin = 0;
uint256 public burnMax = 0;
address registry_Deprecated;
string name_Deprecated;
string symbol_Deprecated;
uint256[] gasRefundPool_Deprecated;
uint256 private redemptionAddressCount_Deprecated;
uint256 minimumGasPriceForFutureRefunds_Deprecated;
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
mapping(bytes32 => mapping(address => uint256)) attributes_Deprecated;
// reward token storage
mapping(address => address) finOps_Deprecated;
mapping(address => mapping(address => uint256)) finOpBalances_Deprecated;
mapping(address => uint256) finOpSupply_Deprecated;
// true reward allocation
// proportion: 1000 = 100%
struct RewardAllocation {
uint256 proportion;
address finOp;
}
mapping(address => RewardAllocation[]) _rewardDistribution_Deprecated;
uint256 maxRewardProportion_Deprecated = 1000;
mapping(address => bool) isBlacklisted;
mapping(address => bool) public canBurn;
/* Additionally, we have several keccak-based storage locations.
* If you add more keccak-based storage mappings, such as mappings, you must document them here.
* If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision.
* A preimage collision can be used to attack the contract by treating one storage location as another,
* which would always be a critical issue.
* Carefully examine future keccak-based storage to ensure there can be no preimage collisions.
*******************************************************************************************************
** length input usage
*******************************************************************************************************
** 19 "trueXXX.proxy.owner" Proxy Owner
** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner
** 28 "trueXXX.proxy.implementation" Proxy Implementation
** 32 uint256(11) gasRefundPool_Deprecated
** 64 uint256(address),uint256(14) balanceOf
** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance
** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes
**/
}
pragma solidity 0.6.10;
/**
* @title ClamableOwnable
* @dev The ClamableOwnable contract is a copy of Claimable Contract by Zeppelin.
* and provides basic authorization control functions. Inherits storage layout of
* ProxyStorage.
*/
contract ClaimableOwnable is ProxyStorage {
/**
* @dev emitted when ownership is transferred
* @param previousOwner previous owner of this contract
* @param newOwner new owner of this contract
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sets the original `owner` of the contract to the sender
* at construction. Must then be reinitialized
*/
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "only Owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "only pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @notice This is a copy of openzeppelin ERC20 contract with removed state variables.
* Removing state variables has been necessary due to proxy pattern usage.
* Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol:
* - Remove state variables _name, _symbol, _decimals
* - Use state variables _balances, _allowances, _totalSupply from ProxyStorage
* - Remove constructor
* - Solidity version changed from ^0.6.0 to 0.6.10
* - Contract made abstract
*
* See also: ClaimableOwnable.sol and ProxyStorage.sol
*/
pragma solidity 0.6.10;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
abstract contract ERC20 is ClaimableOwnable, Context, IERC20 {
using SafeMath for uint256;
using Address for address;
/**
* @dev Returns the name of the token.
*/
function name() public virtual pure returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public virtual pure returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public virtual pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
// solhint-disable-next-line no-empty-blocks
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.10;
/**
* @title ReclaimerToken
* @dev ERC20 token which allows owner to reclaim ERC20 tokens
* or ether sent to this contract
*/
abstract contract ReclaimerToken is ERC20 {
/**
* @dev send all eth balance in the contract to another address
* @param _to address to send eth balance to
*/
function reclaimEther(address payable _to) external onlyOwner {
_to.transfer(address(this).balance);
}
/**
* @dev send all token balance of an arbitrary erc20 token
* in the contract to another address
* @param token token to reclaim
* @param _to address to send eth balance to
*/
function reclaimToken(IERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(_to, balance);
}
}
pragma solidity 0.6.10;
/**
* @title BurnableTokenWithBounds
* @dev Burning functions as redeeming money from the system.
* The platform will keep track of who burns coins,
* and will send them back the equivalent amount of money (rounded down to the nearest cent).
*/
abstract contract BurnableTokenWithBounds is ReclaimerToken {
/**
* @dev Emitted when `value` tokens are burnt from one account (`burner`)
* @param burner address which burned tokens
* @param value amount of tokens burned
*/
event Burn(address indexed burner, uint256 value);
/**
* @dev Emitted when new burn bounds were set
* @param newMin new minimum burn amount
* @param newMax new maximum burn amount
* @notice `newMin` should never be greater than `newMax`
*/
event SetBurnBounds(uint256 newMin, uint256 newMax);
/**
* @dev Destroys `amount` tokens from `msg.sender`, reducing the
* total supply.
* @param amount amount of tokens to burn
*
* Emits a {Transfer} event with `to` set to the zero address.
* Emits a {Burn} event with `burner` set to `msg.sender`
*
* Requirements
*
* - `msg.sender` must have at least `amount` tokens.
*
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/**
* @dev Change the minimum and maximum amount that can be burned at once.
* Burning may be disabled by setting both to 0 (this will not be done
* under normal operation, but we can't add checks to disallow it without
* losing a lot of flexibility since burning could also be as good as disabled
* by setting the minimum extremely high, and we don't want to lock
* in any particular cap for the minimum)
* @param _min minimum amount that can be burned at once
* @param _max maximum amount that can be burned at once
*/
function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner {
require(_min <= _max, "BurnableTokenWithBounds: min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
/**
* @dev Checks if amount is within allowed burn bounds and
* destroys `amount` tokens from `account`, reducing the
* total supply.
* @param account account to burn tokens for
* @param amount amount of tokens to burn
*
* Emits a {Burn} event
*/
function _burn(address account, uint256 amount) internal virtual override {
require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound");
require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound");
super._burn(account, amount);
emit Burn(account, amount);
}
}
pragma solidity 0.6.10;
/**
* @title TrueCurrency
* @dev TrueCurrency is an ERC20 with blacklist & redemption addresses
*
* TrueCurrency is a compliant stablecoin with blacklist and redemption
* addresses. Only the owner can blacklist accounts. Redemption addresses
* are assigned automatically to the first 0x100000 addresses. Sending
* tokens to the redemption address will trigger a burn operation. Only
* the owner can mint or blacklist accounts.
*
* This contract is owned by the TokenController, which manages token
* minting & admin functionality. See TokenController.sol
*
* See also: BurnableTokenWithBounds.sol
*
* ~~~~ Features ~~~~
*
* Redemption Addresses
* - The first 0x100000 addresses are redemption addresses
* - Tokens sent to redemption addresses are burned
* - Redemptions are tracked off-chain
* - Cannot mint tokens to redemption addresses
*
* Blacklist
* - Owner can blacklist accounts in accordance with local regulatory bodies
* - Only a court order will merit a blacklist; blacklisting is extremely rare
*
* Burn Bounds & CanBurn
* - Owner can set min & max burn amounts
* - Only accounts flagged in canBurn are allowed to burn tokens
* - canBurn prevents tokens from being sent to the incorrect address
*
* Reclaimer Token
* - ERC20 Tokens and Ether sent to this contract can be reclaimed by the owner
*/
abstract contract TrueCurrency is BurnableTokenWithBounds {
uint256 constant CENT = 10**16;
uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000;
/**
* @dev Emitted when account blacklist status changes
*/
event Blacklisted(address indexed account, bool isBlacklisted);
/**
* @dev Emitted when `value` tokens are minted for `to`
* @param to address to mint tokens for
* @param value amount of tokens to be minted
*/
event Mint(address indexed to, uint256 value);
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
* @param account address to mint tokens for
* @param amount amount of tokens to be minted
*
* Emits a {Mint} event
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` cannot be blacklisted.
* - `account` cannot be a redemption address.
*/
function mint(address account, uint256 amount) external onlyOwner {
require(!isBlacklisted[account], "TrueCurrency: account is blacklisted");
require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address");
_mint(account, amount);
emit Mint(account, amount);
}
/**
* @dev Set blacklisted status for the account.
* @param account address to set blacklist flag for
* @param _isBlacklisted blacklist flag value
*
* Requirements:
*
* - `msg.sender` should be owner.
*/
function setBlacklisted(address account, bool _isBlacklisted) external onlyOwner {
require(uint256(account) >= REDEMPTION_ADDRESS_COUNT, "TrueCurrency: blacklisting of redemption address is not allowed");
isBlacklisted[account] = _isBlacklisted;
emit Blacklisted(account, _isBlacklisted);
}
/**
* @dev Set canBurn status for the account.
* @param account address to set canBurn flag for
* @param _canBurn canBurn flag value
*
* Requirements:
*
* - `msg.sender` should be owner.
*/
function setCanBurn(address account, bool _canBurn) external onlyOwner {
canBurn[account] = _canBurn;
}
/**
* @dev Check if neither account is blacklisted before performing transfer
* If transfer recipient is a redemption address, burns tokens
* @notice Transfer to redemption address will burn tokens with a 1 cent precision
* @param sender address of sender
* @param recipient address of recipient
* @param amount amount of tokens to transfer
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
require(!isBlacklisted[sender], "TrueCurrency: sender is blacklisted");
require(!isBlacklisted[recipient], "TrueCurrency: recipient is blacklisted");
if (isRedemptionAddress(recipient)) {
super._transfer(sender, recipient, amount.sub(amount.mod(CENT)));
_burn(recipient, amount.sub(amount.mod(CENT)));
} else {
super._transfer(sender, recipient, amount);
}
}
/**
* @dev Requere neither accounts to be blacklisted before approval
* @param owner address of owner giving approval
* @param spender address of spender to approve for
* @param amount amount of tokens to approve
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal override {
require(!isBlacklisted[owner], "TrueCurrency: tokens owner is blacklisted");
require(!isBlacklisted[spender] || amount == 0, "TrueCurrency: tokens spender is blacklisted");
super._approve(owner, spender, amount);
}
/**
* @dev Check if tokens can be burned at address before burning
* @param account account to burn tokens from
* @param amount amount of tokens to burn
*/
function _burn(address account, uint256 amount) internal override {
require(canBurn[account], "TrueCurrency: cannot burn from this address");
super._burn(account, amount);
}
/**
* @dev First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff)
* are the redemption addresses.
* @param account address to check is a redemption address
*
* All transfers to redemption address will trigger token burn.
*
* @notice For transfer to succeed, canBurn must be true for redemption address
*
* @return is `account` a redemption address
*/
function isRedemptionAddress(address account) internal pure returns (bool) {
return uint256(account) < REDEMPTION_ADDRESS_COUNT && uint256(account) != 0;
}
}
pragma solidity 0.6.10;
/**
* @title DelegateERC20
* Accept forwarding delegation calls from the old TrueUSD (V1) contract.
* This way the all the ERC20 functions in the old contract still works
* (except Burn).
*
* The original contract is at 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E.
* Lines 497-574 on-chain call these delegate functions to forward calls
* This gives the delegate contract the power to change the state of the TrueUSD
* contract. The owner of this contract is the TrueUSD TokenController
* at 0x0000000000075efbee23fe2de1bd0b7690883cc9.
*
* Our audits for TrueCurrency can be found here: github.com/trusttoken/audits
*/
abstract contract DelegateERC20 is TrueCurrency {
address constant DELEGATE_FROM = 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E;
// require msg.sender is the delegate smart contract
modifier onlyDelegateFrom() {
require(msg.sender == DELEGATE_FROM);
_;
}
/**
* @dev Delegate call to get total supply
* @return Total supply
*/
function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
/**
* @dev Delegate call to get balance
* @param who Address to get balance for
* @return balance of account
*/
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
/**
* @dev Delegate call to transfer
* @param to address to transfer to
* @param value amount to transfer
* @param origSender original msg.sender on delegate contract
* @return success
*/
function delegateTransfer(
address to,
uint256 value,
address origSender
) public onlyDelegateFrom returns (bool) {
_transfer(origSender, to, value);
return true;
}
/**
* @dev Delegate call to get allowance
* @param owner account owner
* @param spender account to check allowance for
* @return allowance
*/
function delegateAllowance(address owner, address spender) public view returns (uint256) {
return allowance(owner, spender);
}
/**
* @dev Delegate call to transfer from
* @param from account to transfer funds from
* @param to account to transfer funds to
* @param value value to transfer
* @param origSender original msg.sender on delegate contract
* @return success
*/
function delegateTransferFrom(
address from,
address to,
uint256 value,
address origSender
) public onlyDelegateFrom returns (bool) {
// ERC20 transferFrom with _msgSender() replaced by origSender
_transfer(from, to, value);
_approve(from, origSender, _allowances[from][origSender].sub(value, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Delegate call to approve
* @param spender account to approve for
* @param value amount to approve
* @param origSender original msg.sender on delegate contract
* @return success
*/
function delegateApprove(
address spender,
uint256 value,
address origSender
) public onlyDelegateFrom returns (bool) {
_approve(origSender, spender, value);
return true;
}
/**
* @dev Delegate call to increase approval
* @param spender account to increase approval for
* @param addedValue amount of approval to add
* @param origSender original msg.sender on delegate contract
* @return success
*/
function delegateIncreaseApproval(
address spender,
uint256 addedValue,
address origSender
) public onlyDelegateFrom returns (bool) {
// ERC20 increaseAllowance() with _msgSender() replaced by origSender
_approve(origSender, spender, _allowances[origSender][spender].add(addedValue));
return true;
}
/**
* @dev Delegate call to decrease approval
* @param spender spender to decrease approval for
* @param subtractedValue value to subtract from approval
* @param origSender original msg.sender on delegate contract
* @return success
*/
function delegateDecreaseApproval(
address spender,
uint256 subtractedValue,
address origSender
) public onlyDelegateFrom returns (bool) {
// ERC20 decreaseAllowance() with _msgSender() replaced by origSender
_approve(origSender, spender, _allowances[origSender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
}
pragma solidity 0.6.10;
/**
* @dev Contract that prevents addresses that were previously using autosweep addresses from
* making transfers on them.
*
* In older versions TrueCurrencies had a feature called Autosweep.
* Given a single deposit address, it was possible to generate 16^5-1 autosweep addresses.
* E.g. having deposit address 0xc257274276a4e539741ca11b590b9447b26a8051, you could generate
* - 0xc257274276a4e539741ca11b590b9447b2600000
* - 0xc257274276a4e539741ca11b590b9447b2600001
* - ...
* - 0xc257274276a4e539741ca11b590b9447b26fffff
* Every transfer to an autosweep address resulted as a transfer to deposit address.
* This feature got deprecated, but there were 4 addresses that still actively using the feature.
*
* This contract will reject a transfer to these 4*(16^5-1) addresses to prevent accidental token freeze.
*/
abstract contract TrueCurrencyWithLegacyAutosweep is DelegateERC20 {
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
requireNotAutosweepAddress(recipient, 0x33091DE8341533468D13A80C5A670f4f47cC649f);
requireNotAutosweepAddress(recipient, 0x50E2719208914764087e68C32bC5AaC321f5B04d);
requireNotAutosweepAddress(recipient, 0x71d69e5481A9B7Be515E20B38a3f62Dab7170D78);
requireNotAutosweepAddress(recipient, 0x90fdaA85D52dB6065D466B86f16bF840D514a488);
super._transfer(sender, recipient, amount);
}
function requireNotAutosweepAddress(address recipient, address depositAddress) internal pure {
return
require(uint256(recipient) >> 20 != uint256(depositAddress) >> 20 || recipient == depositAddress, "Autosweep is disabled");
}
}
pragma solidity 0.6.10;
/**
* @title TrueUSD
* @dev This is the top-level ERC20 contract, but most of the interesting functionality is
* inherited - see the documentation on the corresponding contracts.
*/
contract TrueUSD is TrueCurrencyWithLegacyAutosweep {
uint8 constant DECIMALS = 18;
uint8 constant ROUNDING = 2;
function decimals() public override pure returns (uint8) {
return DECIMALS;
}
function rounding() public pure returns (uint8) {
return ROUNDING;
}
function name() public override pure returns (string memory) {
return "TrueUSD";
}
function symbol() public override pure returns (string memory) {
return "TUSD";
}
}File 5 of 7: Vyper_contract
# @version 0.2.4
"""
@title Liquidity Gauge
@author Curve Finance
@license MIT
@notice Used for measuring liquidity and insurance
"""
from vyper.interfaces import ERC20
interface CRV20:
def future_epoch_time_write() -> uint256: nonpayable
def rate() -> uint256: view
interface Controller:
def period() -> int128: view
def period_write() -> int128: nonpayable
def period_timestamp(p: int128) -> uint256: view
def gauge_relative_weight(addr: address, time: uint256) -> uint256: view
def voting_escrow() -> address: view
def checkpoint(): nonpayable
def checkpoint_gauge(addr: address): nonpayable
interface Minter:
def token() -> address: view
def controller() -> address: view
def minted(user: address, gauge: address) -> uint256: view
interface VotingEscrow:
def user_point_epoch(addr: address) -> uint256: view
def user_point_history__ts(addr: address, epoch: uint256) -> uint256: view
event Deposit:
provider: indexed(address)
value: uint256
event Withdraw:
provider: indexed(address)
value: uint256
event UpdateLiquidityLimit:
user: address
original_balance: uint256
original_supply: uint256
working_balance: uint256
working_supply: uint256
TOKENLESS_PRODUCTION: constant(uint256) = 40
BOOST_WARMUP: constant(uint256) = 2 * 7 * 86400
WEEK: constant(uint256) = 604800
minter: public(address)
crv_token: public(address)
lp_token: public(address)
controller: public(address)
voting_escrow: public(address)
balanceOf: public(HashMap[address, uint256])
totalSupply: public(uint256)
future_epoch_time: public(uint256)
# caller -> recipient -> can deposit?
approved_to_deposit: public(HashMap[address, HashMap[address, bool]])
working_balances: public(HashMap[address, uint256])
working_supply: public(uint256)
# The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint
# All values are kept in units of being multiplied by 1e18
period: public(int128)
period_timestamp: public(uint256[100000000000000000000000000000])
# 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
integrate_inv_supply: public(uint256[100000000000000000000000000000]) # bump epoch when rate() changes
# 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint
integrate_inv_supply_of: public(HashMap[address, uint256])
integrate_checkpoint_of: public(HashMap[address, uint256])
# ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint
# Units: rate * t = already number of coins per address to issue
integrate_fraction: public(HashMap[address, uint256])
inflation_rate: public(uint256)
@external
def __init__(lp_addr: address, _minter: address):
"""
@notice Contract constructor
@param lp_addr Liquidity Pool contract address
@param _minter Minter contract address
"""
assert lp_addr != ZERO_ADDRESS
assert _minter != ZERO_ADDRESS
self.lp_token = lp_addr
self.minter = _minter
crv_addr: address = Minter(_minter).token()
self.crv_token = crv_addr
controller_addr: address = Minter(_minter).controller()
self.controller = controller_addr
self.voting_escrow = Controller(controller_addr).voting_escrow()
self.period_timestamp[0] = block.timestamp
self.inflation_rate = CRV20(crv_addr).rate()
self.future_epoch_time = CRV20(crv_addr).future_epoch_time_write()
@internal
def _update_liquidity_limit(addr: address, l: uint256, L: uint256):
"""
@notice Calculate limits which depend on the amount of CRV token per-user.
Effectively it calculates working balances to apply amplification
of CRV production by CRV
@param addr User address
@param l User's amount of liquidity (LP tokens)
@param L Total amount of liquidity (LP tokens)
"""
# To be called after totalSupply is updated
_voting_escrow: address = self.voting_escrow
voting_balance: uint256 = ERC20(_voting_escrow).balanceOf(addr)
voting_total: uint256 = ERC20(_voting_escrow).totalSupply()
lim: uint256 = l * TOKENLESS_PRODUCTION / 100
if (voting_total > 0) and (block.timestamp > self.period_timestamp[0] + BOOST_WARMUP):
lim += L * voting_balance / voting_total * (100 - TOKENLESS_PRODUCTION) / 100
lim = min(l, lim)
old_bal: uint256 = self.working_balances[addr]
self.working_balances[addr] = lim
_working_supply: uint256 = self.working_supply + lim - old_bal
self.working_supply = _working_supply
log UpdateLiquidityLimit(addr, l, L, lim, _working_supply)
@internal
def _checkpoint(addr: address):
"""
@notice Checkpoint for a user
@param addr User address
"""
_token: address = self.crv_token
_controller: address = self.controller
_period: int128 = self.period
_period_time: uint256 = self.period_timestamp[_period]
_integrate_inv_supply: uint256 = self.integrate_inv_supply[_period]
rate: uint256 = self.inflation_rate
new_rate: uint256 = rate
prev_future_epoch: uint256 = self.future_epoch_time
if prev_future_epoch >= _period_time:
self.future_epoch_time = CRV20(_token).future_epoch_time_write()
new_rate = CRV20(_token).rate()
self.inflation_rate = new_rate
Controller(_controller).checkpoint_gauge(self)
_working_balance: uint256 = self.working_balances[addr]
_working_supply: uint256 = self.working_supply
# Update integral of 1/supply
if block.timestamp > _period_time:
prev_week_time: uint256 = _period_time
week_time: uint256 = min((_period_time + WEEK) / WEEK * WEEK, block.timestamp)
for i in range(500):
dt: uint256 = week_time - prev_week_time
w: uint256 = Controller(_controller).gauge_relative_weight(self, prev_week_time / WEEK * WEEK)
if _working_supply > 0:
if prev_future_epoch >= prev_week_time and prev_future_epoch < week_time:
# If we went across one or multiple epochs, apply the rate
# of the first epoch until it ends, and then the rate of
# the last epoch.
# If more than one epoch is crossed - the gauge gets less,
# but that'd meen it wasn't called for more than 1 year
_integrate_inv_supply += rate * w * (prev_future_epoch - prev_week_time) / _working_supply
rate = new_rate
_integrate_inv_supply += rate * w * (week_time - prev_future_epoch) / _working_supply
else:
_integrate_inv_supply += rate * w * dt / _working_supply
# On precisions of the calculation
# rate ~= 10e18
# last_weight > 0.01 * 1e18 = 1e16 (if pool weight is 1%)
# _working_supply ~= TVL * 1e18 ~= 1e26 ($100M for example)
# The largest loss is at dt = 1
# Loss is 1e-9 - acceptable
if week_time == block.timestamp:
break
prev_week_time = week_time
week_time = min(week_time + WEEK, block.timestamp)
_period += 1
self.period = _period
self.period_timestamp[_period] = block.timestamp
self.integrate_inv_supply[_period] = _integrate_inv_supply
# Update user-specific integrals
self.integrate_fraction[addr] += _working_balance * (_integrate_inv_supply - self.integrate_inv_supply_of[addr]) / 10 ** 18
self.integrate_inv_supply_of[addr] = _integrate_inv_supply
self.integrate_checkpoint_of[addr] = block.timestamp
@external
def user_checkpoint(addr: address) -> bool:
"""
@notice Record a checkpoint for `addr`
@param addr User address
@return bool success
"""
assert (msg.sender == addr) or (msg.sender == self.minter) # dev: unauthorized
self._checkpoint(addr)
self._update_liquidity_limit(addr, self.balanceOf[addr], self.totalSupply)
return True
@external
def claimable_tokens(addr: address) -> uint256:
"""
@notice Get the number of claimable tokens per user
@dev This function should be manually changed to "view" in the ABI
@return uint256 number of claimable tokens per user
"""
self._checkpoint(addr)
return self.integrate_fraction[addr] - Minter(self.minter).minted(addr, self)
@external
def kick(addr: address):
"""
@notice Kick `addr` for abusing their boost
@dev Only if either they had another voting event, or their voting escrow lock expired
@param addr Address to kick
"""
_voting_escrow: address = self.voting_escrow
t_last: uint256 = self.integrate_checkpoint_of[addr]
t_ve: uint256 = VotingEscrow(_voting_escrow).user_point_history__ts(
addr, VotingEscrow(_voting_escrow).user_point_epoch(addr)
)
_balance: uint256 = self.balanceOf[addr]
assert ERC20(self.voting_escrow).balanceOf(addr) == 0 or t_ve > t_last # dev: kick not allowed
assert self.working_balances[addr] > _balance * TOKENLESS_PRODUCTION / 100 # dev: kick not needed
self._checkpoint(addr)
self._update_liquidity_limit(addr, self.balanceOf[addr], self.totalSupply)
@external
def set_approve_deposit(addr: address, can_deposit: bool):
"""
@notice Set whether `addr` can deposit tokens for `msg.sender`
@param addr Address to set approval on
@param can_deposit bool - can this account deposit for `msg.sender`?
"""
self.approved_to_deposit[addr][msg.sender] = can_deposit
@external
@nonreentrant('lock')
def deposit(_value: uint256, addr: address = msg.sender):
"""
@notice Deposit `_value` LP tokens
@param _value Number of tokens to deposit
@param addr Address to deposit for
"""
if addr != msg.sender:
assert self.approved_to_deposit[msg.sender][addr], "Not approved"
self._checkpoint(addr)
if _value != 0:
_balance: uint256 = self.balanceOf[addr] + _value
_supply: uint256 = self.totalSupply + _value
self.balanceOf[addr] = _balance
self.totalSupply = _supply
self._update_liquidity_limit(addr, _balance, _supply)
assert ERC20(self.lp_token).transferFrom(msg.sender, self, _value)
log Deposit(addr, _value)
@external
@nonreentrant('lock')
def withdraw(_value: uint256):
"""
@notice Withdraw `_value` LP tokens
@param _value Number of tokens to withdraw
"""
self._checkpoint(msg.sender)
_balance: uint256 = self.balanceOf[msg.sender] - _value
_supply: uint256 = self.totalSupply - _value
self.balanceOf[msg.sender] = _balance
self.totalSupply = _supply
self._update_liquidity_limit(msg.sender, _balance, _supply)
assert ERC20(self.lp_token).transfer(msg.sender, _value)
log Withdraw(msg.sender, _value)
@external
@view
def integrate_checkpoint() -> uint256:
return self.period_timestamp[self.period]File 6 of 7: Vyper_contract
# A "zap" to deposit/withdraw Curve contract without too many transactions
# (c) Curve.Fi, 2020
from vyper.interfaces import ERC20
# External Contracts
contract yERC20:
def totalSupply() -> uint256: constant
def allowance(_owner: address, _spender: address) -> uint256: constant
def transfer(_to: address, _value: uint256) -> bool: modifying
def transferFrom(_from: address, _to: address, _value: uint256) -> bool: modifying
def approve(_spender: address, _value: uint256) -> bool: modifying
def name() -> string[64]: constant
def symbol() -> string[32]: constant
def decimals() -> uint256: constant
def balanceOf(arg0: address) -> uint256: constant
def deposit(depositAmount: uint256): modifying
def withdraw(withdrawTokens: uint256): modifying
def getPricePerFullShare() -> uint256: constant
# Tether transfer-only ABI
contract USDT:
def transfer(_to: address, _value: uint256): modifying
def transferFrom(_from: address, _to: address, _value: uint256): modifying
contract Curve:
def add_liquidity(amounts: uint256[N_COINS], min_mint_amount: uint256): modifying
def remove_liquidity(_amount: uint256, min_amounts: uint256[N_COINS]): modifying
def remove_liquidity_imbalance(amounts: uint256[N_COINS], max_burn_amount: uint256): modifying
def balances(i: int128) -> uint256: constant
def A() -> uint256: constant
def fee() -> uint256: constant
def owner() -> address: constant
N_COINS: constant(int128) = 4
TETHERED: constant(bool[N_COINS]) = [False, False, True, False]
ZERO256: constant(uint256) = 0 # This hack is really bad XXX
ZEROS: constant(uint256[N_COINS]) = [ZERO256, ZERO256, ZERO256, ZERO256] # <- change
LENDING_PRECISION: constant(uint256) = 10 ** 18
PRECISION: constant(uint256) = 10 ** 18
PRECISION_MUL: constant(uint256[N_COINS]) = [convert(1, uint256), convert(1000000000000, uint256), convert(1000000000000, uint256), convert(1, uint256)]
FEE_DENOMINATOR: constant(uint256) = 10 ** 10
FEE_IMPRECISION: constant(uint256) = 25 * 10 ** 8 # % of the fee
coins: public(address[N_COINS])
underlying_coins: public(address[N_COINS])
curve: public(address)
token: public(address)
@public
def __init__(_coins: address[N_COINS], _underlying_coins: address[N_COINS],
_curve: address, _token: address):
self.coins = _coins
self.underlying_coins = _underlying_coins
self.curve = _curve
self.token = _token
@public
@nonreentrant('lock')
def add_liquidity(uamounts: uint256[N_COINS], min_mint_amount: uint256):
tethered: bool[N_COINS] = TETHERED
amounts: uint256[N_COINS] = ZEROS
for i in range(N_COINS):
uamount: uint256 = uamounts[i]
if uamount > 0:
# Transfer the underlying coin from owner
if tethered[i]:
USDT(self.underlying_coins[i]).transferFrom(
msg.sender, self, uamount)
else:
assert_modifiable(ERC20(self.underlying_coins[i])\
.transferFrom(msg.sender, self, uamount))
# Mint if needed
ERC20(self.underlying_coins[i]).approve(self.coins[i], uamount)
yERC20(self.coins[i]).deposit(uamount)
amounts[i] = yERC20(self.coins[i]).balanceOf(self)
ERC20(self.coins[i]).approve(self.curve, amounts[i])
Curve(self.curve).add_liquidity(amounts, min_mint_amount)
tokens: uint256 = ERC20(self.token).balanceOf(self)
assert_modifiable(ERC20(self.token).transfer(msg.sender, tokens))
@private
def _send_all(_addr: address, min_uamounts: uint256[N_COINS], one: int128):
tethered: bool[N_COINS] = TETHERED
for i in range(N_COINS):
if (one < 0) or (i == one):
_coin: address = self.coins[i]
_balance: uint256 = yERC20(_coin).balanceOf(self)
if _balance == 0: # Do nothing for 0 coins
continue
yERC20(_coin).withdraw(_balance)
_ucoin: address = self.underlying_coins[i]
_uamount: uint256 = ERC20(_ucoin).balanceOf(self)
assert _uamount >= min_uamounts[i], "Not enough coins withdrawn"
if tethered[i]:
USDT(_ucoin).transfer(_addr, _uamount)
else:
assert_modifiable(ERC20(_ucoin).transfer(_addr, _uamount))
@public
@nonreentrant('lock')
def remove_liquidity(_amount: uint256, min_uamounts: uint256[N_COINS]):
zeros: uint256[N_COINS] = ZEROS
assert_modifiable(ERC20(self.token).transferFrom(msg.sender, self, _amount))
Curve(self.curve).remove_liquidity(_amount, zeros)
self._send_all(msg.sender, min_uamounts, -1)
@public
@nonreentrant('lock')
def remove_liquidity_imbalance(uamounts: uint256[N_COINS], max_burn_amount: uint256):
"""
Get max_burn_amount in, remove requested liquidity and transfer back what is left
"""
tethered: bool[N_COINS] = TETHERED
_token: address = self.token
amounts: uint256[N_COINS] = uamounts
for i in range(N_COINS):
if amounts[i] > 0:
rate: uint256 = yERC20(self.coins[i]).getPricePerFullShare()
amounts[i] = amounts[i] * LENDING_PRECISION / rate
# Transfrer max tokens in
_tokens: uint256 = ERC20(_token).balanceOf(msg.sender)
if _tokens > max_burn_amount:
_tokens = max_burn_amount
assert_modifiable(ERC20(_token).transferFrom(msg.sender, self, _tokens))
Curve(self.curve).remove_liquidity_imbalance(amounts, max_burn_amount)
# Transfer unused tokens back
_tokens = ERC20(_token).balanceOf(self)
assert_modifiable(ERC20(_token).transfer(msg.sender, _tokens))
# Unwrap and transfer all the coins we've got
self._send_all(msg.sender, ZEROS, -1)
@private
@constant
def _xp_mem(rates: uint256[N_COINS], _balances: uint256[N_COINS]) -> uint256[N_COINS]:
result: uint256[N_COINS] = rates
for i in range(N_COINS):
result[i] = result[i] * _balances[i] / PRECISION
return result
@private
@constant
def get_D(A: uint256, xp: uint256[N_COINS]) -> uint256:
S: uint256 = 0
for _x in xp:
S += _x
if S == 0:
return 0
Dprev: uint256 = 0
D: uint256 = S
Ann: uint256 = A * N_COINS
for _i in range(255):
D_P: uint256 = D
for _x in xp:
D_P = D_P * D / (_x * N_COINS + 1) # +1 is to prevent /0
Dprev = D
D = (Ann * S + D_P * N_COINS) * D / ((Ann - 1) * D + (N_COINS + 1) * D_P)
# Equality with the precision of 1
if D > Dprev:
if D - Dprev <= 1:
break
else:
if Dprev - D <= 1:
break
return D
@private
@constant
def get_y(A: uint256, i: int128, _xp: uint256[N_COINS], D: uint256) -> uint256:
"""
Calculate x[i] if one reduces D from being calculated for _xp to D
Done by solving quadratic equation iteratively.
x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
"""
# x in the input is converted to the same price/precision
assert (i >= 0) and (i < N_COINS)
c: uint256 = D
S_: uint256 = 0
Ann: uint256 = A * N_COINS
_x: uint256 = 0
for _i in range(N_COINS):
if _i != i:
_x = _xp[_i]
else:
continue
S_ += _x
c = c * D / (_x * N_COINS)
c = c * D / (Ann * N_COINS)
b: uint256 = S_ + D / Ann
y_prev: uint256 = 0
y: uint256 = D
for _i in range(255):
y_prev = y
y = (y*y + c) / (2 * y + b - D)
# Equality with the precision of 1
if y > y_prev:
if y - y_prev <= 1:
break
else:
if y_prev - y <= 1:
break
return y
@private
@constant
def _calc_withdraw_one_coin(_token_amount: uint256, i: int128, rates: uint256[N_COINS]) -> uint256:
# First, need to calculate
# * Get current D
# * Solve Eqn against y_i for D - _token_amount
crv: address = self.curve
A: uint256 = Curve(crv).A()
fee: uint256 = Curve(crv).fee() * N_COINS / (4 * (N_COINS - 1))
fee += fee * FEE_IMPRECISION / FEE_DENOMINATOR # Overcharge to account for imprecision
precisions: uint256[N_COINS] = PRECISION_MUL
total_supply: uint256 = ERC20(self.token).totalSupply()
xp: uint256[N_COINS] = PRECISION_MUL
S: uint256 = 0
for j in range(N_COINS):
xp[j] *= Curve(crv).balances(j)
xp[j] = xp[j] * rates[j] / LENDING_PRECISION
S += xp[j]
D0: uint256 = self.get_D(A, xp)
D1: uint256 = D0 - _token_amount * D0 / total_supply
xp_reduced: uint256[N_COINS] = xp
# xp = xp - fee * | xp * D1 / D0 - (xp - S * dD / D0 * (0, ... 1, ..0))|
for j in range(N_COINS):
dx_expected: uint256 = 0
b_ideal: uint256 = xp[j] * D1 / D0
b_expected: uint256 = xp[j]
if j == i:
b_expected -= S * (D0 - D1) / D0
if b_ideal >= b_expected:
dx_expected += (b_ideal - b_expected)
else:
dx_expected += (b_expected - b_ideal)
xp_reduced[j] -= fee * dx_expected / FEE_DENOMINATOR
dy: uint256 = xp_reduced[i] - self.get_y(A, i, xp_reduced, D1)
dy = dy / precisions[i]
return dy
@public
@constant
def calc_withdraw_one_coin(_token_amount: uint256, i: int128) -> uint256:
rates: uint256[N_COINS] = ZEROS
for j in range(N_COINS):
rates[j] = yERC20(self.coins[j]).getPricePerFullShare()
return self._calc_withdraw_one_coin(_token_amount, i, rates)
@public
@nonreentrant('lock')
def remove_liquidity_one_coin(_token_amount: uint256, i: int128, min_uamount: uint256, donate_dust: bool = False):
"""
Remove _amount of liquidity all in a form of coin i
"""
rates: uint256[N_COINS] = ZEROS
_token: address = self.token
for j in range(N_COINS):
rates[j] = yERC20(self.coins[j]).getPricePerFullShare()
dy: uint256 = self._calc_withdraw_one_coin(_token_amount, i, rates)
assert dy >= min_uamount, "Not enough coins removed"
assert_modifiable(
ERC20(self.token).transferFrom(msg.sender, self, _token_amount))
amounts: uint256[N_COINS] = ZEROS
amounts[i] = dy * LENDING_PRECISION / rates[i]
token_amount_before: uint256 = ERC20(_token).balanceOf(self)
Curve(self.curve).remove_liquidity_imbalance(amounts, _token_amount)
# Unwrap and transfer all the coins we've got
self._send_all(msg.sender, ZEROS, i)
if not donate_dust:
# Transfer unused tokens back
token_amount_after: uint256 = ERC20(_token).balanceOf(self)
if token_amount_after > token_amount_before:
assert_modifiable(ERC20(_token).transfer(
msg.sender, token_amount_after - token_amount_before)
)
@public
@nonreentrant('lock')
def withdraw_donated_dust():
owner: address = Curve(self.curve).owner()
assert msg.sender == owner
_token: address = self.token
assert_modifiable(
ERC20(_token).transfer(owner, ERC20(_token).balanceOf(self)))File 7 of 7: Vyper_contract
# https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
from vyper.interfaces import ERC20
implements: ERC20
Transfer: event({_from: indexed(address), _to: indexed(address), _value: uint256})
Approval: event({_owner: indexed(address), _spender: indexed(address), _value: uint256})
name: public(string[64])
symbol: public(string[32])
decimals: public(uint256)
# NOTE: By declaring `balanceOf` as public, vyper automatically generates a 'balanceOf()' getter
# method to allow access to account balances.
# The _KeyType will become a required parameter for the getter and it will return _ValueType.
# See: https://vyper.readthedocs.io/en/v0.1.0-beta.8/types.html?highlight=getter#mappings
balanceOf: public(map(address, uint256))
allowances: map(address, map(address, uint256))
total_supply: uint256
minter: address
@public
def __init__(_name: string[64], _symbol: string[32], _decimals: uint256, _supply: uint256):
init_supply: uint256 = _supply * 10 ** _decimals
self.name = _name
self.symbol = _symbol
self.decimals = _decimals
self.balanceOf[msg.sender] = init_supply
self.total_supply = init_supply
self.minter = msg.sender
log.Transfer(ZERO_ADDRESS, msg.sender, init_supply)
@public
def set_minter(_minter: address):
assert msg.sender == self.minter
self.minter = _minter
@public
@constant
def totalSupply() -> uint256:
"""
@dev Total number of tokens in existence.
"""
return self.total_supply
@public
@constant
def allowance(_owner : address, _spender : address) -> uint256:
"""
@dev Function to check the amount of tokens that an owner allowed to a spender.
@param _owner The address which owns the funds.
@param _spender The address which will spend the funds.
@return An uint256 specifying the amount of tokens still available for the spender.
"""
return self.allowances[_owner][_spender]
@public
def transfer(_to : address, _value : uint256) -> bool:
"""
@dev Transfer token for a specified address
@param _to The address to transfer to.
@param _value The amount to be transferred.
"""
# NOTE: vyper does not allow underflows
# so the following subtraction would revert on insufficient balance
self.balanceOf[msg.sender] -= _value
self.balanceOf[_to] += _value
log.Transfer(msg.sender, _to, _value)
return True
@public
def transferFrom(_from : address, _to : address, _value : uint256) -> bool:
"""
@dev Transfer tokens from one address to another.
Note that while this function emits a Transfer event, this is not required as per the specification,
and other compliant implementations may not emit the event.
@param _from address The address which you want to send tokens from
@param _to address The address which you want to transfer to
@param _value uint256 the amount of tokens to be transferred
"""
# NOTE: vyper does not allow underflows
# so the following subtraction would revert on insufficient balance
self.balanceOf[_from] -= _value
self.balanceOf[_to] += _value
if msg.sender != self.minter: # minter is allowed to transfer anything
# NOTE: vyper does not allow underflows
# so the following subtraction would revert on insufficient allowance
self.allowances[_from][msg.sender] -= _value
log.Transfer(_from, _to, _value)
return True
@public
def approve(_spender : address, _value : uint256) -> bool:
"""
@dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
Beware that changing an allowance with this method brings the risk that someone may use both the old
and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
@param _spender The address which will spend the funds.
@param _value The amount of tokens to be spent.
"""
assert _value == 0 or self.allowances[msg.sender][_spender] == 0
self.allowances[msg.sender][_spender] = _value
log.Approval(msg.sender, _spender, _value)
return True
@public
def mint(_to: address, _value: uint256):
"""
@dev Mint an amount of the token and assigns it to an account.
This encapsulates the modification of balances such that the
proper events are emitted.
@param _to The account that will receive the created tokens.
@param _value The amount that will be created.
"""
assert msg.sender == self.minter
assert _to != ZERO_ADDRESS
self.total_supply += _value
self.balanceOf[_to] += _value
log.Transfer(ZERO_ADDRESS, _to, _value)
@private
def _burn(_to: address, _value: uint256):
"""
@dev Internal function that burns an amount of the token of a given
account.
@param _to The account whose tokens will be burned.
@param _value The amount that will be burned.
"""
assert _to != ZERO_ADDRESS
self.total_supply -= _value
self.balanceOf[_to] -= _value
log.Transfer(_to, ZERO_ADDRESS, _value)
@public
def burn(_value: uint256):
"""
@dev Burn an amount of the token of msg.sender.
@param _value The amount that will be burned.
"""
assert msg.sender == self.minter, "Only minter is allowed to burn"
self._burn(msg.sender, _value)
@public
def burnFrom(_to: address, _value: uint256):
"""
@dev Burn an amount of the token from a given account.
@param _to The account whose tokens will be burned.
@param _value The amount that will be burned.
"""
assert msg.sender == self.minter, "Only minter is allowed to burn"
self._burn(_to, _value)