contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | LibCLLa | library LibCLLa {
string constant public VERSION = "LibCLLa 0.4.0";
address constant NULL = 0;
address constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct CLL{
mapping (address => mapping (bool => address)) cll;
}
// n: node id d: direction r: return node id
// Return existential state of a node. n == HEAD returns list existence.
function exists(CLL storage self, address n) internal constant returns (bool) {
if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD)
return true;
if (n == HEAD)
return false;
if (self.cll[HEAD][NEXT] == n)
return true;
return false;
}
// Returns the number of elements in the list
function sizeOf(CLL storage self) internal constant returns (uint r) {
address i = step(self, HEAD, NEXT);
while (i != HEAD) {
i = step(self, i, NEXT);
r++;
}
return;
}
// Returns the links of a node as and array
function getNode(CLL storage self, address n)
internal constant returns (address[2])
{
return [self.cll[n][PREV], self.cll[n][NEXT]];
}
// Returns the link of a node `n` in direction `d`.
function step(CLL storage self, address n, bool d)
internal constant returns (address)
{
return self.cll[n][d];
}
// Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d`
function seek(CLL storage self, address a, address b, bool d)
internal constant returns (address r)
{
r = step(self, a, d);
while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
return;
}
// Creates a bidirectional link between two nodes on direction `d`
function stitch(CLL storage self, address a, address b, bool d) internal {
self.cll[b][!d] = a;
self.cll[a][d] = b;
}
// Insert node `b` beside existing node `a` in direction `d`.
function insert (CLL storage self, address a, address b, bool d) internal {
address c = self.cll[a][d];
stitch (self, a, b, d);
stitch (self, b, c, d);
}
function remove(CLL storage self, address n) internal returns (address) {
if (n == NULL) return;
stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT);
delete self.cll[n][PREV];
delete self.cll[n][NEXT];
return n;
}
function push(CLL storage self, address n, bool d) internal {
insert(self, HEAD, n, d);
}
function pop(CLL storage self, bool d) internal returns (address) {
return remove(self, step(self, HEAD, d));
}
} | // LibCLL using `address` keys | LineComment | seek | function seek(CLL storage self, address a, address b, bool d)
internal constant returns (address r)
{
r = step(self, a, d);
while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
return;
}
| // Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d` | LineComment | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
1673,
1912
]
} | 9,200 |
|
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | LibCLLa | library LibCLLa {
string constant public VERSION = "LibCLLa 0.4.0";
address constant NULL = 0;
address constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct CLL{
mapping (address => mapping (bool => address)) cll;
}
// n: node id d: direction r: return node id
// Return existential state of a node. n == HEAD returns list existence.
function exists(CLL storage self, address n) internal constant returns (bool) {
if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD)
return true;
if (n == HEAD)
return false;
if (self.cll[HEAD][NEXT] == n)
return true;
return false;
}
// Returns the number of elements in the list
function sizeOf(CLL storage self) internal constant returns (uint r) {
address i = step(self, HEAD, NEXT);
while (i != HEAD) {
i = step(self, i, NEXT);
r++;
}
return;
}
// Returns the links of a node as and array
function getNode(CLL storage self, address n)
internal constant returns (address[2])
{
return [self.cll[n][PREV], self.cll[n][NEXT]];
}
// Returns the link of a node `n` in direction `d`.
function step(CLL storage self, address n, bool d)
internal constant returns (address)
{
return self.cll[n][d];
}
// Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d`
function seek(CLL storage self, address a, address b, bool d)
internal constant returns (address r)
{
r = step(self, a, d);
while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
return;
}
// Creates a bidirectional link between two nodes on direction `d`
function stitch(CLL storage self, address a, address b, bool d) internal {
self.cll[b][!d] = a;
self.cll[a][d] = b;
}
// Insert node `b` beside existing node `a` in direction `d`.
function insert (CLL storage self, address a, address b, bool d) internal {
address c = self.cll[a][d];
stitch (self, a, b, d);
stitch (self, b, c, d);
}
function remove(CLL storage self, address n) internal returns (address) {
if (n == NULL) return;
stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT);
delete self.cll[n][PREV];
delete self.cll[n][NEXT];
return n;
}
function push(CLL storage self, address n, bool d) internal {
insert(self, HEAD, n, d);
}
function pop(CLL storage self, bool d) internal returns (address) {
return remove(self, step(self, HEAD, d));
}
} | // LibCLL using `address` keys | LineComment | stitch | function stitch(CLL storage self, address a, address b, bool d) internal {
self.cll[b][!d] = a;
self.cll[a][d] = b;
}
| // Creates a bidirectional link between two nodes on direction `d` | LineComment | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
1987,
2133
]
} | 9,201 |
|
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | LibCLLa | library LibCLLa {
string constant public VERSION = "LibCLLa 0.4.0";
address constant NULL = 0;
address constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct CLL{
mapping (address => mapping (bool => address)) cll;
}
// n: node id d: direction r: return node id
// Return existential state of a node. n == HEAD returns list existence.
function exists(CLL storage self, address n) internal constant returns (bool) {
if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD)
return true;
if (n == HEAD)
return false;
if (self.cll[HEAD][NEXT] == n)
return true;
return false;
}
// Returns the number of elements in the list
function sizeOf(CLL storage self) internal constant returns (uint r) {
address i = step(self, HEAD, NEXT);
while (i != HEAD) {
i = step(self, i, NEXT);
r++;
}
return;
}
// Returns the links of a node as and array
function getNode(CLL storage self, address n)
internal constant returns (address[2])
{
return [self.cll[n][PREV], self.cll[n][NEXT]];
}
// Returns the link of a node `n` in direction `d`.
function step(CLL storage self, address n, bool d)
internal constant returns (address)
{
return self.cll[n][d];
}
// Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d`
function seek(CLL storage self, address a, address b, bool d)
internal constant returns (address r)
{
r = step(self, a, d);
while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
return;
}
// Creates a bidirectional link between two nodes on direction `d`
function stitch(CLL storage self, address a, address b, bool d) internal {
self.cll[b][!d] = a;
self.cll[a][d] = b;
}
// Insert node `b` beside existing node `a` in direction `d`.
function insert (CLL storage self, address a, address b, bool d) internal {
address c = self.cll[a][d];
stitch (self, a, b, d);
stitch (self, b, c, d);
}
function remove(CLL storage self, address n) internal returns (address) {
if (n == NULL) return;
stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT);
delete self.cll[n][PREV];
delete self.cll[n][NEXT];
return n;
}
function push(CLL storage self, address n, bool d) internal {
insert(self, HEAD, n, d);
}
function pop(CLL storage self, bool d) internal returns (address) {
return remove(self, step(self, HEAD, d));
}
} | // LibCLL using `address` keys | LineComment | insert | function insert (CLL storage self, address a, address b, bool d) internal {
address c = self.cll[a][d];
stitch (self, a, b, d);
stitch (self, b, c, d);
}
| // Insert node `b` beside existing node `a` in direction `d`. | LineComment | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
2203,
2394
]
} | 9,202 |
|
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | totalSupply | function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
| ///Returns total supply of Aqua Tokens | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
2202,
2311
]
} | 9,203 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | balanceOf | function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
| /// Get the token balance for address _owner | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
2364,
2630
]
} | 9,204 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | transfer | function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
| ///Transfer the balance from owner's account to another account | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
2700,
2844
]
} | 9,205 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
| /// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism; | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
3274,
3597
]
} | 9,206 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | approve | function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| /// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value. | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
3795,
4116
]
} | 9,207 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | allowance | function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
| /// Returns the amount that _spender is allowed to withdraw from _owner account. | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
4215,
4371
]
} | 9,208 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | AquaToken | function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
| /// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
8003,
9052
]
} | 9,209 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | startTrading | function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
| ///Called by token owner enable trading with tokens | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
9116,
9294
]
} | 9,210 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | requestRedemption | function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
| ///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request) | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
9581,
10183
]
} | 9,211 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | cancelRedemptionRequest | function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
| ///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
10382,
10985
]
} | 9,212 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | firstRedemptionRequest | function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
| ///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
11143,
11273
]
} | 9,213 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | nextRedemptionRequest | function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
| ///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
11531,
11704
]
} | 9,214 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | getRedemptionRequest | function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
| ///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
11983,
12304
]
} | 9,215 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | firstHolder | function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
| ///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
12504,
12618
]
} | 9,216 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | nextHolder | function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
| ///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
12894,
13038
]
} | 9,217 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | getHolding | function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
| ///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal. | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
13488,
14040
]
} | 9,218 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | startDistribuion | function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
| ///Token owner calls this function to start profit distribution round | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
14122,
14370
]
} | 9,219 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | continueDistribution | function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
| ///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
14600,
16027
]
} | 9,220 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | withdrawBalanceMaxSteps | function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
| ///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
16363,
17077
]
} | 9,221 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | withdrawBalance | function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
| ///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
17195,
17279
]
} | 9,222 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
| ///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
17635,
17969
]
} | 9,223 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | burn | function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
| ///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
18225,
19130
]
} | 9,224 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | windUp | function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
| ///Token owner to call this to initiate final distribution in case of project wind-up | NatSpecSingleLine | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
19224,
20300
]
} | 9,225 |
|||
AquaToken | AquaToken.sol | 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 | Solidity | AquaToken | contract AquaToken is Owned, Token {
//imports
using SafeMath for uint256;
using LibHoldings for LibHoldings.Holding;
using LibHoldings for LibHoldings.HoldingsSet;
using LibRedemptions for LibRedemptions.Redemption;
using LibRedemptions for LibRedemptions.RedemptionsQueue;
//inner types
struct DistributionContext {
uint distributionAmount;
uint receivedRedemptionAmount;
uint redemptionAmount;
uint tokenPriceWei;
uint currentRedemptionId;
uint totalRewardAmount;
}
struct WindUpContext {
uint totalWindUpAmount;
uint tokenReward;
uint paidReward;
address currenHolderAddress;
}
//constants
bool constant PREV = false;
bool constant NEXT = true;
//state
enum TokenStatus {
OnSale,
Trading,
Distributing,
WindingUp
}
///Status of the token contract
TokenStatus public tokenStatus;
///Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle;
LibHoldings.HoldingsSet internal holdings;
uint256 internal totalSupplyOfTokens;
LibRedemptions.RedemptionsQueue redemptionsQueue;
///The whole percentage number (0-100) of the total distributable profit
///amount available for token redemption in each profit distribution round
uint8 public redemptionPercentageOfDistribution;
mapping (address => mapping (address => uint256)) internal allowances;
uint [] internal rewards;
DistributionContext internal distCtx;
WindUpContext internal windUpCtx;
//ERC-20
///Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
///Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
///Token name
string public name;
///Token symbol
string public symbol;
///Number of decimals
uint8 public decimals;
///Returns total supply of Aqua Tokens
function totalSupply() constant external returns (uint256) {
return totalSupplyOfTokens;
}
/// Get the token balance for address _owner
function balanceOf(address _owner) public constant returns (uint256 balance) {
if (!holdings.exists(_owner))
return 0;
LibHoldings.Holding storage h = holdings.get(_owner);
return h.totalTokens.sub(h.lockedTokens);
}
///Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/// Send _value amount of tokens from address _from to address _to
/// The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// fees in sub-currencies; the command should fail unless the _from account has
/// deliberately authorized the sender of the message via some mechanism;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowances[_from][msg.sender]); // Check allowance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value);
return _transfer(_from, _to, _value);
}
/// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
if (tokenStatus == TokenStatus.OnSale) {
require(msg.sender == owner);
}
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// Returns the amount that _spender is allowed to withdraw from _owner account.
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
//custom public interface
///Event is fired when holder requests to redeem their tokens
///@param holder Account address of token holder requesting redemption
///@param _numberOfTokens Number of tokens requested
///@param _requestId ID assigned to the redemption request
event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId);
///Event is fired when holder cancels redemption request with ID = _requestId
///@param holder Account address of token holder cancelling redemption request
///@param _numberOfTokens Number of tokens affected
///@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
///Event occurs when the redemption request is redeemed.
///@param holder Account address of the token holder whose tokens were redeemed
///@param _requestId The ID of the redemption request
///@param _numberOfTokens The number of tokens redeemed
///@param amount The redeemed amount in Wei
event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount);
///Event occurs when profit distribution is triggered
///@param amount Total amount (in Wei) available for this profit distribution round
event DistributionStarted(uint amount);
///Event occurs when profit distribution round completes
///@param redeemedAmount Total amount (in wei) redeemed in this distribution round
///@param rewardedAmount Total amount rewarded as dividends in this distribution round
///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua
event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount);
///Event is triggered when token holder withdraws their balance
///@param holderAddress Address of the token holder account
///@param amount Amount in wei that has been withdrawn
///@param hasRemainingBalance True if there is still remaining balance
event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance);
///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and
///dividend payments during profit distribution round
///@param _continue True if the distribution hasn’t completed as yet
event ContinueDistribution(bool _continue);
///The event is fired when wind-up procedure starts
///@param amount Total amount in Wei available for final distribution among token holders
event WindingUpStarted(uint amount);
///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed
event StartTrading();
///Event is triggered when a token holders destroys their tokens
///@param from Account address of the token holder
///@param numberOfTokens Number of tokens burned (permanently destroyed)
event Burn(address indexed from, uint256 numberOfTokens);
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
uint8 _redemptionPercentageOfDistribution,
address _priceOracle
) public
{
totalSupplyOfTokens = initialSupply;
holdings.add(msg.sender, LibHoldings.Holding({
totalTokens : initialSupply,
lockedTokens : 0,
lastRewardNumber : 0,
weiBalance : 0
}));
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
priceOracle = AquaPriceOracle(_priceOracle);
owner = msg.sender;
tokenStatus = TokenStatus.OnSale;
rewards.push(0);
}
///Called by token owner enable trading with tokens
function startTrading() onlyOwner external {
require(tokenStatus == TokenStatus.OnSale);
tokenStatus = TokenStatus.Trading;
StartTrading();
}
///Token holders can call this function to request to redeem (sell back to
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
LibHoldings.Holding storage h = holdings.get(msg.sender);
require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough
uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);
h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
return redemptionId;
}
///Token holders can call this function to cancel a redemption request they
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
require(r.holderAddress == msg.sender);
LibHoldings.Holding storage h = holdings.get(msg.sender);
h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
uint numberOfTokens = r.numberOfTokens;
redemptionsQueue.remove(_requestId);
CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);
}
///The function is used to enumerate redemption requests. It returns the first redemption request ID.
///@return First redemption request ID
function firstRedemptionRequest() public constant returns (uint) {
return redemptionsQueue.firstRedemption();
}
///The function is used to enumerate redemption requests. It returns the
///next redemption request ID following the supplied one.
///@param _currentRedemptionId Current redemption request ID
///@return Next redemption request ID
function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) {
return redemptionsQueue.nextRedemption(_currentRedemptionId);
}
///The function returns redemption request details for the supplied redemption request ID
///@param _requestId Redemption request ID
///@return _holderAddress Token holder account address
///@return _numberOfTokens Number of tokens requested to redeem
function getRedemptionRequest(uint _requestId) public constant returns
(address _holderAddress, uint256 _numberOfTokens) {
LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId);
_holderAddress = r.holderAddress;
_numberOfTokens = r.numberOfTokens;
}
///The function is used to enumerate token holders. It returns the first
///token holder (that the enumeration starts from)
///@return Account address of the first token holder
function firstHolder() public constant returns (address) {
return holdings.firstHolder();
}
///The function is used to enumerate token holders. It returns the address
///of the next token holder given the token holder address.
///@param _currentHolder Account address of the token holder
///@return Account address of the next token holder
function nextHolder(address _currentHolder) public constant returns (address) {
return holdings.nextHolder(_currentHolder);
}
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant
returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
if (!holdings.exists(_holder)) {
totalTokens = 0;
lockedTokens = 0;
weiBalance = 0;
return;
}
LibHoldings.Holding storage h = holdings.get(_holder);
totalTokens = h.totalTokens;
lockedTokens = h.lockedTokens;
uint stepsMade;
(weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
return;
}
///Token owner calls this function to start profit distribution round
function startDistribuion() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.Distributing;
startRedemption(msg.value);
DistributionStarted(msg.value);
}
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
require(tokenStatus == TokenStatus.Distributing);
if (continueRedeeming(maxNumbeOfSteps)) {
ContinueDistribution(true);
return true;
}
uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
if (unusedDistributionAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedDistributionAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
}
}
tokenStatus = TokenStatus.Trading;
DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount),
paidReward, unusedDistributionAmount);
ContinueDistribution(false);
return false;
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
require(holdings.exists(msg.sender));
LibHoldings.Holding storage h = holdings.get(msg.sender);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
h.weiBalance = 0;
h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
if (h.totalTokens == 0 && h.weiBalance == 0)
holdings.remove(msg.sender);
msg.sender.transfer(updatedBalance);
WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
}
///Token holder can call this function to withdraw their balance (dividend
///and redemption payments)
function withdrawBalance() public {
withdrawBalanceMaxSteps(0);
}
///Set allowance for other address and notify
///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it
///@param _spender The address authorized to spend
///@param _value the max amount they can spend
///@param _extraData some extra information to send to the approved contract
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) {
require(holdings.exists(msg.sender));
if (numberOfTokens == 0) {
Burn(msg.sender, numberOfTokens);
return true;
}
LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(msg.sender);
totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);
Burn(msg.sender, numberOfTokens);
return true;
}
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
require(tokenStatus == TokenStatus.Trading);
tokenStatus = TokenStatus.WindingUp;
uint totalWindUpAmount = msg.value;
uint tokenReward = msg.value.div(totalSupplyOfTokens);
rewards.push(tokenReward);
uint paidReward = tokenReward.mul(totalSupplyOfTokens);
uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
if (unusedWindUpAmount > 0) {
if (!holdings.exists(owner)) {
holdings.add(owner, LibHoldings.Holding({
totalTokens : 0,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : unusedWindUpAmount
}));
}
else {
LibHoldings.Holding storage ownerHolding = holdings.get(owner);
ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
}
}
WindingUpStarted(msg.value);
}
//internal functions
function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal
returns(uint updatedBalance, uint stepsMade) {
(updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps);
if (stepsMade == 0)
return;
holding.weiBalance = updatedBalance;
holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade);
}
function startRedemption(uint distributionAmount) internal {
distCtx.distributionAmount = distributionAmount;
distCtx.receivedRedemptionAmount =
(distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100);
distCtx.redemptionAmount = distCtx.receivedRedemptionAmount;
distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice());
distCtx.currentRedemptionId = redemptionsQueue.firstRedemption();
}
function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) {
uint remainingNoSteps = maxNumbeOfSteps;
uint currentId = distCtx.currentRedemptionId;
uint redemptionAmount = distCtx.redemptionAmount;
uint totalRedeemedTokens = 0;
while(currentId != 0 && redemptionAmount > 0) {
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens );
}
return true;
}
if (redemptionAmount.div(distCtx.tokenPriceWei) < 1)
break;
LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId);
LibHoldings.Holding storage holding = holdings.get(r.holderAddress);
uint updatedBalance;
uint stepsMade;
(updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps);
remainingNoSteps = remainingNoSteps.sub(stepsMade);
if (remainingNoSteps == 0) {
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
if (totalRedeemedTokens > 0) {
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
}
return true;
}
uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei);
if (holderTokensToRedeem > r.numberOfTokens)
holderTokensToRedeem = r.numberOfTokens;
uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei);
holding.weiBalance = holding.weiBalance.add( holderRedemption );
redemptionAmount = redemptionAmount.sub( holderRedemption );
r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem );
holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem);
holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem);
totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem );
uint nextId = redemptionsQueue.nextRedemption(currentId);
HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption);
if (r.numberOfTokens == 0)
redemptionsQueue.remove(currentId);
currentId = nextId;
remainingNoSteps = remainingNoSteps.sub(1);
}
distCtx.currentRedemptionId = currentId;
distCtx.redemptionAmount = redemptionAmount;
totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens);
distCtx.totalRewardAmount =
distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount);
return false;
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
if (tokenStatus == TokenStatus.OnSale) {
require(_from == owner);
}
if (_value == 0) {
Transfer(_from, _to, _value);
return true;
}
require(holdings.exists(_from));
LibHoldings.Holding storage fromHolding = holdings.get(_from);
require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough
if (!holdings.exists(_to)) {
holdings.add(_to, LibHoldings.Holding({
totalTokens : _value,
lockedTokens : 0,
lastRewardNumber : rewards.length.sub(1),
weiBalance : 0
}));
}
else {
LibHoldings.Holding storage toHolding = holdings.get(_to);
require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows
updateWeiBalance(toHolding, 0);
toHolding.totalTokens = toHolding.totalTokens.add(_value);
}
updateWeiBalance(fromHolding, 0);
fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender
if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0)
holdings.remove(_from);
Transfer(_from, _to, _value);
return true;
}
} | calcFullWeiBalance | function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant
returns(uint updatedBalance, uint stepsMade) {
uint fromRewardIdx = holding.lastRewardNumber.add(1);
updatedBalance = holding.weiBalance;
if (fromRewardIdx == rewards.length) {
stepsMade = 0;
return;
}
uint toRewardIdx;
if (maxSteps == 0) {
toRewardIdx = rewards.length.sub( 1);
}
else {
toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1);
if (toRewardIdx > rewards.length.sub(1)) {
toRewardIdx = rewards.length.sub(1);
}
}
for(uint idx = fromRewardIdx;
idx <= toRewardIdx;
idx = idx.add(1)) {
updatedBalance = updatedBalance.add(
rewards[idx].mul( holding.totalTokens )
);
}
stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 );
return;
}
| //internal functions | LineComment | v0.4.20+commit.3155dd80 | bzzr://373bce966b5a3a64cb5cee60e45ef2089d4f385eea83351e825cfda31d420536 | {
"func_code_index": [
20327,
21404
]
} | 9,226 |
|||
BitMonsters | contracts/Minter.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | Minter | contract Minter is BitMonstersAddon {
using RngLibrary for Rng;
uint256 constant public WHITELIST_PER = 6;
address payable private payHere;
// 0 == "not whitelisted"
// 1000 + x == "whitelisted and x whitelists left"
mapping (address => uint256) public whitelist;
MintingState public mintingState;
bool[9] public mintedSpecials;
uint private mintedSpecialsCount = 0;
Rng private rng;
constructor(address payable paymentAddress, address[] memory whitelistedAddrs) {
payHere = paymentAddress;
whitelist[paymentAddress] = WHITELIST_PER + 1000;
for (uint i = 0; i < whitelistedAddrs.length; ++i) {
whitelist[whitelistedAddrs[i]] = WHITELIST_PER + 1000;
}
rng = RngLibrary.newRng();
}
/**
* Adds someone to the whitelist.
*/
function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
/**
* Removes someone from the whitelist.
*/
function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
/**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
/**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/
function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
/**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/
function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
/**
* Mint for a giveaway.
*/
function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
} | addToWhitelist | function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
| /**
* Adds someone to the whitelist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
868,
1131
]
} | 9,227 |
||
BitMonsters | contracts/Minter.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | Minter | contract Minter is BitMonstersAddon {
using RngLibrary for Rng;
uint256 constant public WHITELIST_PER = 6;
address payable private payHere;
// 0 == "not whitelisted"
// 1000 + x == "whitelisted and x whitelists left"
mapping (address => uint256) public whitelist;
MintingState public mintingState;
bool[9] public mintedSpecials;
uint private mintedSpecialsCount = 0;
Rng private rng;
constructor(address payable paymentAddress, address[] memory whitelistedAddrs) {
payHere = paymentAddress;
whitelist[paymentAddress] = WHITELIST_PER + 1000;
for (uint i = 0; i < whitelistedAddrs.length; ++i) {
whitelist[whitelistedAddrs[i]] = WHITELIST_PER + 1000;
}
rng = RngLibrary.newRng();
}
/**
* Adds someone to the whitelist.
*/
function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
/**
* Removes someone from the whitelist.
*/
function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
/**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
/**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/
function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
/**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/
function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
/**
* Mint for a giveaway.
*/
function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
} | removeFromWhitelist | function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
| /**
* Removes someone from the whitelist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
1196,
1304
]
} | 9,228 |
||
BitMonsters | contracts/Minter.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | Minter | contract Minter is BitMonstersAddon {
using RngLibrary for Rng;
uint256 constant public WHITELIST_PER = 6;
address payable private payHere;
// 0 == "not whitelisted"
// 1000 + x == "whitelisted and x whitelists left"
mapping (address => uint256) public whitelist;
MintingState public mintingState;
bool[9] public mintedSpecials;
uint private mintedSpecialsCount = 0;
Rng private rng;
constructor(address payable paymentAddress, address[] memory whitelistedAddrs) {
payHere = paymentAddress;
whitelist[paymentAddress] = WHITELIST_PER + 1000;
for (uint i = 0; i < whitelistedAddrs.length; ++i) {
whitelist[whitelistedAddrs[i]] = WHITELIST_PER + 1000;
}
rng = RngLibrary.newRng();
}
/**
* Adds someone to the whitelist.
*/
function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
/**
* Removes someone from the whitelist.
*/
function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
/**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
/**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/
function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
/**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/
function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
/**
* Mint for a giveaway.
*/
function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
} | generateBitMonster | function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
| /**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
1740,
2432
]
} | 9,229 |
||
BitMonsters | contracts/Minter.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | Minter | contract Minter is BitMonstersAddon {
using RngLibrary for Rng;
uint256 constant public WHITELIST_PER = 6;
address payable private payHere;
// 0 == "not whitelisted"
// 1000 + x == "whitelisted and x whitelists left"
mapping (address => uint256) public whitelist;
MintingState public mintingState;
bool[9] public mintedSpecials;
uint private mintedSpecialsCount = 0;
Rng private rng;
constructor(address payable paymentAddress, address[] memory whitelistedAddrs) {
payHere = paymentAddress;
whitelist[paymentAddress] = WHITELIST_PER + 1000;
for (uint i = 0; i < whitelistedAddrs.length; ++i) {
whitelist[whitelistedAddrs[i]] = WHITELIST_PER + 1000;
}
rng = RngLibrary.newRng();
}
/**
* Adds someone to the whitelist.
*/
function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
/**
* Removes someone from the whitelist.
*/
function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
/**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
/**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/
function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
/**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/
function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
/**
* Mint for a giveaway.
*/
function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
} | setMintingState | function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
| /**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
2623,
2731
]
} | 9,230 |
||
BitMonsters | contracts/Minter.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | Minter | contract Minter is BitMonstersAddon {
using RngLibrary for Rng;
uint256 constant public WHITELIST_PER = 6;
address payable private payHere;
// 0 == "not whitelisted"
// 1000 + x == "whitelisted and x whitelists left"
mapping (address => uint256) public whitelist;
MintingState public mintingState;
bool[9] public mintedSpecials;
uint private mintedSpecialsCount = 0;
Rng private rng;
constructor(address payable paymentAddress, address[] memory whitelistedAddrs) {
payHere = paymentAddress;
whitelist[paymentAddress] = WHITELIST_PER + 1000;
for (uint i = 0; i < whitelistedAddrs.length; ++i) {
whitelist[whitelistedAddrs[i]] = WHITELIST_PER + 1000;
}
rng = RngLibrary.newRng();
}
/**
* Adds someone to the whitelist.
*/
function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
/**
* Removes someone from the whitelist.
*/
function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
/**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
/**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/
function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
/**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/
function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
/**
* Mint for a giveaway.
*/
function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
} | mint | function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
| /**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
2957,
3873
]
} | 9,231 |
||
BitMonsters | contracts/Minter.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | Minter | contract Minter is BitMonstersAddon {
using RngLibrary for Rng;
uint256 constant public WHITELIST_PER = 6;
address payable private payHere;
// 0 == "not whitelisted"
// 1000 + x == "whitelisted and x whitelists left"
mapping (address => uint256) public whitelist;
MintingState public mintingState;
bool[9] public mintedSpecials;
uint private mintedSpecialsCount = 0;
Rng private rng;
constructor(address payable paymentAddress, address[] memory whitelistedAddrs) {
payHere = paymentAddress;
whitelist[paymentAddress] = WHITELIST_PER + 1000;
for (uint i = 0; i < whitelistedAddrs.length; ++i) {
whitelist[whitelistedAddrs[i]] = WHITELIST_PER + 1000;
}
rng = RngLibrary.newRng();
}
/**
* Adds someone to the whitelist.
*/
function addToWhitelist(address[] memory addrs) external onlyAdmin {
for (uint i = 0; i < addrs.length; ++i) {
if (whitelist[addrs[i]] == 0) {
whitelist[addrs[i]] = WHITELIST_PER + 1000;
}
}
}
/**
* Removes someone from the whitelist.
*/
function removeFromWhitelist(address addr) external onlyAdmin {
delete whitelist[addr];
}
/**
* Generates a random Bit Monster.
*
* 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
* All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
* The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
*/
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
uint count = bitMonsters.totalSupply();
int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
if (ub < 0) {
ub = 0;
}
BitMonster memory m;
if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
}
else {
m = BitMonsterGen.generateUnspecialBitMonster(rn);
}
if (m.special != Special.NONE) {
mintedSpecialsCount++;
}
rng = rn;
return m;
}
/**
* Sets the MintingState. See MintingState above.
* By default, no one is allowed to mint. This function must be called before any Bit Monsters can be minted.
*/
function setMintingState(MintingState state) external onlyAdmin {
mintingState = state;
}
/**
* Mints some Bit Monsters.
*
* @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
* You must send 0.06 ETH for each Bit Monster you want to mint.
*/
function mint(uint count) external payable {
require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
require(!Address.isContract(msg.sender), "Contracts cannot mint");
require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");
if (mintingState == MintingState.WhitelistOnly) {
require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
whitelist[msg.sender] -= count;
}
require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");
Rng memory rn = rng;
bool[9] memory ms = mintedSpecials;
for (uint i = 0; i < count; ++i) {
bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
}
rng = rn;
mintedSpecials = ms;
Address.sendValue(payHere, msg.value);
}
/**
* Mint for a giveaway.
*/
function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
} | giveawayMint | function giveawayMint(address[] memory winners) external onlyAdmin {
Rng memory rn = rng;
for (uint i = 0; i < winners.length; ++i) {
bitMonsters.createBitMonster(BitMonsterGen.generateUnspecialBitMonster(rn), winners[i]);
}
rng = rn;
}
| /**
* Mint for a giveaway.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
3923,
4222
]
} | 9,232 |
||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | mul | 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, reverts on overflow.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
88,
484
]
} | 9,233 |
|
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 c;
}
| /**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
596,
875
]
} | 9,234 |
|
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| /**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
990,
1127
]
} | 9,235 |
|
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
| /**
* @dev Adds two numbers, reverts on overflow.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
1192,
1329
]
} | 9,236 |
|
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| /**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
1464,
1581
]
} | 9,237 |
|
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | totalSupply | function totalSupply() public view returns (uint256) {
return _totalSupply;
}
| /**
* @dev Total number of tokens in existence
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
279,
367
]
} | 9,238 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | balanceOf | function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
568,
671
]
} | 9,239 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | allowance | function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
995,
1157
]
} | 9,240 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | transfer | function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
| /**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
1313,
1446
]
} | 9,241 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | approve | function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| /**
* @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.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
2070,
2299
]
} | 9,242 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | transferFrom | function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @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
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
2576,
2884
]
} | 9,243 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | increaseAllowance | function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| /**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
3343,
3691
]
} | 9,244 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | decreaseAllowance | function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
4155,
4513
]
} | 9,245 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | _transfer | function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| /**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
4720,
5088
]
} | 9,246 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | _mint | function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
| /**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
5421,
5668
]
} | 9,247 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | _burn | function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
| /**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
5889,
6179
]
} | 9,248 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @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.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "Insignificant balance in from address");
require(to != address(0), "Invalid to address specified [0x0]");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints 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 account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | _burnFrom | function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
| /**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
6493,
6896
]
} | 9,249 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | Pausable | contract Pausable is Ownable {
bool public paused;
modifier ifNotPaused {
require(!paused, "Contract is paused");
_;
}
modifier ifPaused {
require(paused, "Contract is not paused");
_;
}
// Called by the owner on emergency, triggers paused state
function pause() external onlyOwner {
paused = true;
}
// Called by the owner on end of emergency, returns to normal state
function resume() external onlyOwner ifPaused {
paused = false;
}
} | pause | function pause() external onlyOwner {
paused = true;
}
| // Called by the owner on emergency, triggers paused state | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
319,
392
]
} | 9,250 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | Pausable | contract Pausable is Ownable {
bool public paused;
modifier ifNotPaused {
require(!paused, "Contract is paused");
_;
}
modifier ifPaused {
require(paused, "Contract is not paused");
_;
}
// Called by the owner on emergency, triggers paused state
function pause() external onlyOwner {
paused = true;
}
// Called by the owner on end of emergency, returns to normal state
function resume() external onlyOwner ifPaused {
paused = false;
}
} | resume | function resume() external onlyOwner ifPaused {
paused = false;
}
| // Called by the owner on end of emergency, returns to normal state | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
468,
552
]
} | 9,251 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | getTotalTokensRemaining | function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
| /**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
775,
925
]
} | 9,252 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | isAddressInAirdropList | function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
| /**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
1080,
1299
]
} | 9,253 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | bulkAddAddressesToAirDrop | function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
| /**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
1454,
1714
]
} | 9,254 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | bulkAddAddressesToAirDropWithAward | function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
| /**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
1880,
2223
]
} | 9,255 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | _addAddressToAirdropWithAward | function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
| /**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
2550,
2981
]
} | 9,256 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | _addAddressToAirDrop | function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
| /**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
3130,
3486
]
} | 9,257 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | bulkRemoveAddressesFromAirDrop | function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
| /**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
3626,
3904
]
} | 9,258 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | _removeAddressFromAirDrop | function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
| /**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
4027,
4392
]
} | 9,259 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | claimTokens | function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
| /**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
4880,
5402
]
} | 9,260 |
|||
SparkleAirDrop | SparkleAirDrop.sol | 0x33d9eb04442b7711cec632384df6bba45b141d3a | Solidity | AirDropWinners | contract AirDropWinners is Ownable, Pausable {
using SafeMath for uint256;
struct Contribution {
uint256 tokenAmount;
bool wasClaimed;
bool isValid;
}
address public tokenAddress; //Smartcontract Address
uint256 public totalTokensClaimed; // Totaltokens claimed by winners (you do not set this the contract does as tokens are claimed)
uint256 public startTime; // airDrop Start time
mapping (address => Contribution) contributions;
constructor (address _token)
Ownable()
public {
tokenAddress = _token;
startTime = now;
}
/**
* @dev getTotalTokensRemaining() provides the function of returning the number of
* tokens currently left in the airdrop balance
*/
function getTotalTokensRemaining()
ifNotPaused
public
view
returns (uint256)
{
return ERC20(tokenAddress).balanceOf(this);
}
/**
* @dev isAddressInAirdropList() provides the function of testing if the
* specified address is in fact valid in the airdrop list
*/
function isAddressInAirdropList(address _addressToLookUp)
ifNotPaused
public
view
returns (bool)
{
Contribution storage contrib = contributions[_addressToLookUp];
return contrib.isValid;
}
/**
* @dev _bulkAddAddressesToAirdrop provides the function of adding addresses
* to the airdrop list with the default of 30 sparkle
*/
function bulkAddAddressesToAirDrop(address[] _addressesToAdd)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirDrop(_addressesToAdd[i]);
}
}
/**
* @dev _bulkAddAddressesToAirdropWithAward provides the function of adding addresses
* to the airdrop list with a specific number of tokens
*/
function bulkAddAddressesToAirDropWithAward(address[] _addressesToAdd, uint256 _tokenAward)
ifNotPaused
public
{
require(_addressesToAdd.length > 0);
require(_tokenAward > 0);
for (uint i = 0; i < _addressesToAdd.length; i++) {
_addAddressToAirdropWithAward(_addressesToAdd[i], _tokenAward);
}
}
/**
* @dev _addAddressToAirdropWithAward provides the function of adding an address to the
* airdrop list with a specific number of tokens opposed to the default of
* 30 Sparkle
* @dev NOTE: _tokenAward will be converted so value only needs to be whole number
* Ex: 30 opposed to 30 * (10e7)
*/
function _addAddressToAirdropWithAward(address _addressToAdd, uint256 _tokenAward)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
require(_tokenAward > 0);
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = _tokenAward.mul(10e7);
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev _addAddressToAirdrop provides the function of adding an address to the
* airdrop list with the default of 30 sparkle
*/
function _addAddressToAirDrop(address _addressToAdd)
onlyOwner
internal
{
require(_addressToAdd != 0);
require(!isAddressInAirdropList(_addressToAdd));
Contribution storage contrib = contributions[_addressToAdd];
contrib.tokenAmount = 30 * 10e7;
contrib.wasClaimed = false;
contrib.isValid = true;
}
/**
* @dev bulkRemoveAddressesFromAirDrop provides the function of removing airdrop
* addresses from the airdrop list
*/
function bulkRemoveAddressesFromAirDrop(address[] _addressesToRemove)
ifNotPaused
public
{
require(_addressesToRemove.length > 0);
for (uint i = 0; i < _addressesToRemove.length; i++) {
_removeAddressFromAirDrop(_addressesToRemove[i]);
}
}
/**
* @dev _removeAddressFromAirDrop provides the function of removing an address from
* the airdrop
*/
function _removeAddressFromAirDrop(address _addressToRemove)
onlyOwner
internal
{
require(_addressToRemove != 0);
require(isAddressInAirdropList(_addressToRemove));
Contribution storage contrib = contributions[_addressToRemove];
contrib.tokenAmount = 0;
contrib.wasClaimed = false;
contrib.isValid = false;
}
function setAirdropAddressWasClaimed(address _addressToChange, bool _newWasClaimedValue)
ifNotPaused
onlyOwner
public
{
require(_addressToChange != 0);
require(isAddressInAirdropList(_addressToChange));
Contribution storage contrib = contributions[ _addressToChange];
require(contrib.isValid);
contrib.wasClaimed = _newWasClaimedValue;
}
/**
* @dev claimTokens() provides airdrop winners the function of collecting their tokens
*/
function claimTokens()
ifNotPaused
public {
Contribution storage contrib = contributions[msg.sender];
require(contrib.isValid, "Address not found in airdrop list");
require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
uint256 tempPendingTokens = contrib.tokenAmount;
contrib.tokenAmount = 0;
totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
contrib.wasClaimed = true;
ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
}
/**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/
function() payable public {
revert("ETH not accepted");
}
} | function() payable public {
revert("ETH not accepted");
}
| /**
* @dev () is the default payable function. Since this contract should not accept
* revert the transaction best as possible.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://a3ad412f8d55113db356bb9eeeb4e6c94debf29d915de7e12ab920f863c18039 | {
"func_code_index": [
5551,
5619
]
} | 9,261 |
||||
BitMonsters | contracts/BitMonsters.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | BitMonsters | contract BitMonsters is IBitMonsters, ERC721Enumerable, Ownable {
uint256 constant public SUPPLY_LIMIT = 6666;
using RngLibrary for Rng;
mapping (uint256 => BitMonster) public tokenIdToBitMonster;
Brainz public brainz;
Mutator public mutator;
Minter public minter;
Metadata public metadata;
mapping (address => bool) private admins;
bool private initialized;
/**
* @param whitelistedAddrs The addresses that are allowed to mint when the mintingState is WhiteListOnly.
The owner of the contract is automatically whitelisted, so the owning address doesn't need to be given.
*/
constructor(address[] memory whitelistedAddrs) ERC721("Bit Monsters", unicode"💰🧟") {
brainz = new Brainz();
mutator = new Mutator(brainz);
minter = new Minter(payable(msg.sender), whitelistedAddrs);
metadata = new Metadata();
address[5] memory a = [msg.sender, address(brainz), address(mutator), address(minter), address(metadata)];
for (uint i = 0; i < a.length; ++i) {
admins[a[i]] = true;
}
}
function isAdmin(address addr) public view override returns (bool) {
return owner() == addr || admins[addr];
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), "admins only");
_;
}
function addAdmin(address addr) external onlyAdmin {
admins[addr] = true;
}
function removeAdmin(address addr) external onlyAdmin {
admins[addr] = false;
}
/**
* Initializes the sub contracts so they're ready for use.
* @notice IMPORTANT: This must be called before any other contract functions.
*
* @dev This can't be done in the constructor, because the contract doesn't have an address until the transaction is mined.
*/
function initialize() external onlyAdmin {
if (initialized) {
return;
}
initialized = true;
admins[address(this)] = true;
brainz.setBitMonstersContract(this);
metadata.setBitMonstersContract(this);
mutator.setBitMonstersContract(this);
minter.setBitMonstersContract(this);
}
/**
* Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea.
*
* @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "the token doesn't exist");
string memory metadataRaw = metadata.getMetadataJson(tokenId);
string memory metadataB64 = Base64.encode(bytes(metadataRaw));
return string(abi.encodePacked(
"data:application/json;base64,",
metadataB64
));
}
/**
* Returns the internal representation of the Bit Monster corresponding to the given tokenId.
*/
function getBitMonster(uint256 tokenId) external view override returns (BitMonster memory) {
return tokenIdToBitMonster[tokenId];
}
function setBitMonster(uint256 tokenId, BitMonster memory bm) public override onlyAdmin {
tokenIdToBitMonster[tokenId] = bm;
}
function createBitMonster(BitMonster memory bm, address owner) external override onlyAdmin {
uint total = totalSupply();
require(total <= SUPPLY_LIMIT, "Supply limit reached");
uint tid = total + 1;
_mint(owner, tid);
setBitMonster(tid, bm);
brainz.register(tid);
}
} | /**
* @title The Bit Monsters contract. This is where all of the magic happens.
*/ | NatSpecMultiLine | initialize | function initialize() external onlyAdmin {
if (initialized) {
return;
}
initialized = true;
admins[address(this)] = true;
brainz.setBitMonstersContract(this);
metadata.setBitMonstersContract(this);
mutator.setBitMonstersContract(this);
minter.setBitMonstersContract(this);
}
| /**
* Initializes the sub contracts so they're ready for use.
* @notice IMPORTANT: This must be called before any other contract functions.
*
* @dev This can't be done in the constructor, because the contract doesn't have an address until the transaction is mined.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
1898,
2269
]
} | 9,262 |
BitMonsters | contracts/BitMonsters.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | BitMonsters | contract BitMonsters is IBitMonsters, ERC721Enumerable, Ownable {
uint256 constant public SUPPLY_LIMIT = 6666;
using RngLibrary for Rng;
mapping (uint256 => BitMonster) public tokenIdToBitMonster;
Brainz public brainz;
Mutator public mutator;
Minter public minter;
Metadata public metadata;
mapping (address => bool) private admins;
bool private initialized;
/**
* @param whitelistedAddrs The addresses that are allowed to mint when the mintingState is WhiteListOnly.
The owner of the contract is automatically whitelisted, so the owning address doesn't need to be given.
*/
constructor(address[] memory whitelistedAddrs) ERC721("Bit Monsters", unicode"💰🧟") {
brainz = new Brainz();
mutator = new Mutator(brainz);
minter = new Minter(payable(msg.sender), whitelistedAddrs);
metadata = new Metadata();
address[5] memory a = [msg.sender, address(brainz), address(mutator), address(minter), address(metadata)];
for (uint i = 0; i < a.length; ++i) {
admins[a[i]] = true;
}
}
function isAdmin(address addr) public view override returns (bool) {
return owner() == addr || admins[addr];
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), "admins only");
_;
}
function addAdmin(address addr) external onlyAdmin {
admins[addr] = true;
}
function removeAdmin(address addr) external onlyAdmin {
admins[addr] = false;
}
/**
* Initializes the sub contracts so they're ready for use.
* @notice IMPORTANT: This must be called before any other contract functions.
*
* @dev This can't be done in the constructor, because the contract doesn't have an address until the transaction is mined.
*/
function initialize() external onlyAdmin {
if (initialized) {
return;
}
initialized = true;
admins[address(this)] = true;
brainz.setBitMonstersContract(this);
metadata.setBitMonstersContract(this);
mutator.setBitMonstersContract(this);
minter.setBitMonstersContract(this);
}
/**
* Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea.
*
* @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "the token doesn't exist");
string memory metadataRaw = metadata.getMetadataJson(tokenId);
string memory metadataB64 = Base64.encode(bytes(metadataRaw));
return string(abi.encodePacked(
"data:application/json;base64,",
metadataB64
));
}
/**
* Returns the internal representation of the Bit Monster corresponding to the given tokenId.
*/
function getBitMonster(uint256 tokenId) external view override returns (BitMonster memory) {
return tokenIdToBitMonster[tokenId];
}
function setBitMonster(uint256 tokenId, BitMonster memory bm) public override onlyAdmin {
tokenIdToBitMonster[tokenId] = bm;
}
function createBitMonster(BitMonster memory bm, address owner) external override onlyAdmin {
uint total = totalSupply();
require(total <= SUPPLY_LIMIT, "Supply limit reached");
uint tid = total + 1;
_mint(owner, tid);
setBitMonster(tid, bm);
brainz.register(tid);
}
} | /**
* @title The Bit Monsters contract. This is where all of the magic happens.
*/ | NatSpecMultiLine | tokenURI | function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "the token doesn't exist");
string memory metadataRaw = metadata.getMetadataJson(tokenId);
string memory metadataB64 = Base64.encode(bytes(metadataRaw));
return string(abi.encodePacked(
"data:application/json;base64,",
metadataB64
));
}
| /**
* Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea.
*
* @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
2595,
3024
]
} | 9,263 |
BitMonsters | contracts/BitMonsters.sol | 0xbd091f143ee754f1d755494441aee781d918cb93 | Solidity | BitMonsters | contract BitMonsters is IBitMonsters, ERC721Enumerable, Ownable {
uint256 constant public SUPPLY_LIMIT = 6666;
using RngLibrary for Rng;
mapping (uint256 => BitMonster) public tokenIdToBitMonster;
Brainz public brainz;
Mutator public mutator;
Minter public minter;
Metadata public metadata;
mapping (address => bool) private admins;
bool private initialized;
/**
* @param whitelistedAddrs The addresses that are allowed to mint when the mintingState is WhiteListOnly.
The owner of the contract is automatically whitelisted, so the owning address doesn't need to be given.
*/
constructor(address[] memory whitelistedAddrs) ERC721("Bit Monsters", unicode"💰🧟") {
brainz = new Brainz();
mutator = new Mutator(brainz);
minter = new Minter(payable(msg.sender), whitelistedAddrs);
metadata = new Metadata();
address[5] memory a = [msg.sender, address(brainz), address(mutator), address(minter), address(metadata)];
for (uint i = 0; i < a.length; ++i) {
admins[a[i]] = true;
}
}
function isAdmin(address addr) public view override returns (bool) {
return owner() == addr || admins[addr];
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), "admins only");
_;
}
function addAdmin(address addr) external onlyAdmin {
admins[addr] = true;
}
function removeAdmin(address addr) external onlyAdmin {
admins[addr] = false;
}
/**
* Initializes the sub contracts so they're ready for use.
* @notice IMPORTANT: This must be called before any other contract functions.
*
* @dev This can't be done in the constructor, because the contract doesn't have an address until the transaction is mined.
*/
function initialize() external onlyAdmin {
if (initialized) {
return;
}
initialized = true;
admins[address(this)] = true;
brainz.setBitMonstersContract(this);
metadata.setBitMonstersContract(this);
mutator.setBitMonstersContract(this);
minter.setBitMonstersContract(this);
}
/**
* Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea.
*
* @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "the token doesn't exist");
string memory metadataRaw = metadata.getMetadataJson(tokenId);
string memory metadataB64 = Base64.encode(bytes(metadataRaw));
return string(abi.encodePacked(
"data:application/json;base64,",
metadataB64
));
}
/**
* Returns the internal representation of the Bit Monster corresponding to the given tokenId.
*/
function getBitMonster(uint256 tokenId) external view override returns (BitMonster memory) {
return tokenIdToBitMonster[tokenId];
}
function setBitMonster(uint256 tokenId, BitMonster memory bm) public override onlyAdmin {
tokenIdToBitMonster[tokenId] = bm;
}
function createBitMonster(BitMonster memory bm, address owner) external override onlyAdmin {
uint total = totalSupply();
require(total <= SUPPLY_LIMIT, "Supply limit reached");
uint tid = total + 1;
_mint(owner, tid);
setBitMonster(tid, bm);
brainz.register(tid);
}
} | /**
* @title The Bit Monsters contract. This is where all of the magic happens.
*/ | NatSpecMultiLine | getBitMonster | function getBitMonster(uint256 tokenId) external view override returns (BitMonster memory) {
return tokenIdToBitMonster[tokenId];
}
| /**
* Returns the internal representation of the Bit Monster corresponding to the given tokenId.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://2641bc0a6897496103acbb493c7a9a096bcedd65afb1cb130ed46a31f4554f73 | {
"func_code_index": [
3144,
3294
]
} | 9,264 |
Swapper | Swapper.sol | 0xea483a51abbb216bf7f35b7a8d7eb7f040fa2e4e | Solidity | ERC20 | contract ERC20 {
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function decimals() public view returns (uint256);
//For WETH
function deposit() external payable;
function withdraw(uint) external;
} | /**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/ | NatSpecMultiLine | deposit | function deposit() external payable;
| //For WETH | LineComment | v0.5.16+commit.9c3226ce | MIT | bzzr://3b67425ec1919ddcaa546bf30f7782c44975dfae8796ced5ce88d7d9f8b2b2d0 | {
"func_code_index": [
755,
794
]
} | 9,265 |
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | Pausable | contract Pausable is GuidedByRoles {
mapping (address => bool) public unpausedWallet;
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address _to) {
require(!paused||unpausedWallet[msg.sender]||unpausedWallet[_to]);
_;
}
function onlyAdmin() internal view {
require(rightAndRoles.onlyRoles(msg.sender,3));
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function setUnpausedWallet(address _wallet, bool mode) public {
onlyAdmin();
unpausedWallet[_wallet] = mode;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function setPause(bool mode) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
if (!paused && mode) {
paused = true;
emit Pause();
}else
if (paused && !mode) {
paused = false;
emit Unpause();
}
}
} | setUnpausedWallet | function setUnpausedWallet(address _wallet, bool mode) public {
onlyAdmin();
unpausedWallet[_wallet] = mode;
}
| // Add a wallet ignoring the "Exchange pause". Available to the owner of the contract. | LineComment | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
622,
760
]
} | 9,266 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | Pausable | contract Pausable is GuidedByRoles {
mapping (address => bool) public unpausedWallet;
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address _to) {
require(!paused||unpausedWallet[msg.sender]||unpausedWallet[_to]);
_;
}
function onlyAdmin() internal view {
require(rightAndRoles.onlyRoles(msg.sender,3));
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function setUnpausedWallet(address _wallet, bool mode) public {
onlyAdmin();
unpausedWallet[_wallet] = mode;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function setPause(bool mode) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
if (!paused && mode) {
paused = true;
emit Pause();
}else
if (paused && !mode) {
paused = false;
emit Unpause();
}
}
} | setPause | function setPause(bool mode) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
if (!paused && mode) {
paused = true;
emit Pause();
}else
if (paused && !mode) {
paused = false;
emit Unpause();
}
}
| /**
* @dev called by the owner to pause, triggers stopped state
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
847,
1157
]
} | 9,267 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | totalSupply | function totalSupply() public view returns (uint256) {
return totalSupply_;
}
| /**
* @dev total number of tokens in existence
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
211,
307
]
} | 9,268 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | transfer | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
475,
903
]
} | 9,269 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
1119,
1239
]
} | 9,270 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | MigratableToken | contract MigratableToken is BasicToken,GuidedByRoles {
uint256 public totalMigrated;
address public migrationAgent;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
function setMigrationAgent(address _migrationAgent) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(totalMigrated == 0);
migrationAgent = _migrationAgent;
}
function migrateInternal(address _holder) internal{
require(migrationAgent != 0x0);
uint256 value = balances[_holder];
balances[_holder] = 0;
totalSupply_ = totalSupply_.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(_holder, value);
emit Migrate(_holder,migrationAgent,value);
}
function migrateAll(address[] _holders) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
for(uint i = 0; i < _holders.length; i++){
migrateInternal(_holders[i]);
}
}
// Reissue your tokens.
function migrate() public
{
require(balances[msg.sender] > 0);
migrateInternal(msg.sender);
}
} | migrate | function migrate() public
{
require(balances[msg.sender] > 0);
migrateInternal(msg.sender);
}
| // Reissue your tokens. | LineComment | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
1094,
1220
]
} | 9,271 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | BurnableToken | contract BurnableToken is BasicToken, GuidedByRoles {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(address _beneficiary, uint256 _value) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(_value <= balances[_beneficiary]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_beneficiary] = balances[_beneficiary].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_beneficiary, _value);
emit Transfer(_beneficiary, address(0), _value);
}
} | burn | function burn(address _beneficiary, uint256 _value) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(_value <= balances[_beneficiary]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_beneficiary] = balances[_beneficiary].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_beneficiary, _value);
emit Transfer(_beneficiary, address(0), _value);
}
| /**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
237,
821
]
} | 9,272 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @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
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
415,
908
]
} | 9,273 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | approve | function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @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.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
1560,
1771
]
} | 9,274 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | allowance | function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
2107,
2246
]
} | 9,275 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | increaseApproval | function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
2732,
3017
]
} | 9,276 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @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
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | decreaseApproval | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
3508,
3963
]
} | 9,277 |
|||
Token | Token.sol | 0xebd79044b0a3261b5f2ff95bd06e3a17e7d109fb | Solidity | MintableToken | contract MintableToken is StandardToken, GuidedByRoles {
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public returns (bool) {
require(rightAndRoles.onlyRoles(msg.sender,1));
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
} | mint | function mint(address _to, uint256 _amount) public returns (bool) {
require(rightAndRoles.onlyRoles(msg.sender,1));
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
| /**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/ | NatSpecMultiLine | v0.4.21+commit.dfe3193c | bzzr://d813d768c46e600abe9b980178301a526c61acb09e740c2c69727f636d0a77f0 | {
"func_code_index": [
390,
736
]
} | 9,278 |
|||
ValueVaultProfitSharer | contracts/vaults/ValueVaultProfitSharer.sol | 0x7c1c3116c99b7f8a35163331a33a09e2ebd1e862 | Solidity | ValueVaultProfitSharer | contract ValueVaultProfitSharer {
using SafeMath for uint256;
address public governance;
ValueLiquidityToken public valueToken;
IERC20Burnable public yfvToken;
address public govVault; // YFV -> VALUE, vUSD, vETH and 6.7% profit from Value Vaults
address public insuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start
address public performanceReward = 0x7Be4D5A99c903C437EC77A20CB6d0688cBB73c7f; // set to deploy wallet at start
uint256 public constant FEE_DENOMINATOR = 10000;
uint256 public insuranceFee = 0; // 0% at start and can be set by governance decision
uint256 public performanceFee = 0; // 0% at start and can be set by governance decision
uint256 public burnFee = 0; // 0% at start and can be set by governance decision
constructor(ValueLiquidityToken _valueToken, IERC20Burnable _yfvToken) public {
valueToken = _valueToken;
yfvToken = _yfvToken;
yfvToken.approve(address(valueToken), type(uint256).max);
governance = tx.origin;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setGovVault(address _govVault) public {
require(msg.sender == governance, "!governance");
govVault = _govVault;
}
function setInsuranceFund(address _insuranceFund) public {
require(msg.sender == governance, "!governance");
insuranceFund = _insuranceFund;
}
function setPerformanceReward(address _performanceReward) public{
require(msg.sender == governance, "!governance");
performanceReward = _performanceReward;
}
function setInsuranceFee(uint256 _insuranceFee) public {
require(msg.sender == governance, "!governance");
insuranceFee = _insuranceFee;
}
function setPerformanceFee(uint256 _performanceFee) public {
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function setBurnFee(uint256 _burnFee) public {
require(msg.sender == governance, "!governance");
burnFee = _burnFee;
}
function shareProfit() public returns (uint256 profit) {
if (govVault != address(0)) {
profit = yfvToken.balanceOf(address(this));
if (profit > 0) {
if (performanceReward != address(0) && performanceFee > 0) {
uint256 _performanceFee = profit.mul(performanceFee).div(FEE_DENOMINATOR);
yfvToken.transfer(performanceReward, _performanceFee);
}
if (insuranceFund != address(0) && insuranceFee > 0) {
uint256 _insuranceFee = profit.mul(insuranceFee).div(FEE_DENOMINATOR);
yfvToken.transfer(insuranceFund, _insuranceFee);
}
if (burnFee > 0) {
uint256 _burnFee = profit.mul(burnFee).div(FEE_DENOMINATOR);
yfvToken.burn(_burnFee);
}
uint256 balanceLeft = yfvToken.balanceOf(address(this));
valueToken.deposit(balanceLeft);
valueToken.approve(govVault, 0);
valueToken.approve(govVault, balanceLeft);
IGovVault(govVault).make_profit(balanceLeft);
}
}
}
/**
* This function allows governance to take unsupported tokens out of the contract.
* This is in an effort to make someone whole, should they seriously mess up.
* There is no guarantee governance will vote to return these.
* It also allows for removal of airdropped tokens.
*/
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
_token.transfer(to, amount);
}
} | governanceRecoverUnsupported | function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
_token.transfer(to, amount);
}
| /**
* This function allows governance to take unsupported tokens out of the contract.
* This is in an effort to make someone whole, should they seriously mess up.
* There is no guarantee governance will vote to return these.
* It also allows for removal of airdropped tokens.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://085864682220b518f31f4a2d8935ceb8b807e3cd25dce5015ffaecd05caad3a2 | {
"func_code_index": [
3816,
4016
]
} | 9,279 |
||
ORI | ORI.sol | 0xed54e0b27b29dcc1cd72179659de6fedfb8a8fd3 | Solidity | ORI | contract ORI is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Oliver Rogan Inu";//
string private constant _symbol = "ORI";//
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public launchBlock;
//Buy Fee
uint256 private _redisFeeOnBuy = 1;//
uint256 private _taxFeeOnBuy = 9;//
//Sell Fee
uint256 private _redisFeeOnSell = 1;//
uint256 private _taxFeeOnSell = 19;//
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xe2c1cA67abD8af4538Bc2B06980748c8E8C590DF);//
address payable private _marketingAddress = payable(0x7A869Ec53d176ACE2346f5640298CFB1D9aa0B52);//
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 10000000 * 10**9; //
uint256 public _maxWalletSize = 15000000 * 10**9; //
uint256 public _swapTokensAtAmount = 10000 * 10**9; //
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true;
bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true;
bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true;
bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true;
bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true;
bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
launchBlock = block.number;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set maximum transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | setMinSwapTokensThreshold | function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
| //Set minimum tokens required to swap. | LineComment | v0.8.4+commit.c7e474f2 | None | ipfs://049464cc21116dc99bc42156da4df77105ce66b20c9dc235f3f31f8ac2fe49db | {
"func_code_index": [
13978,
14122
]
} | 9,280 |
||
ORI | ORI.sol | 0xed54e0b27b29dcc1cd72179659de6fedfb8a8fd3 | Solidity | ORI | contract ORI is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Oliver Rogan Inu";//
string private constant _symbol = "ORI";//
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public launchBlock;
//Buy Fee
uint256 private _redisFeeOnBuy = 1;//
uint256 private _taxFeeOnBuy = 9;//
//Sell Fee
uint256 private _redisFeeOnSell = 1;//
uint256 private _taxFeeOnSell = 19;//
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xe2c1cA67abD8af4538Bc2B06980748c8E8C590DF);//
address payable private _marketingAddress = payable(0x7A869Ec53d176ACE2346f5640298CFB1D9aa0B52);//
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 10000000 * 10**9; //
uint256 public _maxWalletSize = 15000000 * 10**9; //
uint256 public _swapTokensAtAmount = 10000 * 10**9; //
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true;
bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true;
bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true;
bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true;
bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true;
bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
launchBlock = block.number;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set maximum transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | toggleSwap | function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
| //Set minimum tokens required to swap. | LineComment | v0.8.4+commit.c7e474f2 | None | ipfs://049464cc21116dc99bc42156da4df77105ce66b20c9dc235f3f31f8ac2fe49db | {
"func_code_index": [
14170,
14276
]
} | 9,281 |
||
ORI | ORI.sol | 0xed54e0b27b29dcc1cd72179659de6fedfb8a8fd3 | Solidity | ORI | contract ORI is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Oliver Rogan Inu";//
string private constant _symbol = "ORI";//
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public launchBlock;
//Buy Fee
uint256 private _redisFeeOnBuy = 1;//
uint256 private _taxFeeOnBuy = 9;//
//Sell Fee
uint256 private _redisFeeOnSell = 1;//
uint256 private _taxFeeOnSell = 19;//
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xe2c1cA67abD8af4538Bc2B06980748c8E8C590DF);//
address payable private _marketingAddress = payable(0x7A869Ec53d176ACE2346f5640298CFB1D9aa0B52);//
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 10000000 * 10**9; //
uint256 public _maxWalletSize = 15000000 * 10**9; //
uint256 public _swapTokensAtAmount = 10000 * 10**9; //
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true;
bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true;
bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true;
bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true;
bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true;
bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true;
bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){
bots[to] = true;
}
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
launchBlock = block.number;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set maximum transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | setMaxTxnAmount | function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
| //Set maximum transaction | LineComment | v0.8.4+commit.c7e474f2 | None | ipfs://049464cc21116dc99bc42156da4df77105ce66b20c9dc235f3f31f8ac2fe49db | {
"func_code_index": [
14314,
14427
]
} | 9,282 |
||
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | Ownable | contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
} | /// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable. | NatSpecSingleLine | Ownable | function Ownable() public {
owner = msg.sender;
}
| /// @dev Constructor sets the original `owner` of the contract to the sender account. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
331,
399
]
} | 9,283 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | Ownable | contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
} | /// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable. | NatSpecSingleLine | requestOwnershipTransfer | function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
| /// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
832,
1091
]
} | 9,284 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | Ownable | contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
} | /// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable. | NatSpecSingleLine | acceptOwnership | function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
| /// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
1200,
1442
]
} | 9,285 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | Standard223Receiver | contract Standard223Receiver is ERC223Receiver {
Tkn tkn;
struct Tkn {
address addr;
address sender; // the transaction caller
uint256 value;
}
bool __isTokenFallback;
modifier tokenPayable {
require(__isTokenFallback);
_;
}
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function supportsToken(address token) public constant returns (bool);
} | /// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier | NatSpecSingleLine | tokenFallback | function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
| /// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
542,
1237
]
} | 9,286 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | openForPublicTrade | function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
| /// @dev open the Market Maker for public trade. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
1608,
1738
]
} | 9,287 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | isOpenForPublic | function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
| /// @dev returns true iff the contract is open for public trade. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
1809,
1921
]
} | 9,288 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | supportsToken | function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
| /// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
2080,
2213
]
} | 9,289 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | initializeAfterTransfer | function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
| /// @dev initialize the contract after transfering all of the tokens form the pair | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
2302,
2439
]
} | 9,290 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | initializeOnTransfer | function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
| /// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
2543,
2695
]
} | 9,291 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | initialize | function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
| /// @dev initialize the contract. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
2735,
3050
]
} | 9,292 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | getCurrentPrice | function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
| /// @dev the price of token1 in terms of token2, represented in 18 decimals. | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
3133,
3255
]
} | 9,293 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | getPrice | function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
| /// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
3613,
3948
]
} | 9,294 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | quoteAndReserves | function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
| /// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
4205,
5198
]
} | 9,295 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | quote | function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
| /// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
5425,
6441
]
} | 9,296 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | calcReserve | function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
| /// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
6892,
7235
]
} | 9,297 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | change | function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
| /// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
7449,
7634
]
} | 9,298 |
|
EllipseMarketMakerLib | EllipseMarketMakerLib.sol | 0xc70636e0886ec4a4f2b7e42ac57ccd1b976352d0 | Solidity | EllipseMarketMakerLib | contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | /// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja. | NatSpecSingleLine | change | function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
| /// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token | NatSpecSingleLine | v0.4.18+commit.9cf6e910 | bzzr://e07437398c8063256f4539de2815dd3347816cfbdafa1a03c1a21987495774b0 | {
"func_code_index": [
7898,
8581
]
} | 9,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.