why can't transfer token in the GetReward function in eqzip crowdsale? - ethereum

The following is my contract after I deploy eqcoin contract and eqzip contract I have tried use account2 send ether to eqzip contract then the beneficiary can get the ether but when the crowdsale finished. I tried use account2 execute the GetReward function to get the reward but after I execute the GetReward function account2 didn't get the token why?
Could you please review my source code and tell me what's wrong with my contract?Thank you!
Eqcoin contract:
pragma solidity ^0.4.21;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract Eqcoin {
// Public variables of the token
// string public constant whitePaperForEqcoin = "The total supply of eqcoin is 100000 which corresponds to 1% of Eqzip stock,\
// 0.01% of Eqcoin stock and 10% of Lostk stock...\
// The decimals of Eqcoin is 18...\
// ";
string public name = "eqcoin";
string public symbol = "eqc";
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// The owner's address
// address private owner;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
// The following is test stub comment when release
// string public ownerAddress;
event Log(string log, address _address, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function Eqcoin(uint256 initialSupply,
string tokenName,
string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
// owner = msg.sender; // Set the owner
// ownerAddress = toAsciiString(msg.sender);
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
emit Log("_transfer", _to, _value);
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* #param _to The address of the recipient
* #param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
emit Log("transfer", msg.sender, _value);
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* #param _from The address of the sender
* #param _to The address of the recipient
* #param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* #param _spender The address authorized to spend
* #param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
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
*/
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;
}
}
// /**
// * Destroy tokens
// *
// * Remove `_value` tokens from the system irreversibly
// *
// * #param _value the amount of money to burn
// */
// function burn(uint256 _value) public returns (bool success) {
// if(balanceOf[msg.sender] < _value){
// return;
// }
// balanceOf[msg.sender] -= _value; // Subtract from the sender
// if(msg.sender == owner){
// totalSupply -= _value; // Updates totalSupply
// }
// emit Burn(msg.sender, _value);
// return true;
// }
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* #param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* #param _from the address of the sender
* #param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
function getTotalSupply() public constant returns (uint256 _totalSupply){
return totalSupply;
}
// function getOwner() public constant returns(address _address){
// return owner;
// }
// the following is test stub comment when release
// function toAsciiString(address x) internal pure returns (string) {
// bytes memory s = new bytes(40);
// for (uint i = 0; i < 20; i++) {
// byte b = byte(uint8(uint(x) / (2**(8*(19 - i)))));
// byte hi = byte(uint8(b) / 16);
// byte lo = byte(uint8(b) - 16 * uint8(hi));
// s[2*i] = char(hi);
// s[2*i+1] = char(lo);
// }
// return string(s);
// }
// function char(byte b) internal pure returns (byte c) {
// if (b < 10) return byte(uint8(b) + 0x30);
// else return byte(uint8(b) + 0x57);
// }
}
Eqzip crowdsale contract:
pragma solidity ^0.4.21;
interface token {
function transfer(address receiver, uint amount) external;
function getTotalSupply() external returns (uint256 _totalSupply);
// function getOwner() external returns(address _address);
}
contract EqzipCrowdsale {
string public constant whitePaperForEqzip = "The total supply of eqcoin is 100000 which corresponds to: \n\
1. 1% of Eqzip stock. \n\
2. 0.01% of Eqcoin stock. \n\
3. 10% of Lostk stock. \n\
4. Get the EQC corresponding to the price of eqcoin ico. \n\
5. If the Ether from one person's investment is greater than or equal to 333, \
hope life offers one cloned resurrection place (only 3 places, take the top 3). \n\
6. Hired Hope Media to provide Growth Hacker, product design, and business architecture design for Ethereum. \n\
7. Prior to joining eqzip work, under the same conditions to participate in the next round of financing eqzip. \n\
The decimals of Eqcoin is 18... \n\
owner: Xun Wang \n\
wechat: nju20006 \n\
email: 10509759#qq.com \n\
URL: www.eqzip.com www.eqzip.cn www.lostk.com www.lostk.cn github.com/eqzip/eqcoin github.com/eqzip/lostk \n\
";
// The owner's address
address public owner;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(string reason, uint256 value);
uint public fundingGoal;
uint public amountRaised;
uint public funderNumbers;
uint public deadline;
struct BalanceOfFounder{
uint256 _ether;
bool isSentToken;
}
// This creates an array with all balances of eqcoin, ether and if have sent token
mapping(address => BalanceOfFounder) public balanceOfEther;
token public tokenReward;
address public beneficiary;
bool burnedUnsaleToken = false;
event GoalReached(address recipient, uint totalAmountRaised);
// Milestone
string public milestone;
// Total supply
uint256 public totalSupply;
event Log(string log, address _address, uint256 value);
/**
* Constructor function
*
* Setup the owner
*/
function EqzipCrowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
address addressOfTokenUsedAsReward
) public {
// For Eqzip crowdsale
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
tokenReward = token(addressOfTokenUsedAsReward);
totalSupply = tokenReward.getTotalSupply();
owner = msg.sender;
emit Log("cons", owner, 0);
// emit Log("cons", tokenReward.getOwner(), 1);
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () beforeDeadline public payable {
balanceOfEther[msg.sender]._ether += msg.value;
balanceOfEther[msg.sender].isSentToken = false;
amountRaised += msg.value;
beneficiary.transfer(msg.value);
emit GoalReached(msg.sender, msg.value);
}
modifier afterDeadline() { if (now > deadline) _; }
modifier beforeDeadline() { if (now <= deadline) _; }
function getReward() afterDeadline public {
emit Log("getReward", owner, 0);
// require(!balanceOfEther[msg.sender].isSentToken);
// save investment value
// uint256 amount = balanceOfEther[msg.sender]._ether;
emit Log("getReward after require", msg.sender, 1);
// because have sent the token to founder so set isSentToken to true to void get multiply reward
balanceOfEther[msg.sender].isSentToken = true;
// if amount raised less than founding goal then burn un sold token and reduce the total supply
// if((amountRaised < fundingGoal) && !burnedUnsaleToken){
// burnedUnsaleToken = true;
// // totalSupply = (totalSupply*amountRaised)/fundingGoal;
// // balanceOf[owner] = totalSupply;
// // emit Burn("Token not sold out all the sold value is", totalSupply);
// }
if(amountRaised < fundingGoal && !burnedUnsaleToken){
burnedUnsaleToken = true;
totalSupply = (totalSupply*amountRaised)/fundingGoal;
emit Burn("Token not sold out all the sold value is", totalSupply);
}
emit Log("getReward tokenReward.transfer", msg.sender, 2);
tokenReward.transfer(msg.sender, (balanceOfEther[msg.sender]._ether*totalSupply)/amountRaised);
emit Log("getReward after tokenReward.transfer", msg.sender, 3);
// _transfer(owner, msg.sender, (amount*totalSupply)/amountRaised);
}
function getBalanceOfEther(address _address) public payable returns(uint256) {
emit Log("getBalanceOfEther", _address, balanceOfEther[_address]._ether);
return balanceOfEther[_address]._ether;
}
function updateMilestone(string str) public {
emit Log("updateMilestone", msg.sender, 0);
milestone = strConcat(milestone, "\n", toAsciiString(msg.sender), "\n", str);
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function toAsciiString(address x) internal pure returns (string) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(byte b) internal pure returns (byte c) {
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
}

Related

How to add a uint T in constructor that will be a time constant inside my smart contract?

I need a time constant to calculate timestamps for deposit, withdrawal, and reward sub-pools. this time constant called T will start from contract deployment and will not be specific to one address/user. I.e rewards(R) are divided into 3 sub-pools: R1 = 20% available after 2T has passed since contract deployment, R2 = 30% available after 3T has passed since contract deployment, R3= 50% available after 4T has passed since contract deployment. I need this variable to be in minutes, for example, sender inputs 3 I want the time between each timestamp to be 3, like deposit in the first T, withdrawal after 3T. How to set it in minutes?
Here is the state variable
uint256 public T;
Here is the constructor
constructor(address stakingToken, address rewardsToken, uint256 timeConstant) {
s_stakingToken = IERC20(stakingToken);
s_rewardsToken = IERC20(rewardsToken);
initialTime = block.timestamp;
T = timeConstant;
}
My full code
error TransferFailed();
error NeedsMoreThanZero();
contract Staking is ReentrancyGuard {
IERC20 public s_rewardsToken;
IERC20 public s_stakingToken;
// This is the reward token per seco
nd
// Which will be multiplied by the tokens the user staked divided by the total
// This ensures a steady reward rate of the platform
// So the more users stake, the less for everyone who is staking.
uint256 public constant REWARD_RATE = 100;
uint256 public s_lastUpdateTime;
uint256 public s_rewardPerTokenStored;
//uint256 public constant T = 3;
uint256 public initialTime;
uint256 public T;
mapping(address => uint256) public s_userRewardPerTokenPaid;
mapping(address => uint256) public s_rewards;
uint256 private s_totalSupply;
mapping(address => uint256) public s_balances; // someones address => how much he staked
event Staked(address indexed user, uint256 indexed amount);
event WithdrewStake(address indexed user, uint256 indexed amount);
event RewardsClaimed(address indexed user, uint256 indexed amount);
constructor(address stakingToken, address rewardsToken, uint256 timeConstant) {
s_stakingToken = IERC20(stakingToken);
s_rewardsToken = IERC20(rewardsToken);
initialTime = block.timestamp;
T = timeConstant;
}
/**
* #notice How much reward a token gets based on how long it's been in and during which "snapshots"
*/
function rewardPerToken() public view returns (uint256) {
if (s_totalSupply == 0) {
return s_rewardPerTokenStored;
}
return
s_rewardPerTokenStored +
(((block.timestamp - s_lastUpdateTime) * REWARD_RATE * 1e18) / s_totalSupply);
}
/**
* #notice How much reward a user has earned
*/
function earned(address account) public view returns (uint256) {
uint256 nowTime = block.timestamp-initialTime;
require(nowTime > 2*T);
if (nowTime > 2*T && nowTime <= 3*T) {
return
((((s_balances[account] * (rewardPerToken() - s_userRewardPerTokenPaid[account])) /
1e18) + s_rewards[account]) / 5 );
} else if
(nowTime > 3*T && nowTime <= 4*T) {
return
((((s_balances[account] * (rewardPerToken() - s_userRewardPerTokenPaid[account])) /
1e18) + s_rewards[account]) / 2 );
} else {
return
(((s_balances[account] * (rewardPerToken() - s_userRewardPerTokenPaid[account])) /
1e18) + s_rewards[account]);
}
}
/**
* #notice Deposit tokens into this contract
* #param amount | How much to stake
*/
function stake(uint256 amount)
external
updateReward(msg.sender)
nonReentrant
moreThanZero(amount)
{
//from T0 to T deposit is available
uint256 nowTime = block.timestamp-initialTime; // time between deployment of contract and now.
require(nowTime < T);
s_totalSupply += amount;
// increasing how much they are staking for how much they staked each time.
s_balances[msg.sender] += amount;
emit Staked(msg.sender, amount);
// sending an amount of token from an address to this contract
bool success = s_stakingToken.transferFrom(msg.sender, address(this), amount);
// if not successfully sent, return an error.
// using the below code instead of "require(success, "Failed")" reduces gas fees, since it doesn't output a string.
if (!success) {
revert TransferFailed(); // revert resets everything done in a failed transaction.
}
}
/**
* #notice Withdraw tokens from this contract
* #param amount | How much to withdraw
*/
function withdraw(uint256 amount) external updateReward(msg.sender) nonReentrant {
// from 2T the user can reward his tokens
uint256 nowTime = block.timestamp-initialTime; // time between deployment of contract and now.
require(nowTime > 2* T);
s_totalSupply -= amount;
s_balances[msg.sender] -= amount;
emit WithdrewStake(msg.sender, amount);
// transfer: send tokens from contract back to msg.sender.
bool success = s_stakingToken.transfer(msg.sender, amount);
if (!success) {
revert TransferFailed(); // revert resets everything done in a failed transaction.
}
}
/**
* #notice User claims their tokens
*/
function claimReward() external updateReward(msg.sender) nonReentrant {
uint256 reward = s_rewards[msg.sender];
s_rewards[msg.sender] = 0;
emit RewardsClaimed(msg.sender, reward);
bool success = s_rewardsToken.transfer(msg.sender, reward);
if (!success) {
revert TransferFailed(); // revert resets everything done in a failed transaction.
}
}
/********************/
/* Modifiers Functions */
/********************/
modifier updateReward(address account) {
s_rewardPerTokenStored = rewardPerToken();
s_lastUpdateTime = block.timestamp;
s_rewards[account] = earned(account);
s_userRewardPerTokenPaid[account] = s_rewardPerTokenStored;
_;
}
modifier moreThanZero(uint256 amount) {
if (amount == 0) {
revert NeedsMoreThanZero();
}
_;
}
/********************/
/* Getter Functions */
/********************/
// Ideally, we'd have getter functions for all our s_ variables we want exposed, and set them all to private.
// But, for the purpose of this demo, we've left them public for simplicity.
function getStaked(address account) public view returns (uint256) {
return s_balances[account];
}
}
Firstly maintain a map for storing the time for each user. Then make functions like depositTimeSet , withdrawalTimeSet for storing different time for different user. While despositing update the variable and while withdraw check the time has exceed or not.
struct Users {
uint dipositTime;
uint withDrawTime;
uint lastDepositTime;
}
mapping(address => Users ) users;
function depositeTimeSet(uint t) {
users[msg.sender].dipositTime = t minutes;
withdrawalTimeSet(t);
}
function withdrawalTimeSet(uint t) {
users[msg.sender].withDrawTime = 3 * t minutes
}
function deposite() {
transferFrom(msg.sender,address(this));
depositeTimeSet(3); // considering sender send 3
users[msg.sender].lastDepositTime = now;
}
function withdraw() {
if(
now > users[msg.sender].lastDepositTime +
users[msg.sender].withDrawTime,"too early for withdraw
request"
)
transferFrom(address(this),msg.sender);
}
You can see THIS one might be helpful
You can see THIS resource for time unit in solidity

Cryptocurrency - parser error on Smart Contact final line?

I have been working on a smart contract for a cryptocurrency over the past few hours and was getting ready to compile it. But when it was time to compile it, I got a error from Solidity stating: " ParserError: Expected pragma, import directive or contract/interface/library definition." It's on the final line, and I've checked the whole code multiple times to see no error. Any help would be great. Code is below:
pragma solidity ^0.4.21;
// File: zepplin-solidity/contracts/ownership/Ownable.sol
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
// #dev The Ownable constructor sets the original 'owner' of the contract to the sender
// account.
function Ownable() public {
owner = msg.sender;
}
// if any other account besides owner
modifier onlyOwner() {
requir(msg.sender == owner);
_;
}
// to transfer ownership in case of event
function transferOwnership(address newOwner) public onlyOwner
{
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// Safemath protocol
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) {
// assrt(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(unit256 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;
}
}
// Smart contract title (ERC20)
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer (address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(addres from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event approval(address indexed owner, address indexed spender, uint256 value);
}
contract HepburnA is ERC20, Ownable {
using SafeMath for uint256;
// the controller of minting and destroying tokens
address public hepburnDevmoon =
0x471E918a75A99038856eF9754368Eb1b5D15f9D5;
// the controller of approving of minting and withdraw tokens
address public hepburnCommunitymoon =
0x0554c3CF2315FB98181d1FEBfaf083cDf68Fa145;
struct TokensWithLock{
uint256 value;
uint256 blockNumber;
}
//Balances (shared with ERC20Basic replicant)
mapping(address => uint256) balances;
//When token numbers is less than incoming block
mapping(address => TokenswithLock) lockTokens;
mapping(address => mapping (address => uint256)) allowed;
// Token Cap
uint256 public totalSupplyCap = 1e11;
// Token Info
string public name = "Hepburn A";
string public symbol = "AUYHA";
uint8 public decimals = 18;
bool public mintingFinished = false;
// the block number when deploy
uint256 public deployBlockNumber = getCurrentBlockNumber();
// the min threshold of lock time
uint256 public constant TIMETHRESHOLD = 9720;
// the time when mintTokensWithinTime can be called
uint256 public constant MINTTIME = 291600;
// the lock time of minted tokens
uint256 public durationOfLock = 9720;
// True if transfers are allowed
bool public transferable = false;
// True if the transferable can be change
bool public canSetTransferable = true;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier only(address _address) {
require(msg.sender == _address);
_;
}
modifier nonZeroAddress(address _address) {
require(_address != address(0));
_;
}
modifier canTransfer() {
require(transferable == true);
}
event SetDurationOfLock(address indexed _caller);
event ApproveMintTokens(address indexed _owner, uint256 _amount);
event WithdrawMintTokens(address indexed _owner, uint256 _amount);
event MintTokens(address indexed _owner, uint256 _amount);
event BurnTokens(address indexed _owner, uint256 _amount);
event MintFinished(address indexed _caller);
event setTransferable(address indexed _address, bool _transferable);
event SethepburnDevmoon(address indexed _old, address indexed _new);
event DisableSetTransferable(ddress indexed _address, bool _canSetTransferable);
function transfer(address _to, uint256 _value) canTransfer 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);
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];
}
/**
* #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) canTransfer 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);
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) canTransfer public returns (bool) {
allowed[msg.sender][_spender] = _value;
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];
}
/**
* 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
*/
function increaseApproval(address _spender, uint256 _addedValue) canTransfer public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue) canTransfer public returns (bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* #dev Enables token holders to transfer their tokens freely if true
* #param _transferable True if transfers are allowed
*/
function setTransferable(bool _transferable) only(hepburnDevmoon) public {
require(canSetTransferable == true);
transferable = _transferable;
SetTransferable(msg.sender, _transferable);
}
/**
* #dev disable the canSetTransferable
*/
function disableSetTransferable() only(hepburnDevmoon) public {
transferable = true;
canSetTransferable = false;
DisableSetTransferable(msg.sender, false);
}
/**
* #dev Set the hepburnDevmoon
* #param _hepburnDevmoon The new hepburnDevmoon
*/
function SethepburnDevmoon(address _hepburnDevmoon) only(hepburnDevmoon) nonZeroAddress(_hepburnDevmoon) public {
hepburnDevmoon = _hepburnDevmoon;
SethepburnDevmoon(msg.sender, _hepburnDevmoon);
}
/**
* #dev Set the hepburnCommunitymoon
* #param _hepburnCommunitymoon The new hepburnCommunitymoon
*/
function sethepburnCommunitymoon(address _hepburnCommunitymoon) only(hepburnCommunitymoon) nonZeroAddress(_hepburnCommunitymoon) public {
hepburnCommunitymoon = _hepburnCommunitymoon;
sethepburnCommunitymoon(msg.sender, _hepburnCommunitymoon);
}
/**
* #dev Set the duration of lock of tokens approved of minting
* #param _durationOfLock the new duration of lock
*/
function setDurationOfLock(uint256 _durationOfLock) canMint only(hepburnCommunitymoon) public {
require(_durationOfLock >= TIMETHRESHOLD);
durationOfLock = _durationOfLock;
SetDurationOfLock(msg.sender);
}
/**
* #dev Get the quantity of locked tokens
* #param _owner The address of locked tokens
* #return the quantity and the lock time of locked tokens
*/
function getLockTokens(address _owner) nonZeroAddress(_owner) view public returns (uint256 value, uint256 blockNumber) {
return (lockTokens[_owner].value, lockTokens[_owner].blockNumber);
}
/**
* #dev Approve of minting `_amount` tokens that are assigned to `_owner`
* #param _owner The address that will be assigned the new tokens
* #param _amount The quantity of tokens approved of mintting
* #return True if the tokens are approved of mintting correctly
*/
function approveMintTokens(address _owner, uint256 _amount) nonZeroAddress(_owner) canMint only(hepburnCommunitymoon) public returns (bool) {
require(_amount > 0);
uint256 previousLockTokens = lockTokens[_owner].value;
require(previousLockTokens + _amount >= previousLockTokens);
uint256 curTotalSupply = totalSupply;
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
require(curTotalSupply + _amount <= totalSupplyCap); // Check for overflow of total supply cap
uint256 previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
lockTokens[_owner].value = previousLockTokens.add(_amount);
uint256 curBlockNumber = getCurrentBlockNumber();
lockTokens[_owner].blockNumber = curBlockNumber.add(durationOfLock);
ApproveMintTokens(_owner, _amount);
return true;
}
/**
* #dev Withdraw approval of minting `_amount` tokens that are assigned to `_owner`
* #param _owner The address that will be withdrawn the tokens
* #param _amount The quantity of tokens withdrawn approval of mintting
* #return True if the tokens are withdrawn correctly
*/
function withdrawMintTokens(address _owner, uint256 _amount) nonZeroAddress(_owner) canMint only(hepburnCommunitymoon) public returns (bool) {
require(_amount > 0);
uint256 previousLockTokens = lockTokens[_owner].value;
require(previousLockTokens - _amount >= 0);
lockTokens[_owner].value = previousLockTokens.sub(_amount);
if (previousLockTokens - _amount == 0) {
lockTokens[_owner].blockNumber = 0;
}
WithdrawMintTokens(_owner, _amount);
return true;
}
/**
* #dev Mints `_amount` tokens that are assigned to `_owner`
* #param _owner The address that will be assigned the new tokens
* #return True if the tokens are minted correctly
*/
function mintTokens(address _owner) canMint only(hepburnDevmoon) nonZeroAddress(_owner) public returns (bool) {
require(lockTokens[_owner].blockNumber <= getCurrentBlockNumber());
uint256 _amount = lockTokens[_owner].value;
uint256 curTotalSupply = totalSupply;
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
require(curTotalSupply + _amount <= totalSupplyCap); // Check for overflow of total supply cap
uint256 previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
totalSupply = curTotalSupply.add(_amount);
balances[_owner] = previousBalanceTo.add(_amount);
lockTokens[_owner].value = 0;
lockTokens[_owner].blockNumber = 0;
MintTokens(_owner, _amount);
Transfer(0, _owner, _amount);
return true;
}
/**
* #dev Mints `_amount` tokens that are assigned to `_owner` within one day after deployment
* the tokens minted will be added to balance immediately
* #param _owner The address that will be assigned the new tokens
* #param _amount The quantity of tokens withdrawn minted
* #return True if the tokens are minted correctly
*/
function mintTokensWithinTime(address _owner, uint256 _amount) nonZeroAddress(_owner) canMint only(hepburnDevmoon) public returns (bool) {
require(_amount > 0);
require(getCurrentBlockNumber() < (deployBlockNumber + MINTTIME));
uint256 curTotalSupply = totalSupply;
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
require(curTotalSupply + _amount <= totalSupplyCap); // Check for overflow of total supply cap
uint256 previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
totalSupply = curTotalSupply.add(_amount);
balances[_owner] = previousBalanceTo.add(_amount);
MintTokens(_owner, _amount);
Transfer(0, _owner, _amount);
return true;
}
/**
* #dev Transfer tokens to multiple addresses
* #param _addresses The addresses that will receieve tokens
* #param _amounts The quantity of tokens that will be transferred
* #return True if the tokens are transferred correctly
*/
function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) canTransfer public returns (bool) {
for (uint256 i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0));
require(_amounts[i] <= balances[msg.sender]);
require(_amounts[i] > 0);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amounts[i]);
balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]);
Transfer(msg.sender, _addresses[i], _amounts[i]);
}
return true;
}
/**
* #dev Burns `_amount` tokens from `_owner`
* #param _amount The quantity of tokens being burned
* #return True if the tokens are burned correctly
*/
function burnTokens(uint256 _amount) public returns (bool) {
require(_amount > 0);
uint256 curTotalSupply = totalSupply;
require(curTotalSupply >= _amount);
uint256 previousBalanceTo = balanceOf(msg.sender);
require(previousBalanceTo >= _amount);
totalSupply = curTotalSupply.sub(_amount);
balances[msg.sender] = previousBalanceTo.sub(_amount);
BurnTokens(msg.sender, _amount);
Transfer(msg.sender, 0, _amount);
return true;
}
/**
* #dev Function to stop minting new tokens.
* #return True if the operation was successful.
*/
function finishMinting() only(hepburnDevmoon) canMint public returns (bool) {
mintingFinished = true;
MintFinished(msg.sender);
return true;
}
function getCurrentBlockNumber() private view returns (uint256) {
return block.number;
}
}
}
}
You have two extra right curly brackets (}) at the end of the code. I think that is why you get the error.
Some Observations:
two extra right curly brackets at the end.
in modifier onlyOwner(), their is typo (requir -> require).
function sub(unit256 a) typo, (unit256 -> uint256).
address typo -> event DisableSetTransferable(ddress indexed _address,
bool _canSetTransferable);
function transferFrom(addres from) typo, (addres -> address).
modifier canTransfer() should contain "_;".
function setTransferable -> try changing name of this function as it
is same as the event name you are calling from inside. (and may be due
to prefix "set" in function name compiler can give error)
best practice if you call any function, call it with same name and
same case
(ex. approval not as Approval)
Call correct method SethepburnDevmoon not sethepburnCommunitymoon
inside function sethepburnCommunitymoon.
whenever you invoking any event, you should invoke it by adding prefix
"emit" to it.
The GAS used by this contract at deployment will be almost 3800000 ->
0.07562 eth -> almost $210 (in case you wanna know) -happy coding :)

Retrieve stuck ether on smart contract

Is there any way to recover ether that is stuck in a smart contract?
refundMoney() method was supposed to call only after everything is finalized but because someone has transferred some ether amount from an exchange wallet and we had to refund that. Now the weiRaised variable is showing more value than the smart contract currently have.
Here is the live contract deployed with source code
https://etherscan.io/address/0x7ff0b2afa427507a50ed4f82231b2b8a972fdff1
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public { owner = msg.sender; }
modifier onlyOwner() {
address sender = msg.sender;
address _owner = owner;
require(msg.sender == _owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* #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));
// 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 constant returns (uint256 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 on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.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 constant returns (uint256 remaining) {
return allowed[_owner][_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
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
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;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* #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) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0, _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.
*/
function mintFinalize(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
/**
* #dev Function to stop minting new tokens.
* #return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* #title SwordToken
* #dev Sword ERC20 Token that can be minted.
* It is meant to be used in Sword crowdsale contract.
*/
contract SwordToken is MintableToken {
string public constant name = "Sword Coin";
string public constant symbol = "SWDC";
uint8 public constant decimals = 18;
function getTotalSupply() view public returns (uint256) {
return totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
super.transfer(_to, _value);
}
}
contract KycContractInterface {
function isAddressVerified(address _address) public view returns (bool);
}
contract KycContract is Ownable {
mapping (address => bool) verifiedAddresses;
function isAddressVerified(address _address) public view returns (bool) {
return verifiedAddresses[_address];
}
function addAddress(address _newAddress) public onlyOwner {
require(!verifiedAddresses[_newAddress]);
verifiedAddresses[_newAddress] = true;
}
function removeAddress(address _oldAddress) public onlyOwner {
require(verifiedAddresses[_oldAddress]);
verifiedAddresses[_oldAddress] = false;
}
function batchAddAddresses(address[] _addresses) public onlyOwner {
for (uint cnt = 0; cnt < _addresses.length; cnt++) {
assert(!verifiedAddresses[_addresses[cnt]]);
verifiedAddresses[_addresses[cnt]] = true;
}
}
}
/**
* #title SwordCrowdsale
* #dev This is Sword's crowdsale contract.
*/
contract SwordCrowdsale is Ownable {
using SafeMath for uint256;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public limitDateSale; // end date in units
bool public isSoftCapHit = false;
bool public isStarted = false;
bool public isFinalized = false;
struct ContributorData {
uint256 contributionAmount;
uint256 tokensIssued;
}
address[] public tokenSendFailures;
mapping(address => ContributorData) public contributorList;
mapping(uint => address) contributorIndexes;
uint nextContributorIndex;
constructor() public {}
function init(uint256 _totalTokens, uint256 _tokensForCrowdsale, address _wallet,
uint256 _etherInUSD, address _tokenAddress, uint256 _softCapInEthers, uint256 _hardCapInEthers,
uint _saleDurationInDays, address _kycAddress, uint bonus) onlyOwner public {
setTotalTokens(_totalTokens);
setTokensForCrowdSale(_tokensForCrowdsale);
setWallet(_wallet);
setRate(_etherInUSD);
setTokenAddress(_tokenAddress);
setSoftCap(_softCapInEthers);
setHardCap(_hardCapInEthers);
setSaleDuration(_saleDurationInDays);
setKycAddress(_kycAddress);
setSaleBonus(bonus);
kyc = KycContract(_kycAddress);
start(); // starting the crowdsale
}
/**
* #dev Must be called to start the crowdsale
*/
function start() onlyOwner public {
require(!isStarted);
require(!hasStarted());
require(wallet != address(0));
require(tokenAddress != address(0));
require(kycAddress != address(0));
require(rate != 0);
require(saleDuration != 0);
require(totalTokens != 0);
require(tokensForCrowdSale != 0);
require(softCap != 0);
require(hardCap != 0);
starting();
emit SwordStarted();
isStarted = true;
}
uint256 public totalTokens = 0;
function setTotalTokens(uint256 _totalTokens) onlyOwner public {
totalTokens = _totalTokens * (10 ** 18); // Total 1 billion tokens, 75 percent will be sold
}
uint256 public tokensForCrowdSale = 0;
function setTokensForCrowdSale(uint256 _tokensForCrowdsale) onlyOwner public {
tokensForCrowdSale = _tokensForCrowdsale * (10 ** 18); // Total 1 billion tokens, 75 percent will be sold
}
// address where funds are collected
address public wallet = 0x0;
function setWallet(address _wallet) onlyOwner public {
wallet = _wallet;
}
uint256 public rate = 0;
function setRate(uint256 _etherInUSD) public onlyOwner{
rate = (5 * (10**18) / 100) / _etherInUSD;
}
// The token being sold
SwordToken public token;
address tokenAddress = 0x0;
function setTokenAddress(address _tokenAddress) public onlyOwner {
tokenAddress = _tokenAddress; // to check if token address is provided at start
token = SwordToken(_tokenAddress);
}
uint256 public softCap = 0;
function setSoftCap(uint256 _softCap) onlyOwner public {
softCap = _softCap * (10 ** 18);
}
uint256 public hardCap = 0;
function setHardCap(uint256 _hardCap) onlyOwner public {
hardCap = _hardCap * (10 ** 18);
}
// sale period (includes holidays)
uint public saleDuration = 0; // in days ex: 60.
function setSaleDuration(uint _saleDurationInDays) onlyOwner public {
saleDuration = _saleDurationInDays;
limitDateSale = startTime + (saleDuration * 1 days);
endTime = limitDateSale;
}
address kycAddress = 0x0;
function setKycAddress(address _kycAddress) onlyOwner public {
kycAddress = _kycAddress;
}
uint public saleBonus = 0; // ex. 10
function setSaleBonus(uint bonus) public onlyOwner{
saleBonus = bonus;
}
bool public isKYCRequiredToReceiveFunds = true; // whether Kyc is required to receive funds.
function setKYCRequiredToReceiveFunds(bool IS_KYCRequiredToReceiveFunds) public onlyOwner{
isKYCRequiredToReceiveFunds = IS_KYCRequiredToReceiveFunds;
}
bool public isKYCRequiredToSendTokens = true; // whether Kyc is required to send tokens.
function setKYCRequiredToSendTokens(bool IS_KYCRequiredToSendTokens) public onlyOwner{
isKYCRequiredToSendTokens = IS_KYCRequiredToSendTokens;
}
// fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender);
}
KycContract public kyc;
function transferKycOwnerShip(address _address) onlyOwner public {
kyc.transferOwnership(_address);
}
function transferTokenOwnership(address _address) onlyOwner public {
token.transferOwnership(_address);
}
/**
* release Tokens
*/
function releaseAllTokens() onlyOwner public {
for(uint i=0; i < nextContributorIndex; i++) {
address addressToSendTo = contributorIndexes[i]; // address of user
releaseTokens(addressToSendTo);
}
}
/**
* release Tokens of an individual address
*/
function releaseTokens(address _contributerAddress) onlyOwner public {
if(isKYCRequiredToSendTokens){
if(KycContractInterface(kycAddress).isAddressVerified(_contributerAddress)){ // if kyc needs to be checked at release time
release(_contributerAddress);
}
} else {
release(_contributerAddress);
}
}
function release(address _contributerAddress) internal {
if(contributorList[_contributerAddress].tokensIssued > 0) {
if(token.mint(_contributerAddress, contributorList[_contributerAddress].tokensIssued)) { // tokens sent successfully
contributorList[_contributerAddress].tokensIssued = 0;
contributorList[_contributerAddress].contributionAmount = 0;
} else { // token sending failed, has to be processed manually
tokenSendFailures.push(_contributerAddress);
}
}
}
function tokenSendFailuresCount() public view returns (uint) {
return tokenSendFailures.length;
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
if(isKYCRequiredToReceiveFunds){
require(KycContractInterface(kycAddress).isAddressVerified(msg.sender));
}
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = computeTokens(weiAmount);
require(isWithinTokenAllocLimit(tokens));
// update state - Add to eth raised
weiRaised = weiRaised.add(weiAmount);
if (contributorList[beneficiary].contributionAmount == 0) { // if its a new contributor, add him and increase index
contributorIndexes[nextContributorIndex] = beneficiary;
nextContributorIndex += 1;
}
contributorList[beneficiary].contributionAmount += weiAmount;
contributorList[beneficiary].tokensIssued += tokens;
emit SwordTokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
handleFunds();
}
/**
* event for token purchase logging
* #param purchaser who paid for the tokens
* #param beneficiary who got the tokens
* #param value weis paid for purchase
* #param amount amount of tokens purchased
*/
event SwordTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function investorCount() constant public returns(uint) {
return nextContributorIndex;
}
// #return true if crowdsale event has started
function hasStarted() public constant returns (bool) {
return (startTime != 0 && now > startTime);
}
// send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// send ether to the fund collection wallet
function forwardAllRaisedFunds() internal {
wallet.transfer(weiRaised);
}
function isWithinSaleTimeLimit() internal view returns (bool) {
return now <= limitDateSale;
}
function isWithinSaleLimit(uint256 _tokens) internal view returns (bool) {
return token.getTotalSupply().add(_tokens) <= tokensForCrowdSale;
}
function computeTokens(uint256 weiAmount) view internal returns (uint256) {
uint256 appliedBonus = 0;
if (isWithinSaleTimeLimit()) {
appliedBonus = saleBonus;
}
return (weiAmount.div(rate) + (weiAmount.div(rate).mul(appliedBonus).div(100))) * (10 ** 18);
}
function isWithinTokenAllocLimit(uint256 _tokens) view internal returns (bool) {
return (isWithinSaleTimeLimit() && isWithinSaleLimit(_tokens));
}
function didSoftCapReached() internal returns (bool) {
if(weiRaised >= softCap){
isSoftCapHit = true; // setting the flag that soft cap is hit and all funds should be sent directly to wallet from now on.
} else {
isSoftCapHit = false;
}
return isSoftCapHit;
}
// overriding SwordBaseCrowdsale#validPurchase to add extra cap logic
// #return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= hardCap;
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return (withinPeriod && nonZeroPurchase) && withinCap && isWithinSaleTimeLimit();
}
// overriding Crowdsale#hasEnded to add cap logic
// #return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= hardCap;
return (endTime != 0 && now > endTime) || capReached;
}
event SwordStarted();
event SwordFinalized();
/**
* #dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
// require(hasEnded());
finalization();
emit SwordFinalized();
isFinalized = true;
}
function starting() internal {
startTime = now;
limitDateSale = startTime + (saleDuration * 1 days);
endTime = limitDateSale;
}
function finalization() internal {
uint256 remainingTokens = totalTokens.sub(token.getTotalSupply());
token.mintFinalize(wallet, remainingTokens);
forwardAllRaisedFunds();
}
// overridden
function handleFunds() internal {
if(isSoftCapHit){ // if soft cap is reached, start transferring funds immediately to wallet
forwardFunds();
} else {
if(didSoftCapReached()){
forwardAllRaisedFunds();
}
}
}
modifier afterDeadline() { if (hasEnded() || isFinalized) _; } // a modifier to tell token sale ended
/**
* auto refund Tokens
*/
function refundAllMoney() onlyOwner public {
for(uint i=0; i < nextContributorIndex; i++) {
address addressToSendTo = contributorIndexes[i];
refundMoney(addressToSendTo);
}
}
/**
* refund Tokens of a single address
*/
function refundMoney(address _address) onlyOwner public {
uint amount = contributorList[_address].contributionAmount;
if (amount > 0 && _address.send(amount)) { // user got money back
contributorList[_address].contributionAmount = 0;
contributorList[_address].tokensIssued = 0;
}
}
}
It appears that your refundMoney() implementation has a bug, and doesn't decrease the weiRaised value. This means that once you issue a refund, you can no longer use forwardAllRaisedFunds() to drain the contract.
The somewhat good news (for the person who asked for the refund) is that this isn't their fault. Your bug would be triggered even in the regular course of action after you hit the softcap, since funds after the softcap are forwarded automatically, but are still added to weiRaised. There is no scenario in which you would have been able to access all the funds, unless you did not issue a refund and raised less money than the softcap.
The ether in this contract is effectively stuck. You will still be able to receive any funds after the softcap is hit, but funds under the softcap can never be retrieved.

Send ERC-20 token from another contract

I am trying to send ERC-20 token that was deposited to my contract address to another address. Here is the ERC-20 contract code -
pragma solidity ^0.4.11;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/**
* #title ERC20Basic
* #dev Simpler version of ERC20 interface
* #dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* #title Basic token
* #dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* #dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
/**
* #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) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* #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) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* #title ERC20 interface
* #dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* #title Standard ERC20 token
*
* #dev Implementation of the basic standard token.
* #dev https://github.com/ethereum/EIPs/issues/20
* #dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) 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;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* #dev Aprove the passed address to spend the specified amount of tokens on beahlf 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) {
// 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
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* #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() {
owner = msg.sender;
}
/**
* #dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
/**
* #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) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* #title Mintable token
* #dev Simple ERC20 Token example, with mintable token creation
* #dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint value);
event MintFinished();
bool public mintingFinished = false;
uint public totalSupply = 0;
modifier canMint() {
if(mintingFinished) throw;
_;
}
/**
* #dev Function to mint tokens
* #param _to The address that will recieve 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, uint _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* #dev Function to stop minting new tokens.
* #return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* #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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
if (paused) throw;
_;
}
/**
* #dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
if (!paused) throw;
_;
}
/**
* #dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* #dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/**
* Pausable token
*
* Simple ERC20 Token example, with pausable token creation
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint _value) whenNotPaused {
super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused {
super.transferFrom(_from, _to, _value);
}
}
/**
* #title TokenTimelock
* #dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a time has passed
*/
contract TokenTimelock {
// ERC20 basic token contract being held
ERC20Basic token;
// beneficiary of tokens after they are released
address beneficiary;
// timestamp where token release is enabled
uint releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint _releaseTime) {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* #dev beneficiary claims tokens held by time lock
*/
function claim() {
require(msg.sender == beneficiary);
require(now >= releaseTime);
uint amount = token.balanceOf(this);
require(amount > 0);
token.transfer(beneficiary, amount);
}
}
contract TestToken is PausableToken, MintableToken {
using SafeMath for uint256;
string public name = "TestToken";
string public symbol = "TT";
uint public decimals = 18;
/**
* #dev mint timelocked tokens
*/
function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime)
onlyOwner canMint returns (TokenTimelock) {
TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime);
mint(timelock, _amount);
return timelock;
}
}
And the following is the contract from which I'm trying to send the deposited tokens -
pragma solidity ^0.4.18;
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
/**
* Create the contract, and sets the destination address to that of the creator
*/
function Forwarder() public {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
revert();
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the parent address
*/
function() public payable {
// throws on failure
parentAddress.transfer(msg.value);
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* #param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) public onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
revert();
}
}
}
When I call the flushToken function I get an error - Error: gas required exceeds allowance or always failing transaction.
In order to transfer tokens from one address to another you need first to approve the transaction.
function approve(address spender, uint tokens) public returns (bool success);
In that was you approve that the second contract can transfer the money from the first contract.
You can check the allowance wit this function
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);

Error when transfer at token contract

I'm building a token smart contract And I am using ropsen tesnet with remix.
When I call the function transfer or transferfrom I always got error:
on ropsen tesnet I got:
transact to TokenERC20.transfer errored: VM error: revert. revert The
transaction has been reverted to the initial state. Note: The
constructor should be payable if you send value. Debug the transaction
to get more information.
on JavaScript JM I got the same error while I can debug,and my debug information is:
status 0x0 Transaction mined but execution failed
from 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c
to TokenERC20.transfer(address,uint256) 0xbbf289d846208c16edc8474705c748aff07732db
gas 3000000 gas
transaction cost 23644 gas
execution cost 772 0x6581192b9d4c2395814668bb13163f0a6c34bab8f49b8395950b278ed7e9c666
gas hash input ...
decoded input { "address _to":
"0x14723a09acff6d2a60dcdf7aa4aff308fddc160c", "uint256 _value": "100"
} decoded output {} logs [] value 0 wei
Here is my coding:
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18; // decimals 可以有的小数点个数,最小的代币单位。18 是建议的默认值
uint256 public totalSupply;
// 用mapping保存每个地址对应的余额
mapping (address => uint256) public balanceOf;
// 存储对账号的控制
mapping (address => mapping (address => uint256)) public allowance;
// 事件,用来通知客户端交易发生
event Transfer(address indexed from, address indexed to, uint256 value);
// 事件,用来通知客户端代币被消费
event Burn(address indexed from, uint256 value);
/**
* 初始化构造
*/
function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // 供应的份额,份额跟最小的代币单位有关,份额 = 币数 * 10 ** decimals。
balanceOf[msg.sender] = totalSupply; // 创建者拥有所有的代币
name = tokenName; // 代币名称
symbol = tokenSymbol; // 代币符号
}
/**
* 代币交易转移的内部实现
*/
function _transfer(address _from, address _to, uint _value) internal {
// 确保目标地址不为0x0,因为0x0地址代表销毁
require(_to != 0x0);
// 检查发送者余额
require(balanceOf[_from] >= _value);
// 确保转移为正数个
require(balanceOf[_to] + _value > balanceOf[_to]);
// 以下用来检查交易,
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// 用assert来检查代码逻辑。
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* 代币交易转移
* 从自己(创建交易者)账号发送`_value`个代币到 `_to`账号
*
* #param _to 接收者地址
* #param _value 转移数额
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* 账号之间代币交易转移
* #param _from 发送者地址
* #param _to 接收者地址
* #param _value 转移数额
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* 设置某个地址(合约)可以创建交易者名义花费的代币数。
*
* 允许发送者`_spender` 花费不多于 `_value` 个代币
*
* #param _spender The address authorized to spend
* #param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* 设置允许一个地址(合约)以我(创建交易者)的名义可最多花费的代币数。
*
* #param _spender 被授权的地址(合约)
* #param _value 最大可花费代币数
* #param _extraData 发送给合约的附加数据
*/
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;
}
}
/**
* 销毁我(创建交易者)账户中指定个代币
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* 销毁用户账户中指定个代币
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* #param _from the address of the sender
* #param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
I would appreciate it if someone could point me in the right direction.
You should make the transfer function use the payable keyword if you are wanting the contract to accept ether.
You shouldn't put any Ether when calling transfer function, just set the value field of your transaction to 0.