is there function like foreach from php in solidity? - foreach

this is so important, so when i made mapping
mapping(address => uint256) balances;
i cant check all address in the list like
foreach(balances as address => balance) log(address + ":" + balance + "\n");
so if i not store all address in sorted array i well not access any address in this array, so currently i use this:
mapping(address => uint8) joiners;
address[] members;
...
if (joiners[_to] >= 1) {
joiners[_to] = 1;
members.push(_to);
}
balances[_to] += _value;
so then i can do this
uint allbalances = 0;
for(uint i; i < members.length; i++) {
allbalances = balances[members[i]];
}
return allbalances;
but this is disgusting, any one find another solution, or function like foreach from php??

At this moment, You can not retrieve all the keys from the solidity mapping.
https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=mapping#mappings
I think that it is good to avoid loops in the contracts unless we know what we are doing. I could not get much on what you are trying to implement from your question. If your aim is to maintain the balances per address and also the total balances, I would do something similar as shown here.
contract Balance{
mapping(address => uint) public balances;
uint public totalBalance;
function credit() payable public{
balances[msg.sender] += msg.value;
totalBalance += msg.value;
}
function debit(uint amount) public{
//conditions
require(balances[msg.sender] >= amount);
//effects
msg.sender.transfer(amount);
balances[msg.sender] -= amount;
totalBalance -= amount;
}
}
That is - Update totalBalance whenever you update the individual address balance.
Updating as per the question on the comments section:
If we need to iterate all the accounts, then we need to maintain the keys separately. My point was - total Balance would be called a lot more often than distributing profit to all accounts. So to avoid loops there for total balance calculation.
contract Ledger{
address internal manager;
mapping(address => uint) public balances;
address[] public accounts;
uint public totalBalance;
constructor() public{
manager = msg.sender;
}
function credit() payable public{
if(balances[msg.sender] == 0){
accounts.push(msg.sender);
}
balances[msg.sender] += msg.value;
totalBalance += msg.value;
}
function debit(uint amount) public{
//conditions
require(balances[msg.sender] > amount);
//effects
msg.sender.transfer(amount);
balances[msg.sender] -= amount;
totalBalance -= amount;
}
function distributeProfit(uint amountToDistribute) public {
require(manager == msg.sender);
require(amountToDistribute > 0);
//if profit might vary depends of balance, then place inside the loop.
uint profit = amountToDistribute / accounts.length;
for(uint index=0; index<accounts.length; index++){
balances[accounts[index]] += profit;
}
}
}

Related

Update Token Information Page

