Skip to content

Instantly share code, notes, and snippets.

@bitbd83
Created August 6, 2020 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitbd83/c15b98e6655ce6d5adead9344fda33a8 to your computer and use it in GitHub Desktop.
Save bitbd83/c15b98e6655ce6d5adead9344fda33a8 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.5.4+commit.9549d8ff.js&optimize=true&gist=
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
Note: Simple contract to use as base for const vals
*/
contract CommonConstants {
bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _id The ID of the token being transferred
@param _value The amount of tokens being transferred
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);
/**
@notice Handle the receipt of multiple ERC1155 token types.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@param _operator The address which initiated the batch transfer (i.e. msg.sender)
@param _from The address which previously owned the token
@param _ids An array containing ids of each token being transferred (order and length must match _values array)
@param _values An array containing amounts of each token being transferred (order and length must match _ids array)
@param _data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
/**
@title ERC-1155 Multi Token Standard
@dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
interface IERC1155 /* is ERC165 */ {
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be msg.sender.
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _id);
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// A sample implementation of core ERC1155 function.
contract ERC1155 is IERC1155, ERC165, CommonConstants
{
using SafeMath for uint256;
using Address for address;
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping (address => mapping(address => bool)) internal operatorApproval;
/////////////////////////////////////////// ERC165 //////////////////////////////////////////////
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
bytes4(keccak256("balanceOf(address,uint256)")) ^
bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
bytes4(keccak256("setApprovalForAll(address,bool)")) ^
bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
function supportsInterface(bytes4 _interfaceId)
public
view
returns (bool) {
if (_interfaceId == INTERFACE_SIGNATURE_ERC165 ||
_interfaceId == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external {
require(_to != address(0x0), "_to must be non-zero.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);
}
}
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external {
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero.");
require(_ids.length == _values.length, "_ids and _values array lenght must match.");
require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
for (uint256 i = 0; i < _ids.length; ++i) {
uint256 id = _ids[i];
uint256 value = _values[i];
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[id][_from] = balances[id][_from].sub(value);
balances[id][_to] = value.add(balances[id][_to]);
}
// Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
// event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
// Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
// However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.
// MUST emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _values);
// Now that the balances are updated and the events are emitted,
// call onERC1155BatchReceived if the destination is a contract.
if (_to.isContract()) {
_doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data);
}
}
/**
@notice Get the balance of an account's Tokens.
@param _owner The address of the token holder
@param _id ID of the Token
@return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256) {
// The balance of any account can be calculated from the Transfer events history.
// However, since we need to keep the balances to validate transfer request,
// there is no extra cost to also privide a querry function.
return balances[_id][_owner];
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the Tokens
@return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) {
require(_owners.length == _ids.length);
uint256[] memory balances_ = new uint256[](_owners.length);
for (uint256 i = 0; i < _owners.length; ++i) {
balances_[i] = balances[_ids[i]][_owners[i]];
}
return balances_;
}
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
operatorApproval[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the Tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApproval[_owner][_operator];
}
/////////////////////////////////////////// Internal //////////////////////////////////////////////
function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received");
}
function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal {
// If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
// the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.
// Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
// If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived");
}
}
contract ERC1155withAdapter is ERC1155 {
mapping(uint256 => address) public adapter;
mapping(uint256 => uint256) public totalSupply;
address public template;
event NewAdapter(uint256 indexed id, address indexed adapter);
constructor() public {
template = address(new ERC20Adapter());
}
function createAdapter(uint256 _id, string memory _name, string memory _symbol, uint8 _decimals) public {
require(adapter[_id] == address(0));
address a = createClone(template);
ERC20Adapter(a).setup(_id, _name, _symbol, _decimals);
adapter[_id] = a;
emit NewAdapter(_id, a);
}
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function transferByAdapter(address _from, address _to, uint256 _id, uint256 _value) public returns(bool) {
require(adapter[_id] == msg.sender);
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
balances[_id][_to] = _value.add(balances[_id][_to]);
bytes memory _data;
if(_to.isContract()){
if(ERC165(_from).supportsInterface(0x4e2312e0)){
_doSafeTransferAcceptanceCheck(_from, _from, _to, _id, _value, _data);
}
}
// MUST emit event
emit TransferSingle(msg.sender, _from, _to, _id, _value);
return true;
}
}
contract ERC20Adapter {
using SafeMath for uint256;
ERC1155withAdapter public entity;
uint256 public id;
string public name;
string public symbol;
uint8 public decimals;
mapping (address => mapping (address => uint256)) private allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev setup the adapter, use as a constructor.
*/
function setup(uint256 _id, string memory _name, string memory _symbol, uint8 _decimals) public {
require(id == 0 && address(entity) == address(0));
entity = ERC1155withAdapter(msg.sender);
id = _id;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function totalSupply() external view returns (uint256){
return entity.totalSupply(id);
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256){
return entity.balanceOf(account, id);
}
/**
* @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){
require(entity.transferByAdapter(msg.sender, recipient, id, amount));
emit Transfer(msg.sender, recipient, amount);
return true;
}
/**
* @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){
return allowed[owner][spender];
}
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool){
allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @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){
allowed[sender][msg.sender] = allowed[sender][msg.sender].sub(amount);
require(entity.transferByAdapter(sender, recipient, id, amount));
emit Transfer(sender, recipient, amount);
return true;
}
}
/**
*Smart Contract for "ZebSwap DeFi". Expanding Q-Protocol
*/
/**
*Submitted for verification at Etherscan.io on 2020-08-11
by @BitBD, NEXBIT.IO
*/
pragma solidity ^0.5.4;
import "ERC1155Adapter-flat.sol";
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previous_owner, address indexed new_owner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param new_owner The address to transfer ownership to.
*/
function transferOwnership(address new_owner) public onlyOwner {
require(new_owner != address(0));
emit OwnershipTransferred(owner, new_owner);
owner = new_owner;
}
}
contract Admin is Ownable {
mapping(address => bool) public isAdmin;
function addAdmin(address who) external onlyOwner {
isAdmin[who] = true;
}
function removeAdmin(address who) external onlyOwner {
isAdmin[who] = false;
}
modifier onlyAdmin() {
require(msg.sender == owner || isAdmin[msg.sender]);
_;
}
}
contract ERC20 {
function balanceOf(address) external view returns(uint256);
function transfer(address to, uint256 amount) external returns(bool);
function transferFrom(address from, address to, uint256 amount) external returns(bool);
function approve(address spender, uint256 amount) external returns(bool);
}
interface ERC20NonStandard {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 amount) external;
function transferFrom(address from, address to, uint256 amount) external;
function approve(address spender, uint256 amount) external;
}
interface IDispatcher {
// external function
function trigger() external returns (bool);
function withdrawProfit() external returns (bool);
function drainFunds(uint256 _index) external returns (bool);
function refundDispather(address _receiver) external returns (bool);
function withdrawPrinciple (uint256 _amount) external returns (bool); //custom function
// get function
function getReserve() external view returns (uint256);
function getReserveRatio() external view returns (uint256);
function getPrinciple() external view returns (uint256);
function getBalance() external view returns (uint256);
function getProfit() external view returns (uint256);
function getTHPrinciple(uint256 _index) external view returns (uint256);
function getTHBalance(uint256 _index) external view returns (uint256);
function getTHProfit(uint256 _index) external view returns (uint256);
function getToken() external view returns (address);
function getFund() external view returns (address);
function getTHStructures() external view returns (uint256[] memory, address[] memory, address[] memory);
function getTHData(uint256 _index) external view returns (uint256, uint256, uint256, uint256);
function getTHCount() external view returns (uint256);
function getTHAddress(uint256 _index) external view returns (address);
function getTargetAddress(uint256 _index) external view returns (address);
function getPropotion() external view returns (uint256[] memory);
function getProfitBeneficiary() external view returns (address);
function getReserveUpperLimit() external view returns (uint256);
function getReserveLowerLimit() external view returns (uint256);
function getExecuteUnit() external view returns (uint256);
// Governmence Functions
function setAimedPropotion(uint256[] calldata _thPropotion) external returns (bool);
function addTargetHandler(address _targetHandlerAddr, uint256[] calldata _thPropotion) external returns (bool);
function removeTargetHandler(address _targetHandlerAddr, uint256 _index, uint256[] calldata _thPropotion) external returns (bool);
function setProfitBeneficiary(address _profitBeneficiary) external returns (bool);
function setReserveLowerLimit(uint256 _number) external returns (bool);
function setReserveUpperLimit(uint256 _number) external returns (bool);
function setExecuteUnit(uint256 _number) external returns (bool);
function newOwner() external view returns(address);
function acceptOwnership() external;
}
contract ZebSwapV1 is ERC1155withAdapter, Admin {
event TokenPurchase(address indexed buyer, address indexed token, uint256 coin_sold, uint256 tokens_bought);
event CoinPurchase(address indexed buyer, address indexed token, uint256 tokens_sold, uint256 coin_bought);
event AddLiquidity(address indexed provider, address indexed token, uint256 coin_amount, uint256 token_amount);
event RemoveLiquidity(address indexed provider, address indexed token, uint256 coin_amount, uint256 token_amount);
mapping(address => address) public DispatcherOf;
mapping(address => uint256) public coinReserveShare;
uint256 public totalCoinStored;
uint256 public globalIndex = 1e18;
uint256 public feeRate = 3000000000000000;
address public coin = address(0x83f797f7d70fdCE011A138F6A29332A31293B309); /**USDz*/
/***********************************|
| Dispatcher Functions |
|__________________________________*/
function updateGlobalIndex() public {
if(totalCoinStored > 0) {
globalIndex = globalIndex.mul(tokenReserveOf(coin)).div(totalCoinStored);
totalCoinStored = tokenReserveOf(coin);
}
}
function coinReserveOf(address token) public view returns(uint256) {
return coinReserveShare[token].mul(globalIndex) / 1e18;
}
function tokenReserveOf(address token) public view returns(uint256) {
uint256 amount = ERC20(token).balanceOf(address(this));
if(DispatcherOf[token] != address(0)) {
amount = amount.add(IDispatcher(DispatcherOf[token]).getBalance());
}
return amount;
}
function depositAndTrigger(address token, address from, uint256 amount) internal {
require(doTransferIn(token, from, amount));
address dispatcher = DispatcherOf[token];
if(dispatcher != address(0)){
IDispatcher(dispatcher).trigger();
}
}
function checkAndWithdraw(address token, address to, uint256 amount) internal {
uint256 cash = ERC20(token).balanceOf(address(this));
if(cash < amount) {
IDispatcher(DispatcherOf[token]).withdrawProfit();
cash = ERC20(token).balanceOf(address(this));
if(cash < amount)
IDispatcher(DispatcherOf[token]).withdrawPrinciple(amount.sub(cash));
}
require(doTransferOut(token, to, amount));
}
/***********************************|
| Manager Functions |
|__________________________________*/
function setDispatcher(address token, address dispatcher) external onlyAdmin {
// maybe check previous dispatcher balance if exist?
DispatcherOf[token] = dispatcher;
require(IDispatcher(dispatcher).newOwner() == address(this));
IDispatcher(dispatcher).acceptOwnership();
IDispatcher(dispatcher).setProfitBeneficiary(address(this));
doApproval(token, dispatcher, uint256(-1));
}
function setFee(uint256 new_fee) external onlyAdmin {
require(new_fee <= 30000000000000000); //fee must be smaller than 3%
feeRate = new_fee;
}
function createAdapter(uint256 _id, string memory _name, string memory _symbol, uint8 _decimals) public onlyAdmin {
require(adapter[_id] == address(0));
address a = createClone(template);
ERC20Adapter(a).setup(_id, _name, _symbol, _decimals);
adapter[_id] = a;
emit NewAdapter(_id, a);
}
/***********************************|
| Exchange Functions |
|__________________________________*/
/**
* @dev Pricing function for converting between tokens.
* @param input_amount Amount of Tokens being sold.
* @param input_reserve Amount of Tokens in exchange reserves.
* @param output_reserve Amount of Tokens in exchange reserves.
* @return Amount of Tokens bought.
*/
function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) {
require(input_reserve > 0 && output_reserve > 0);
uint256 input_amount_with_fee = input_amount.mul(1e18 - feeRate);
uint256 numerator = input_amount_with_fee.mul(output_reserve);
uint256 denominator = input_reserve.mul(1e18).add(input_amount_with_fee);
return numerator / denominator;
}
/**
* @dev Pricing function for converting between Tokens.
* @param output_amount Amount of Tokens being bought.
* @param input_reserve Amount of Tokens in exchange reserves.
* @param output_reserve Amount of Tokens in exchange reserves.
* @return Amount of Tokens sold.
*/
function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) {
require(input_reserve > 0 && output_reserve > 0);
uint256 numerator = input_reserve.mul(output_amount).mul(1e18);
uint256 denominator = (output_reserve.sub(output_amount)).mul(1e18 - feeRate);
return (numerator / denominator).add(1);
}
function CoinToTokenInput(address token, uint256 coin_sold, uint256 min_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && coin_sold > 0 && min_tokens > 0);
updateGlobalIndex();
uint256 tokens_bought = getInputPrice(coin_sold, coinReserveOf(token), tokenReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].add(coin_sold.mul(1e18)/globalIndex);
require(tokens_bought >= min_tokens);
checkAndWithdraw(token, recipient, tokens_bought);
depositAndTrigger(coin, buyer, coin_sold);
totalCoinStored = totalCoinStored.add(coin_sold);
emit TokenPurchase(buyer, token, coin_sold, tokens_bought);
return tokens_bought;
}
/**
* @notice Convert coin to tokens.
* @dev User specifies exact coin input && minium output.
* @param token Address of Tokens bought.
* @param coin_sold Amount of coin user wants to pay.
* @param min_tokens Minium Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens bought.
*/
function CoinToTokenSwapInput(address token, uint256 coin_sold, uint256 min_tokens, uint256 deadline) public returns (uint256) {
return CoinToTokenInput(token, coin_sold, min_tokens, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert coin to Tokens && transfers Tokens to recipient.
* @dev User specifies exact coin input && minium output.
* @param token Address of Tokens bought.
* @param coin_sold Amount of coin user wants to pay.
* @param min_tokens Minium Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The addresss that recieves output Tokens.
* @return Amount of Token bought.
*/
function CoinToTokenTransferInput(address token, uint256 coin_sold, uint256 min_tokens, uint256 deadline, address recipient) public returns(uint256) {
require(recipient != address(this) && recipient != address(0));
return CoinToTokenInput(token, coin_sold, min_tokens, deadline, msg.sender, recipient);
}
function CoinToTokenOutput(address token, uint256 tokens_bought, uint256 max_coin, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && tokens_bought > 0 && max_coin > 0);
updateGlobalIndex();
uint256 coin_sold = getOutputPrice(tokens_bought, coinReserveOf(token), tokenReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].add(coin_sold.mul(1e18)/globalIndex);
require(coin_sold <= max_coin);
checkAndWithdraw(token, recipient, tokens_bought);
depositAndTrigger(coin, buyer, coin_sold);
totalCoinStored = totalCoinStored.add(coin_sold);
emit TokenPurchase(buyer, token, coin_sold, tokens_bought);
return coin_sold;
}
/**
* @notice Convert coin to Tokens.
* @dev User specifies maxium coin input && exact output.
* @param token Address of Tokens bought.
* @param tokens_bought Amount of token bought.
* @param max_coin Maxium amount of coin sold.
* @param deadline Time after which this transaction can be no longer be executed.
* @return Amount of coin sold.
*/
function CoinToTokenSwapOutput(address token, uint256 tokens_bought, uint256 max_coin, uint256 deadline) public returns(uint256) {
return CoinToTokenOutput(token, tokens_bought, max_coin, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert coin to Tokens && transfer Tokens to recipient.
* @dev User specifies maxium coin input && exact output.
* @param token Address of Tokens bought.
* @param tokens_bought Amount of token bought.
* @param max_coin Maxium amount of coin sold.
* @param deadline Time after which this transaction can be no longer be executed.
* @param recipient The address the receives output Tokens.
* @return Amount of coin sold.
*/
function CoinToTokenTransferOutput(address token, uint256 tokens_bought, uint256 max_coin, uint256 deadline, address recipient) public returns (uint256) {
require(recipient != address(this) && recipient != address(0));
return CoinToTokenOutput(token, tokens_bought, max_coin, deadline, msg.sender, recipient);
}
function tokenToCoinInput(address token, uint256 tokens_sold, uint256 min_coin, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && tokens_sold > 0 && min_coin > 0);
updateGlobalIndex();
uint256 coin_bought = getInputPrice(tokens_sold, tokenReserveOf(token), coinReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].sub(coin_bought.mul(1e18)/globalIndex);
require(coin_bought >= min_coin);
depositAndTrigger(token, buyer, tokens_sold);
checkAndWithdraw(coin, recipient, coin_bought);
totalCoinStored = totalCoinStored.sub(coin_bought);
emit CoinPurchase(buyer, token, tokens_sold, coin_bought);
return coin_bought;
}
/**
* @notice Convert Tokens to coin.
* @dev User specifies exact input && minium output.
* @param token Address of Tokens sold.
* @param tokens_sold Amount of Tokens sold.
* @param min_coin Minium coin purchased.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of coin bought.
*/
function tokenToCoinSwapInput(address token, uint256 tokens_sold, uint256 min_coin, uint256 deadline) public returns (uint256) {
return tokenToCoinInput(token, tokens_sold, min_coin, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to coin && transfer coin to recipient.
* @dev User specifies exact input && minium output.
* @param token The address of Tokens sold.
* @param tokens_sold Amount of Tokens sold.
* @param min_coin Minium coin purchased.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that receives output coin.
* @return Amount of coin bought.
*/
function tokenToCoinTransferInput(address token, uint256 tokens_sold, uint256 min_coin, uint256 deadline, address recipient) public returns (uint256) {
require(recipient != address(this) && recipient != address(0));
return tokenToCoinInput(token, tokens_sold, min_coin, deadline, msg.sender, recipient);
}
function tokenToCoinOutput(address token, uint256 coin_bought, uint256 max_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) {
//check if such trading pair exists
require(totalSupply[uint256(token)] > 0);
require(deadline >= block.timestamp && coin_bought > 0);
updateGlobalIndex();
uint256 tokens_sold = getOutputPrice(coin_bought, tokenReserveOf(token), coinReserveOf(token));
coinReserveShare[token] = coinReserveShare[token].sub(coin_bought.mul(1e18)/globalIndex);
require(max_tokens >= tokens_sold);
depositAndTrigger(token, buyer, tokens_sold);
checkAndWithdraw(coin, recipient, coin_bought);
totalCoinStored = totalCoinStored.sub(coin_bought);
emit CoinPurchase(buyer, token, tokens_sold, coin_bought);
return tokens_sold;
}
/**
* @notice Convert Tokens to coin.
* @dev User specifies maxium input && exact output.
* @param token Address of Tokens sold.
* @param coin_bought Amount of coin bought.
* @param max_tokens Maxium Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens sold.
*/
function tokenToCoinSwapOutput(address token, uint256 coin_bought, uint256 max_tokens, uint256 deadline) public returns (uint256) {
return tokenToCoinOutput(token, coin_bought, max_tokens, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to coin && transfers coin to recipient.
* @dev User specifies maxium input && exact output.
* @param token Address of Tokens sold.
* @param coin_bought Amount of coin bought.
* @param max_tokens Maxium Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that receives output coin.
* @return Amount of Tokens sold.
*/
function tokenToCoinTransferOutput(address token, uint256 coin_bought, uint256 max_tokens, uint256 deadline, address recipient) public returns (uint256) {
require(recipient != address(this) && recipient != address(0));
return tokenToCoinOutput(token, coin_bought, max_tokens, deadline, msg.sender, recipient);
}
function tokenToTokenInput(
address input_token,
address output_token,
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 deadline,
address buyer,
address recipient)
private returns (uint256)
{
//check not self-swapping
require(input_token != output_token);
//check if such trading pair exists
require(totalSupply[uint256(input_token)] > 0 && totalSupply[uint256(output_token)] > 0);
require(deadline >= block.timestamp && tokens_sold > 0 && min_tokens_bought > 0);
updateGlobalIndex();
uint256 coin_bought = getInputPrice(tokens_sold, tokenReserveOf(input_token), coinReserveOf(input_token));
uint256 token_bought = getInputPrice(coin_bought, coinReserveOf(output_token), tokenReserveOf(output_token));
// move coin reserve
coinReserveShare[input_token] = coinReserveShare[input_token].sub(coin_bought.mul(1e18)/globalIndex);
coinReserveShare[output_token] = coinReserveShare[output_token].add(coin_bought.mul(1e18)/globalIndex);
// do input/output token transfer
require(min_tokens_bought <= token_bought);
checkAndWithdraw(output_token, recipient, token_bought);
depositAndTrigger(input_token, buyer, tokens_sold);
emit CoinPurchase(buyer, input_token, tokens_sold, coin_bought);
emit TokenPurchase(buyer, output_token, coin_bought, token_bought);
return token_bought;
}
/**
* @notice Convert Tokens to Tokens.
* @dev User specifies exact input && minium output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_sold Amount of Tokens sold.
* @param min_tokens_bought Minium amount of Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens bought.
*/
function tokenToTokenSwapInput(
address input_token,
address output_token,
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 deadline)
public returns (uint256)
{
return tokenToTokenInput(input_token, output_token, tokens_sold, min_tokens_bought, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to Tokens && transfers Tokens to recipient.
* @dev User specifies exact input && minium output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_sold Amount of Tokens sold.
* @param min_tokens_bought Minium amount of Tokens bought.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that recieves output token.
* @return Amount of Tokens bought.
*/
function tokenToTokenTransferInput(
address input_token,
address output_token,
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 deadline,
address recipient)
public returns (uint256)
{
return tokenToTokenInput(input_token, output_token, tokens_sold, min_tokens_bought, deadline, msg.sender, recipient);
}
function tokenToTokenOutput(
address input_token,
address output_token,
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 deadline,
address buyer,
address recipient)
private returns (uint256)
{
//check not self-swapping
require(input_token != output_token);
//check if such trading pair exists
require(totalSupply[uint256(input_token)] > 0 && totalSupply[uint256(output_token)] > 0);
require(deadline >= block.timestamp && tokens_bought > 0);
updateGlobalIndex();
uint256 coin_bought = getOutputPrice(tokens_bought, coinReserveOf(output_token), tokenReserveOf(output_token));
uint256 tokens_sold;
tokens_sold = tokenToTokenOutputHelper(input_token,coin_bought);
// move coin reserve
coinReserveShare[input_token] = coinReserveShare[input_token].sub(coin_bought.mul(1e18)/globalIndex);
coinReserveShare[output_token] = coinReserveShare[output_token].add(coin_bought.mul(1e18)/globalIndex);
require(max_tokens_sold >= tokens_sold);
checkAndWithdraw(output_token, recipient, tokens_bought);
depositAndTrigger(input_token, buyer, tokens_sold);
emit CoinPurchase(buyer, input_token, tokens_sold, coin_bought);
emit TokenPurchase(buyer, output_token, coin_bought, tokens_bought);
return tokens_sold;
}
function tokenToTokenOutputHelper(address input_token, uint256 coin_bought) private view returns(uint256) {
uint256 tokens_sold = getOutputPrice(coin_bought, tokenReserveOf(input_token), coinReserveOf(input_token));
return tokens_sold;
}
/**
* @notice Convert Tokens to Tokens.
* @dev User specifies maxium input && exact output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_bought Amount of Tokens bought.
* @param max_tokens_sold Maxium amount of Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Tokens sold.
*/
function tokenToTokenSwapOutput(
address input_token,
address output_token,
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 deadline)
public returns (uint256)
{
return tokenToTokenOutput(input_token, output_token, tokens_bought, max_tokens_sold, deadline, msg.sender, msg.sender);
}
/**
* @notice Convert Tokens to Tokens && transfers Tokens to recipient.
* @dev User specifies maxium input && exact output.
* @param input_token Address of Tokens sold.
* @param output_token Address of Tokens bought.
* @param tokens_bought Amount of Tokens bought.
* @param max_tokens_sold Maxium amount of Tokens sold.
* @param deadline Time after which this transaction can no longer be executed.
* @param recipient The address that receives output Tokens.
* @return Amount of Tokens sold.
*/
function tokenToTokenTransferOutput(
address input_token,
address output_token,
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 deadline,
address recipient)
public returns (uint256)
{
return tokenToTokenOutput(input_token, output_token, tokens_bought, max_tokens_sold, deadline, msg.sender, recipient);
}
/***********************************|
| Getter Functions |
|__________________________________*/
/**
* @notice Public price function for coin to Token trades with an exact input.
* @param token address of token bought.
* @param coin_sold Amount of coin sold.
* @return Amount of Tokens that can be bought with input coin.
*/
function getCoinToTokenInputPrice(address token, uint256 coin_sold) public view returns (uint256) {
require(coin_sold > 0);
return getInputPrice(coin_sold, coinReserveOf(token), tokenReserveOf(token));
}
/**
* @notice Public price function for coin to Token trades with an exact output.
* @param token address of token to buy.
* @param tokens_bought Amount of Tokens bought.
* @return Amount of coin needed to buy output Tokens.
*/
function getCoinToTokenOutputPrice(address token, uint256 tokens_bought) public view returns (uint256) {
require(tokens_bought > 0);
return getOutputPrice(tokens_bought, coinReserveOf(token), tokenReserveOf(token));
}
/**
* @notice Public price function for Token to coin trades with an exact input.
* @param token address of token sold.
* @param tokens_sold Amount of Tokens sold.
* @return Amount of coin that can be bought with input Tokens.
*/
function getTokenToCoinInputPrice(address token, uint256 tokens_sold) public view returns (uint256) {
require(tokens_sold > 0);
return getInputPrice(tokens_sold, tokenReserveOf(token), coinReserveOf(token));
}
/**
* @notice Public price function for Token to coin trades with an exact output.
* @param token address of token sold.
* @param coin_bought Amount of output coin.
* @return Amount of Tokens needed to buy output coin.
*/
function getTokenToCoinOutputPrice(address token, uint256 coin_bought) public view returns (uint256) {
require(coin_bought > 0);
return getOutputPrice(coin_bought, tokenReserveOf(token), coinReserveOf(token));
}
/***********************************|
| Liquidity Functions |
|__________________________________*/
/**
* @notice Deposit coin && Tokens at current ratio to mint liquidity tokens.
* @dev min_liquidity does nothing when total liquidity supply is 0.
* @param token Address of Tokens reserved
* @param reserve_added Amount of coin reserved
* @param min_liquidity Minium number of liquidity sender will mint if total liquidity supply is greater than 0.
* @param max_tokens Maxium number of tokens deposited. Deposits max amount if total liquidity supply is 0.
* @param deadline Time after which this transaction can no longer be executed.
* @return Amount of Liquidity minted
*/
function addLiquidity(address token, uint256 reserve_added, uint256 min_liquidity, uint256 max_tokens, uint256 deadline) public payable returns (uint256) {
require(deadline >= block.timestamp && max_tokens > 0 && reserve_added > 0);
require(token != coin);
uint256 total_liquidity = totalSupply[uint256(token)];
if (total_liquidity > 0) {
require(min_liquidity > 0);
updateGlobalIndex();
uint256 token_amount = (reserve_added.mul(tokenReserveOf(token)) / coinReserveOf(token)).add(1);
uint256 liquidity_minted = reserve_added.mul(total_liquidity) / coinReserveOf(token);
require(max_tokens >= token_amount && liquidity_minted >= min_liquidity);
balances[uint256(token)][msg.sender] = balances[uint256(token)][msg.sender].add(liquidity_minted);
totalSupply[uint256(token)] = total_liquidity.add(liquidity_minted);
coinReserveShare[token] = coinReserveShare[token].add(reserve_added.mul(1e18)/globalIndex);
depositAndTrigger(token, msg.sender, token_amount);
depositAndTrigger(coin, msg.sender, reserve_added);
totalCoinStored = totalCoinStored.add(reserve_added);
emit AddLiquidity(msg.sender, token, reserve_added, token_amount);
emit TransferSingle(msg.sender, address(0), msg.sender, uint256(token), liquidity_minted);
return liquidity_minted;
} else {
require(reserve_added >= 1000000000);
uint256 token_amount = max_tokens;
uint256 initial_liquidity = reserve_added;
totalSupply[uint256(token)] = initial_liquidity;
balances[uint256(token)][msg.sender] = initial_liquidity;
coinReserveShare[token] = coinReserveShare[token].add(reserve_added.mul(1e18)/globalIndex);
depositAndTrigger(token, msg.sender, token_amount);
depositAndTrigger(coin, msg.sender, reserve_added);
totalCoinStored = totalCoinStored.add(reserve_added);
emit AddLiquidity(msg.sender, token, reserve_added, token_amount);
emit TransferSingle(msg.sender, address(0), msg.sender, uint256(token), initial_liquidity);
return initial_liquidity;
}
}
/**
* @notice Withdraw coin && Tokens at current ratio to burn liquidity tokens.
* @dev Burn liquidity tokens to withdraw coin && Tokens at current ratio.
* @param token Address of Tokens withdrawn.
* @param amount Amount of liquidity burned.
* @param min_coin Minium coin withdrawn.
* @param min_tokens Minium Tokens withdrawn.
* @param deadline Time after which this transaction can no longer be executed.
* @return The amount of coin && Tokens withdrawn.
*/
function removeLiquidity(address token, uint256 amount, uint256 min_coin, uint256 min_tokens, uint256 deadline) public returns (uint256, uint256) {
require(amount > 0 && deadline >= block.timestamp && min_coin > 0 && min_tokens > 0);
uint256 total_liquidity = totalSupply[uint256(token)];
require(total_liquidity > 0);
updateGlobalIndex();
uint256 coin_amount = amount.mul(coinReserveOf(token)) / total_liquidity;
uint256 token_amount = amount.mul(tokenReserveOf(token)) / total_liquidity;
require(coin_amount >= min_coin && token_amount >= min_tokens);
balances[uint256(token)][msg.sender] = balances[uint256(token)][msg.sender].sub(amount);
totalSupply[uint256(token)] = total_liquidity.sub(amount);
coinReserveShare[token] = coinReserveShare[token].sub(coin_amount.mul(1e18)/globalIndex);
checkAndWithdraw(token, msg.sender, token_amount);
checkAndWithdraw(coin, msg.sender, coin_amount);
totalCoinStored = totalCoinStored.sub(coin_amount);
emit RemoveLiquidity(msg.sender, token, coin_amount, token_amount);
emit TransferSingle(msg.sender, msg.sender, address(0), uint256(token), amount);
return (coin_amount, token_amount);
}
/***********************************|
| SAFE Token Transfer |
|__________________________________*/
function doTransferIn(address tokenAddr, address from, uint amount) internal returns (bool result) {
ERC20NonStandard token = ERC20NonStandard(tokenAddr);
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
}
function doTransferOut(address tokenAddr, address to, uint amount) internal returns (bool result) {
ERC20NonStandard token = ERC20NonStandard(tokenAddr);
token.transfer(to, amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
}
function doApproval(address tokenAddr, address to, uint amount) internal returns(bool result) {
ERC20NonStandard token = ERC20NonStandard(tokenAddr);
token.approve(to, amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment