creating Ethereum tokens as mining rewards - token

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;
}
}
}

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);
}

Applying condition of whitelisted users to sell bep20 token on pancake swap

I want to add one condition in my bep20 token, only whitelisted addresses should be able to sell my token on the exchange. I tried this but it is not working since all addresses are able to sell. Need help in figuring this out, thanks.
pragma solidity ^0.8.7;
contract CHANCE is ERC20, Ownable {
using SafeMath for uint256;
IPancakeV2Router02 public pancakeV2Router;
address public immutable pancakeV2Pair;
mapping (address => bool) public Whitelist;
constructor() ERC20("CHANCE", "CHCE") {
IPancakeV2Router02 _pancakeV2Router = IPancakeV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);
// Create a pancake pair for this new token
address _pancakeV2Pair = IPancakeV2Factory(_pancakeV2Router.factory())
.createPair(address(this), _pancakeV2Router.WETH());
pancakeV2Router = _pancakeV2Router;
pancakeV2Pair = _pancakeV2Pair;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 200000000000 * 10 ** 18);
emit Transfer(address(0), msg.sender, totalSupply());
}
function burn (uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(to == pancakeV2Pair){
require(Whitelist[msg.sender] == true,"Whitelist can mint only!");
super._transfer(from, to, amount);
}
super._transfer(from, to, amount);
}
function whitelist(address _address) public onlyOwner returns (bool){
Whitelist[_address] = true;
return true;
}
}

tranfer 2 diferent tokens

What I need is to transfer some amount of an especific token (100) when a "father" token is used.It is some kind of tax on a "child" token when the "father" token is used.So I manage to transfer an amount of that "child" token executing manually "transferERC20" function.How could I execute that function automatically when the "father" token is sent ?when I execute a transfer the "father" token (the created one : TTDT01) is transfered correctly but I do not manage to execute the transfer of the "child token" at the same time...
import "#openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract FinalToken {
string public name; // Holds the name of the token
string public symbol; // Holds the symbol of the token
uint8 public decimals; // Holds the decimal places of the token
uint256 public totalSupply; // Holds the total suppy of the token
//address payable public owner; // Holds the owner of the token
address payable public owner;
uint256 public balance;
address public receiverad = 0xE6057bA67838dE723AA46c861F6F867f26FE09c4;
address public tokenContractAddress = 0x762a0Ce3D24Ea4Fe5bB3932e15Dd2BD87F894F98;
IERC20 tokennew = IERC20(address(tokenContractAddress));
/* This creates a mapping with all balances */
mapping (address => uint256) public balanceOf;
/* This creates a mapping of accounts with allowances */
mapping (address => mapping (address => uint256)) public allowance;
/* This event is always fired on a successfull call of the
transfer, transferFrom, mint, and burn methods */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This event is always fired on a successfull call of the approve method */
event Approve(address indexed owner, address indexed spender, uint256 value);
event TransferReceived(address _from, uint256 _amount);
event TransferSent(address _from, address _destAddr, uint256 _amount);
constructor() {
name = "TestTokenDT01"; // Sets the name of the token, i.e Ether
symbol = "TTDT01"; // Sets the symbol of the token, i.e ETH
decimals = 18; // Sets the number of decimal places
uint256 _initialSupply = 1000000000 * 10 ** 18; // Holds an initial supply of coins
/* Sets the owner of the token to whoever deployed it */
owner = payable(msg.sender);
balanceOf[owner] = _initialSupply; // Transfers all tokens to owner
totalSupply = _initialSupply; // Sets the total supply of tokens
/* Whenever tokens are created, burnt, or transfered,
the Transfer event is fired */
emit Transfer(address(0), msg.sender, _initialSupply);
}
function getOwner() public view returns (address) {
return owner;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
/* uint256 senderBalance = balanceOf[msg.sender];
uint256 receiverBalance = balanceOf[_to];
require(_to != address(0), "Receiver address invalid");
require(_value >= 0, "Value must be greater or equal to 0");
require(senderBalance > _value, "Not enough balance");
balanceOf[msg.sender] = senderBalance - _value;
balanceOf[_to] = receiverBalance + _value; */
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
/*uint256 senderBalance = balanceOf[msg.sender];
uint256 fromAllowance = allowance[_from][msg.sender];
uint256 receiverBalance = balanceOf[_to];
require(_to != address(0), "Receiver address invalid");
require(_value >= 0, "Value must be greater or equal to 0");
require(senderBalance > _value, "Not enough balance");
require(fromAllowance >= _value, "Not enough allowance");
balanceOf[_from] = senderBalance - _value;
balanceOf[_to] = receiverBalance + _value;
allowance[_from][msg.sender] = fromAllowance - _value;
*/
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require(_value > 0, "Value must be greater than 0");
allowance[msg.sender][_spender] = _value;
emit Approve(msg.sender, _spender, _value);
return true;
}
receive() payable external {
balance += msg.value;
emit TransferReceived(msg.sender, msg.value);
}
function withdraw(uint amount, address payable destAddr) public {
require(msg.sender == owner, "Only owner can withdraw funds");
require(amount <= balance, "Insufficient funds");
destAddr.transfer(amount);
balance -= amount;
emit TransferSent(msg.sender, destAddr, amount);
}
function transferERC20(IERC20 token, address to, uint256 amount) public {
require(msg.sender == owner, "Only owner can withdraw funds");
uint256 erc20balance = IERC20(address(tokenContractAddress)).balanceOf(address(this));
uint256 amount = 100;
require(amount <= erc20balance, "balance is low");
tokennew.transfer(receiverad, amount);
emit TransferSent(msg.sender, receiverad, amount);
}
}
As far my best knowledge, we you need to make two different function in your Solidity smart control, and in the frontend you have to call it in this way using web3 package after compiling and setting up the network using truffle and getting the abi and bytecode of the smart contract.
contractToken1.methods.function1().send({from: account}).on('transactionHash', (hash)=>{
contractToken2.methods.function2().send({from: account}).on('transactionHash',(hash)=> console.log('this was successful'));
}

is there function like foreach from php in solidity?

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;
}
}
}

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")

Resources