I did the first 2 steps, verifying the contract address, but because I didn't know much about smart contracts before, I also created many wallets,enter image description here now the last step is to verify the signature, I don't know I used the wallet any. . Can anyone guide me to redo or what is possible in my case? Thank you very much alone! help
/**
*Submitted for verification at Etherscan.io on 2017-11-28
*/
pragma solidity ^0.4.17;
/**
* #title SafeMath
* #dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* #title Ownable
* #dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* #dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* #dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* #dev Allows the current owner to transfer control of the contract to a newOwner.
* #param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* #title ERC20Basic
* #dev Simpler version of ERC20 interface
* #dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* #title ERC20 interface
* #dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* #title Basic token
* #dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
// additional variables for use if transaction fees ever became necessary
uint public basisPointsRate = 0;
uint public maximumFee = 0;
/**
* #dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* #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, uint _value) public onlyPayloadSize(2 * 32) {
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(msg.sender, owner, fee);
}
Transfer(msg.sender, _to, sendAmount);
}
/**
* #dev Gets the balance of the specified address.
* #param _owner The address to query the the balance of.
* #return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* #title Standard ERC20 token
*
* #dev Implementation of the basic standard token.
* #dev https://github.com/ethereum/EIPs/issues/20
* #dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) public allowed;
uint public constant MAX_UINT = 2**256 - 1;
/**
* #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 uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
uint sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
Transfer(_from, owner, fee);
}
Transfer(_from, _to, sendAmount);
}
/**
* #dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* #param _spender The address which will spend the funds.
* #param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* #dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* #title Pausable
* #dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* #dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* #dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* #dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* #dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract UpgradedStandardToken is StandardToken{
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(address from, address to, uint value) public;
function transferFromByLegacy(address sender, address from, address spender, uint value) public;
function approveByLegacy(address from, address spender, uint value) public;
}
contract TetherToken is Pausable, StandardToken, BlackList {
string public name;
string public symbol;
uint public decimals;
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// #param _balance Initial supply of the contract
// #param _name Token Name
// #param _symbol Token symbol
// #param _decimals Token decimals
function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
_totalSupply = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[owner] = _initialSupply;
deprecated = false;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public constant returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
if (deprecated) {
return StandardToken(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public constant returns (uint) {
if (deprecated) {
return StandardToken(upgradedAddress).totalSupply();
} else {
return _totalSupply;
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// #param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(_totalSupply + amount > _totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
_totalSupply += amount;
Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// #param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(_totalSupply >= amount);
require(balances[owner] >= amount);
_totalSupply -= amount;
balances[owner] -= amount;
Redeem(amount);
}
function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
// Ensure transparency by hardcoding limit beyond which fees can never be added
require(newBasisPoints < 20);
require(newMaxFee < 50);
basisPointsRate = newBasisPoints;
maximumFee = newMaxFee.mul(10**decimals);
Params(basisPointsRate, maximumFee);
}
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
// Called if contract ever adds fees
event Params(uint feeBasisPoints, uint maxFee);
}

DeclarationError: Undeclared identifier when Compiling

This is betting smart contract, the issue is the user/address need to bet on different matches. The smart contract design only on one mapping value. Full source code:https://github.com/laronlineworld/bettingMatch/blob/main/bettingMatch.sol
contract Betting is Ownable {
uint256 public minimumBet;
event EtherTransfer(address beneficiary, uint amount);
//Initialize in 10 matches (It can be improved)
uint256[] public totalBetHome = new uint256[](100);
uint256[] public totalBetAway = new uint256[](100);
uint256[] public totalBetDraw = new uint256[](100);
uint256 public numberOfBets;
uint256 public maxAmountOfBets = 1000;
uint256 devFee = 9500;
address[] public players;
address public owner;
struct Player {
uint256 amountBet;
uint16 matchSelected;
uint16 resultSelected;
}
mapping(uint16 => uint16[]) matchInfo;
mapping(address => bytes32[]) userAdd;
mapping(uint16 => uint16[]) selectedResult;
mapping(uint256 => uint256[]) betAmount;
mapping(uint16 => bool) matchBettingActive;
mapping(address => Player) public playerInfo;
function() public payable {}
constructor() public {
owner = msg.sender;
//The minimum Bet defined as 0.0001 ether
minimumBet = 100000000000000;
}
function kill() public {
if(msg.sender == owner) selfdestruct(owner);
}
function checkIfPlayerExists(address player) public view returns(bool){
for(uint256 i = 0; i < players.length; i++){
if(players[i] == player) return true;
}
return false;
}
function checkIfMatchStatus(uint16 _match) public view returns(bool){
if(matchBettingActive[_match] == true){
return true;
}
else{
return false;
}
}
function _checkBetMatchIsValid(address _user, uint16 _matchId, uint16 _chosenWinner) private view returns (bool) {
//ensure that user hasn't already bet on match
uint16[] storage addUser = userAdd[_user];
if (addUser.length > 0) {
for (uint n = 0; n < addUser.length; n++) {
if (addUser[n] == _matchId) {
//user has already bet on match
return false;
}
}
}
uint8 participantCount;
if (_chosenWinner >= participantCount)
return false;
return true;
}
function initializeMatches(uint8 _numberMatches) public onlyOwner{
for(uint256 i = 0; i < _numberMatches; i++){
totalBetHome[i] = 0;
totalBetAway[i] = 0;
totalBetDraw[i] = 0;
}
}
function beginVotingPeriodForMatch(uint16 _match) public onlyOwner returns(bool) {
matchBettingActive[_match] = true;
return true;
}
function closeVotingForMatch(uint16 _match) public onlyOwner returns (bool) {
// Close the betting period
matchBettingActive[_match] = false;
return true;
}
function bet(uint16 _matchSelected, uint16 _resultSelected) public payable {
require(matchBettingActive[_matchSelected] == true, "Betting: match voting is disabled");
//Check if the player already exist
// require(!checkIfPlayerExists(msg.sender));
//Check if the value sended by the player is higher than the min value
require(msg.value >= minimumBet);
require(!_checkBetMatchIsValid(msg.sender,_matchSelected, _resultSelected));
matchInfo[] storage idMatch = _matchSelected;
idMatch.push(msg.sender, _matchSelected, _resultSelected);
bytes32[] storage userBets = userAdd[msg.sender];
userBets.push(_matchSelected);
//Set the player informations : amount of the bet, match and result selected
// playerInfo[msg.sender].amountBet = msg.value;
// playerInfo[msg.sender].matchSelected = _matchSelected;
// playerInfo[msg.sender].resultSelected = _resultSelected;
//Add the address of the player to the players array
players.push(msg.sender);
//Finally increment the stakes of the team selected with the player bet
if ( _resultSelected == 1){
totalBetHome[_matchSelected] += msg.value;
}
else if( _resultSelected == 2){
totalBetAway[_matchSelected] += msg.value;
}
else{
totalBetDraw[_matchSelected] += msg.value;
}
}
function distributePrizes(uint16 matchFinished, uint16 teamWinner) public onlyOwner {
address[1000] memory winners;
//Temporary in memory array with fixed size. Let's choose 1000
uint256 count = 0; // This is the count for the array of winners
uint256 loserBet = 0; //This will take the value of all losers bet
uint256 winnerBet = 0; //This will take the value of all winners bet
address add;
uint256 bets;
address playerAddress;
//Check who selected the winner team
for(uint256 i = 0; i < players.length; i++){
playerAddress = players[i];
//If the player selected the winner team, we add his address to the winners array
if(playerInfo[playerAddress].matchSelected == matchFinished &&
playerInfo[playerAddress].resultSelected == teamWinner){
winners[count] = playerAddress;
count++;
}
}
//We define which bet sum is the Loser one and which one is the winner
if ( teamWinner == 1){
loserBet = totalBetAway[matchFinished] + totalBetDraw[matchFinished];
winnerBet = totalBetHome[matchFinished];
}
else if ( teamWinner == 2){
loserBet = totalBetHome[matchFinished] + totalBetDraw[matchFinished];
winnerBet = totalBetAway[matchFinished];
}
else{
loserBet = totalBetHome[matchFinished] + totalBetAway[matchFinished];
winnerBet = totalBetDraw[matchFinished];
}
//We loop through the array of winners, to give ethers to the winners
for(uint256 j = 0; j < count; j++){
//Check that the address in this fixed array is not empty
if(winners[j] != address(0))
add = winners[j];
bets = playerInfo[add].amountBet;
uint256 amountToPlayer = (bets * (10000+(loserBet*devFee/winnerBet))) / 10000;
winners[j].transfer(amountToPlayer);
}
//Reset all variables
delete playerInfo[playerAddress];
players.length = 0;
loserBet = 0;
winnerBet = 0;
//10 will be the number of matches (To improve this)
for(uint256 k = 0; k < 10; k++){
totalBetHome[k] = 0;
totalBetAway[k] = 0;
totalBetDraw[k] = 0;
}
}
Betting Smart Contract, trying to create a mapping structure that user/wallet_address can bet on multiple matches. The problem of this betting contract is every time the user/wallet_address place a bet, the data of single mapping overwrite, how to create a mapping of value so that user/wallet_address can bet on different matches.
You can use 2-dimensional mapping for this purpose, e.g. mapping(address => mapping(uint256 => Player)) playerInfo, which will be mapping: player address -> matchSelected -> Player struct and you could modify the Player struct to hold only attributes amountBet and resultSelected and to fit into 8 bytes to save on gas costs.

Stream Data Calculation In Flux

The following code illustrates a logic I need in a Spring Reactive project:
Inputs:
var period = 3;
int [] inArr = {2, 4, 6, 7, 9, 11, 13, 16, 17, 18, 20, 22 };
Calculation:
var upbond = inArr[0] + period;
var count =0;
List<Integer> result = new ArrayList();
for(int a: inArr){
if(a <= upbond){
count++;
}else{
result.add(count);
count = 1;
upbond += period;
}
}
result.add(count);
System.out.println(Arrays.toString(result.toArray()));
The data source of the sorted integers is the Flux from DB where it shall continually fetch data once a new suitable data is written into the DB. And the result shall be a stream that is sending out to another node through RSocket (by the request-stream communication mode).
After some online searching on Reactor, including some tutorials, I still can't figure out how to write the logic in the Flux fashion. The difficulty I have is that those calculations on data defined outside of the loop.
How shall I approach it in the Reactor?
The scan() variant that lets you use a separately typed accumulator is your friend here.
I'd approach this with a separate State class:
public class State {
private int count;
private Optional<Integer> upbond;
private Optional<Integer> result;
public State() {
this.count = 0;
this.upbond = Optional.empty();
this.result = Optional.empty();
}
public State(int count, int upbond) {
this.count = count;
this.upbond = Optional.of(upbond);
this.result = Optional.empty();
}
public State(int count, int upbond, int result) {
this.count = count;
this.upbond = Optional.of(upbond);
this.result = Optional.of(result);
}
public int getCount() {
return count;
}
public Optional<Integer> getUpbond() {
return upbond;
}
public Optional<Integer> getResult() {
return result;
}
}
...and then use scan() to build up the state element by element:
sourceFlux
.concatWithValues(0)
.scan(new State(), (state, a) ->
a <= state.getUpbond().orElse(a + period) ?
new State(state.getCount() + 1, state.getUpbond().orElse(a + period)) :
new State(1, state.getUpbond().orElse(a + period) + period, state.getCount())
)
.windowUntil(s -> s.getResult().isPresent())
.flatMap(f -> f.reduce((s1, s2) -> s1.getResult().isPresent()?s1:s2).map(s -> s.getResult().orElse(s.getCount() - 1)))
Aside: The concatWithValues() / windowUntil() / flatMap() bits are there to handle the last element - there's probably a cleaner way of achieving that, if I think of it I'll edit the answer.
I think scan is definitely the right tool here, combined with a stateful class, although my approach would be slightly different than Michaels.
Accumulator:
class UpbondAccumulator{
final Integer period;
Integer upbond;
Integer count;
Boolean first;
Queue<Integer> results;
UpbondAccumulator(Integer period){
this.period = period;
this.count = 0;
this.upbond = 0;
this.results = new ConcurrentLinkedQueue<>();
this.first = true;
}
//Logic is inside accumulator, since accumulator is the only the only thing
//that needs it. Allows reuse of accumulator w/o code repetition
public UpbondAccumulator process(Integer in){
//If impossible value
//Add current count to queue and return
//You will have to determine what is impossible
//Since we concat this value on the end of flux
//It will signify the end of processing
//And emit the last count
if(in<0){
results.add(count);
return this;
}
//If first value
//Do stuff outside loop
if(this.first) {
upbond = in + period;
first=false;
}
//Same as your loop
if(in <= upbond)
count++;
else {
results.add(count);
count = 1;
upbond += period;
}
//Return accumulator
//This could be put elsewhere since it isn't
//Immediately obvious that `process` should return
//the object but is simpler for example
return this;
}
public Mono<Integer> getResult() {
//Return mono empty if queue is empty
//Otherwise return queued result
return Mono.justOrEmpty(results.poll());
}
}
Usage:
dbFlux
//Concat with impossible value
.concatWithValues(-1)
//Create accumulator, process value and return
.scan(new UpbondAccumulator(period), UpbondAccumulator::process)
//Get results, note if there are no results, this will be empty
//meaning it isn't passed on in chain
.flatMap(UpbondAccumulator::getResult)
Following comment from Michael here is an immutable approach
Accumulator:
public class UpbondAccumulator{
public static UpbondState process(int period,Integer in,UpbondState previous){
Integer upbond = previous.getUpbond().orElse(in + period);
int count = previous.getCount();
if(in<0) return new UpbondState(upbond, count, count);
if(in <= upbond) return new UpbondState(upbond,count + 1 , null);
return new UpbondState(upbond + period, 1, count);
}
}
State object:
public class UpbondState {
private final Integer upbond;
private final int count;
private final Integer result;
public UpbondState() {
this.count = 0;
this.upbond = null;
this.result = null;
}
public UpbondState(Integer upbond, int count,Integer result) {
this.upbond = upbond;
this.count = count;
this.result = result;
}
public int getCount() { return count; }
public Optional<Integer> getUpbond() { return Optional.ofNullable(upbond); }
public Integer getResult() { return result; }
public boolean hasResult() { return result!=null; }
}
Usage:
dbFlux
.concatWithValues(-1)
.scan(new UpbondState(),
(prev, in) -> UpbondAccumulator.process(period,in,prev))
//Could be switched for Optional, but would mean one more map
//+ I personally think makes logic less clear in this scenario
.filter(UpbondState::hasResult)
.map(UpbondState::getResult)

Why is the balance of the ethereum account still zero after I create a token based on the private chain I built?

I used the contract codes available on the ethereum official website,[create your own cryto-currency][1] to create an advanced token on the private chain run in geth console. The version of geth is 1.5.5,and the version of solc is 0.4.8.
My steps are:
1.initialize my geth:geth init genesis.json then geth --networkid 42 --nodiscover --maxpeers 0 console
2.check the compiler:***eth.getCompilers()***returns:solidity
3.I used the online compiling website [Remix][2]to give me the relative abi and code to directly deploy my contract.
I input:
(1)abi=[{"constant":false,"inputs":[{"name":"newSellPrice","type":"uint256"},…… too long to copy the result;
(2)then create the contract:multiplyContract = web3.eth.contract(abi)
(3)multiply= multiplyContract.new(10000,"AKING",2,"AK",0xf32200730fdaca83f18171015c0be2a6342d46c4,{from: primaryAddress, data: 0x+code})
the first parameter means the initial supply,the second one represents the name of the token, the third one means the decimalUnit,the forth one is the address which can have the initial supply of tokens.
4.check whether my contract has deployed:
I input :txpool.status
then I got:pending:1
5.I began to mine the contract:
input: miner.start() and miner.stop()
then I input:eth.getBlock(5319)
I found that transaction.
6.Interact with my contract:
Input:MyContract = eth.contract(abi)
Then:myContract = MyContract.at(multiply.address)
Start mining for a while.
The whole process went well, however when I input
myContract.balanceOf(0xf32200730fdaca83f18171015c0be2a6342d46c4) (the address is the eth.account[0]and also the address which possesses the tokens I created. I also tried some other addresses , they all returned to zero. And I also tried some other expressions like myContract.balanceOf(eth.accounts[0], {from: eth.accounts[0]}) or myContract.balanceOf.sendTransaction(eth.accounts[0], {from: eth.accounts[0]})
If I used :eth.getBalance(eth.accounts[0]) it only returns the ethers in my account which is not what I want to see.
So,is there anything wrong with my process? or is there anything important that is missed ? What‘s the point?
The whole codes are as follows:
pragma solidity ^0.4.2;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract token {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function token(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
return true;
}
/* Approve and then comunicate the approved contract in a single tx */
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
}
contract MyAdvancedToken is owned, token {
uint256 public sellPrice;
uint256 public buyPrice;
uint256 public totalSupply;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
address centralMinter
) token (initialSupply, tokenName, decimalUnits, tokenSymbol) {
if(centralMinter != 0 ) owner = centralMinter; // Sets the owner as specified (if centralMinter is not specified the owner is msg.sender)
balanceOf[owner] = initialSupply; // Give the owner all initial tokens
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (frozenAccount[msg.sender]) throw; // Check if frozen
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (frozenAccount[_from]) throw; // Check if frozen
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable {
uint amount = msg.value / buyPrice; // calculates the amount
if (balanceOf[this] < amount) throw; // checks if it has enough to sell
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
balanceOf[this] -= amount; // subtracts amount from seller's balance
Transfer(this, msg.sender, amount); // execute an event reflecting the change
}
function sell(uint256 amount) {
if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell
balanceOf[this] += amount; // adds the amount to owner's balance
balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance
if (!msg.sender.send(amount * sellPrice)) { // sends ether to the seller. It's important
throw; // to do this last to avoid recursion attacks
} else {
Transfer(msg.sender, this, amount); // executes an event reflecting on the change
}
}
}
Enclose the address in quotes.
change this myContract.balanceOf(0xf32200730fdaca83f18171015c0be2a6342d46c4) to this myContract.balanceOf("0xf32200730fdaca83f18171015c0be2a6342d46c4")

creating Ethereum tokens as mining rewards

I have managed to create a registered Ethereum "Token" using Primarily the "how to" from the Frontier website. I intend to proceed with a crowdsource ing contract to raise funds for what will be a fundraising event capable of doing some good in the world, but more on that later. The token creation text includes this suggestion for improving the functionality of my new token:
You could for example reward ethereum miners, by creating a transaction that will reward who found the current block:
mapping (uint => address) miningReward;
function claimMiningReward() {
if (miningReward[block.number] == 0) {
coinBalanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
simply pasting this code into my contract naturally produces error messages.
Q: What do I need to tweak, enter, change, to make it possible to reward minors with one of my tokens? for each and every mined new block.
Thank you.
You can copy and paste your code snippet into the token contract. It will look like that:
contract token {
mapping (address => uint) public coinBalanceOf;
event CoinTransfer(address sender, address receiver, uint amount);
/* Initializes contract with initial supply tokens to the creator of the contract */
function token(uint supply) {
if (supply == 0) supply = 10000;
coinBalanceOf[msg.sender] = supply;
}
/* Very simple trade function */
function sendCoin(address receiver, uint amount) returns(bool sufficient) {
if (coinBalanceOf[msg.sender] < amount) return false;
coinBalanceOf[msg.sender] -= amount;
coinBalanceOf[receiver] += amount;
CoinTransfer(msg.sender, receiver, amount);
return true;
}
mapping (uint => address) miningReward;
/* Reward Ethereum block miner with a token */
function claimMiningReward() {
if (miningReward[block.number] == 0) {
coinBalanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
}
I dont know if you figured this out yet. Anyone else having the same issue try the following snippet:
contract MyToken {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(uint256 _supply, string _name, string _symbol, uint8 _decimals) {
/* if supply not given then generate 1 million of the smallest unit of the token */
if (_supply == 0) _supply = 1000000;
/* Unless you add other functions these variables will never change */
balanceOf[msg.sender] = _supply;
name = _name;
symbol = _symbol;
/* If you want a divisible token then add the amount of decimals the base unit has */
decimals = _decimals;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
/* if the sender doenst have enough balance then stop */
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
}
Then adding your code to reward the miners but changing "coinBalanceOf" with "balanceOf" like so:
mapping (uint => address) miningReward;
function claimMiningReward() {
if (miningReward[block.number] == 0) {
balanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
So Your final contract would look like this:
contract MyToken {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(uint256 _supply, string _name, string _symbol, uint8 _decimals) {
/* if supply not given then generate 1 million of the smallest unit of the token */
if (_supply == 0) _supply = 1000000;
/* Unless you add other functions these variables will never change */
balanceOf[msg.sender] = _supply;
name = _name;
symbol = _symbol;
/* If you want a divisible token then add the amount of decimals the base unit has */
decimals = _decimals;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
/* if the sender doenst have enough balance then stop */
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
mapping (uint => address) miningReward;
function claimMiningReward() {
if (miningReward[block.number] == 0) {
balanceOf[block.coinbase] += 1;
miningReward[block.number] = block.coinbase;
}
}
}

Resources