Gas required exceeds block gas limit fallback function - ethereum

I'm working on a smart contract and followed this video here: https://www.youtube.com/watch?v=s677QFT6e4U&t=911s. I copied the code exactly, but when I try to call the fallback function I get the following error: Gas required exceeds block gas limit: 300000000. Even though the fallback function is as follows (it does nothing):
function () payable {
}
How could this be using too much gas?
CONTRACT CODE:
pragma solidity ^0.4.11;
import './IERC20.sol';
import './SafeMath.sol';
contract AToken is IERC20 {
using SafeMath for uint256;
uint256 public _totalSupply = 0;
uint256 public constant hardLimit = 45000000;
string public constant symbol = "ABC";
string public constant name = "Alphabet";
uint8 public constant decimals = 18;
//1 ETH = 25000 Alphabet
uint256 public constant RATE = 25000;
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function () payable {
createTokens();
}
function SnapToken() {
owner = msg.sender;
}
function createTokens() payable {
//require(msg.value > 0);
//uint256 tokens = msg.value.mul(RATE);
//require(tokens.add(_totalSupply) <= hardLimit);
//balances[msg.sender] = balances[msg.sender].add(tokens);
//_totalSupply = _totalSupply.add(tokens);
//owner.transfer(msg.value);
}
function totalSupply() constant returns (uint256 totalSupply) {
return _totalSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value && _value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
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;
}
function approve(address _spender, uint256 _value) returns (bool success) {
//allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_value);
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 value);
}
I commented out some stuff to see if this would reduce the gas requirement but unfortunately not. Have you faced this before?
Thanks

The contract, as posted, does execute when calling the fallback function (Tested in Remix). However, it will fail once you uncomment the logic in createTokens()
Fallback functions have low gas limits (2300) and, therefore, are very limited in what they can do. You can't do things like write to storage, call external functions, or send ether out as you will instantly hit the limit. It should primarily be used to enable your contract to receive ether and maybe log an event.
In the example you posted above, remove the call to createTokens() in your fallback function and just call that function directly from your client.
Documentation on Fallback Functions
Example client code:
const abiDefinition = ...;
const contractAddress = ...;
const account = ...;
const amountInEther = ...;
const contract = web3.eth.contract(abiDefinition);
const contractInstance = contract.at(contractAddress);
const transactionObj = {
from: account,
value: web3.toWei(amountInEther, 'ether'),
};
contractInstance.createTokens.sendTransaction(transactionObj, (error, result) = {
...
};
Also, as a side note, your value calculations are incorrect. msg.value is in Wei, not ether. Sending in 1 ether causes you to go well above your hardlimit. It's recommended to work with Wei in your contracts, so you should adjust your RATE.

Related

My "Buy" function in smart contract file keep making error

This is my solidity file for NFT marketplace.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
contract NFT is ERC721URIStorage,Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address payable public _owner;
mapping(address => uint[]) public addressToTokenArray;
mapping(uint256 => bool) public forSale;
mapping(uint256 => uint256) public tokenIdToPrice;
event Minting(address _owner, uint256 _tokenId, uint256 _price);
event Purchase(address _seller, address _buyer, uint256 _price);
event Remove(uint256 _tokenId, uint[] beforeBuy, uint[] afterBuy);
constructor() ERC721("TeddyBear", "TEDDY") {
}
function mint(string memory _tokenURI, uint256 _price) public onlyOwner returns (bool)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
tokenIdToPrice[newItemId] = _price;
if(addressToTokenArray[msg.sender].length !=1){
addressToTokenArray[msg.sender].push(newItemId);
}else{
addressToTokenArray[msg.sender] = [newItemId];
}
_mint(msg.sender, newItemId);
_setTokenURI(newItemId, _tokenURI);
emit Minting(msg.sender, newItemId, _price);
return true;
}
// 토큰의 주인이 판매 하는 함수
function sell(uint256 _tokenId, uint256 _price) external {
require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
require(_price > 0, 'Price zero');
tokenIdToPrice[_tokenId] = _price;
forSale[_tokenId] = true;
}
// 토큰의 주인이 판매를 취하하는 함수
function stopSell(uint256 _tokenId) external {
require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
forSale[_tokenId] = false;
}
// function remove(uint[] memory array, uint index) public pure returns(uint[] memory) {
// if (index >= array.length) return array;
// for (uint i = index; i<array.length-1; i++){
// array[i] = array[i+1];
// }
// delete array[array.length-1];
// return array;
// }
function buy(uint256 _tokenId, uint256 sendAmount) external payable {
uint256 price = tokenIdToPrice[_tokenId];
bool isOnSale = forSale[_tokenId];
require(isOnSale, 'This token is not for sale');
require(sendAmount == price, 'Incorrect value');
address seller = ownerOf(_tokenId);
require(seller == ownerOf(_tokenId), 'Seller and Owner is not same');
// uint[] memory beforeBuy = addressToTokenArray[seller];
// // for(uint i=0;i<addressToTokenArray[seller].length;i++){
// // if(_tokenId == addressToTokenArray[seller][i]){
// // remove(addressToTokenArray[seller],i);
// // }
// // }
// uint[] memory afterBuy = addressToTokenArray[seller];
// emit Remove(_tokenId, beforeBuy, afterBuy);
addressToTokenArray[msg.sender] = [_tokenId];
safeTransferFrom(seller, msg.sender, _tokenId);
forSale[_tokenId] = true;
payable(seller).transfer(sendAmount); // send the ETH to the seller
emit Purchase(seller, msg.sender, sendAmount);
}
function getPrice(uint256 _tokenId) public view returns (uint256){
uint256 price = tokenIdToPrice[_tokenId];
return price;
}
function isSale(uint256 _tokenId) public view returns (bool){
bool isOnSale = forSale[_tokenId];
return isOnSale;
}
function getMyTokenId() public view returns (uint[] memory){
uint[] memory myTokens = addressToTokenArray[msg.sender];
return myTokens;
}
}
Among functions up there, the buy function does not emit an error when I compile the .sol file, but after I deploy this contract and send transaction for "buy" function it keeps making this error.
I just want to know where I should fix it and if there is any better idea for other functions, feel free to let me know... many thanks
Most likely it is failing here:
safeTransferFrom(seller, msg.sender, _tokenId);
If you check the ERC721 contract, safeTransferFrom eventually calls this:
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// ****** HERE IS THE ISSUE *****
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
If your contract is going to transfer a token on behalf of owner, owner has to approve first.
so from the seller's contract, this should be called:
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
tokenApprovals is a mapping that keeps track of which tokens can be transferred.
Debugging
in order to test which function call is causing error, place this requirement statement require(sendAmount == price, 'Incorrect value'); right before the function. and pass an incorrect value and you will get an error : 'Incorrect value'
Then put that require statement after the function, and pass a wrong value, if this require does send you error, you can be sure that function is causing the error

SimpleAirdrop contract deploy issue even compile is working

I am trying to make Airdrop smartcontract but it return "This contract may be abstract, not implement an abstract parent's methods completely or not invoke an inherited contract's constructor correctly." message when deployed.....The compile works fine though.
Please check my code below
pragma solidity ^0.4.18;
contract ERC20 {
function transfer(address _to, uint256 _value)public returns(bool);
function balanceOf(address tokenOwner)public view returns(uint balance);
function transferFrom(address from, address to, uint256 tokens)public returns(bool success);
}
contract SimpleAirdrop is IERC20 {
IERC20 public token;
uint256 public _decimals = 18;
uint256 public _amount = 1*10**6*10**_decimals;
function SimpleAirdrop(address _tokenAddr) public {
token = IERC20(_tokenAddr);
}
function setAirdrop(uint256 amount, uint256 decimals) public {
_decimals = decimals;
_amount = amount*10**_decimals;
}
function getAirdrop(address reff) public returns (bool success) {
require (token.balanceOf(msg.sender) == 0);
//token.transfer(msg.sender, 1000000000000000000000);
//token.transfer(reff , 200000000000000000000);
token.transfer(msg.sender, _amount);
token.transfer(reff , _amount);
return true;
}
}
Your SimpleAirdrop inherits from IERC20 (see the first note). IERC20 is an abstract contract - it only defines its functions, but it doesn't implement them. Which makes SimpleAirdrop (the child contract of IERC20) an abstract contract as well.
Solidity doesn't allow deploying abstract contracts. So you have two options to make it not abstract:
Implement the transfer(), balanceOf() and transferFrom() functions (in any of the two contracts).
OR
Remove the inheritance, so that contract SimpleAirdrop is IERC20 becomes only contract SimpleAirdrop.
Assuming by the context of your SimpleAirdrop, which only executes functions on an external IERC20 address, but doesn't act as an ERC-20 token itself, option 2 is sufficient for your use case.
Notes:
Your question defines ERC20 contract but the rest of the code uses IERC20. I'm assuming this is just a typo while copying your code to the question, and that otherwise you're using the same naming in all places.
The current Solidity version (in June 2021) is 0.8.5. I recommend using the current version, there are security and bug fixes.
Please check for any misconception in codes below
No problem in compiling , Deployed using parameters and success in testnet
Problem rise when calling startAirdrop function...some problem with gas
Please be advised
pragma solidity ^0.4.18;
contract ERC20 {
function transfer(address _to, uint256 _value)public returns(bool);
function balanceOf(address tokenOwner)public view returns(uint balance);
function transferFrom(address from, address to, uint256 tokens)public returns(bool success);
}
contract SimpleAirdrop {
ERC20 public token;
uint256 public _decimals = 9;
uint256 public _amount = 1*10**6*10**_decimals;
uint256 public _cap = _amount *10**6;
address public tokenOwner = 0x0;
uint256 public _totalClaimed = 0;
uint256 public _reffPercent = 10;
function SimpleAirdrop(address _tokenAddr ,address _tokenOwner ) public {
token = ERC20(_tokenAddr);
tokenOwner = _tokenOwner;
}
function setAirdrop(uint256 amount, uint256 cap, uint256 decimals ,uint256 reffPercent) public returns (bool success){
require (msg.sender == tokenOwner);
_decimals = decimals;
_amount = amount*10**_decimals;
_cap = cap*10**_decimals;
_reffPercent = reffPercent;
return true;
}
function sendAirdropToken() public returns (bool success){
require (msg.sender == tokenOwner);
token.transferFrom(msg.sender,address(this),_cap);
return true;
}
function returnAirdropToOwner() public returns (bool success){
require (msg.sender == tokenOwner);
token.transferFrom(address(this), msg.sender, address(this).balance);
return true;
}
function getAirdrop(address reff) public returns (bool success){
if(msg.sender != reff && token.balanceOf(reff) != 0 && reff != 0x0000000000000000000000000000000000000000 && _cap >= _amount){
token.transfer(reff , _amount*(_reffPercent/100));
_cap = _cap - (_amount*(_reffPercent/100));
}
if(msg.sender != reff && token.balanceOf(reff) != 0 && token.balanceOf(msg.sender) == 0 && reff != 0x0000000000000000000000000000000000000000 && _cap >= _amount)
{ token.transfer(msg.sender, _amount);
_cap = _cap - _amount;
_totalClaimed ++;
}
return true;
}
}

Solidity, assigning multiple values with "=" in the same line

Where can I get a detailed explaination of this weird assignment in solidity?
The one in the constructor. Multiple = = = .
Couldn't find anything in the official docs.
contract Token {
mapping(address => uint) balances;
uint public totalSupply;
uint public anotherUint = 10;
constructor(uint _initialSupply, uint _anotherUint) {
balances[msg.sender] = totalSupply = anotherUint = _initialSupply = _anotherUint;
}
function transfer(address _to, uint _value) public returns (bool) {
require(balances[msg.sender] - _value >= 0);
balances[msg.sender] -= _value;
balances[_to] += _value;
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
}
It's an example of chained assignment, that is available in many other programming languages.
Example in JS:
// copy paste this to your browser devtools console to explore how it works
let _initialSupply = 5;
let _anotherUint = 10;
let anotherUint;
let totalSupply;
const balance = totalSupply = anotherUint = _initialSupply = _anotherUint;
It assignes:
value of _anotherUint to _initialSupply (overriding the value passed in constructor)
(the new) value of _initialSupply to anotherUint
value of anotherUint to totalSupply
and finally the value of totalSupply to the balances[msg.sender] (or in my JS code to balance)
Solidity docs don't seem to cover this topic, but it's not explicit to Solidity only.

Solidity: TypeError: Function declared as view, but this expression modifies the state and thus requires non-payable (the default) or payable

I have been trying to create a smart contract/Token, will deploy this on the Binance Smart Chain test net. I followed some documentation and started with this. I am getting into this function issue. Function is declared as Read only. Here is the source code
The function is changing the state of the Owner Address, what is the other option to declare it as read only
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.2;
//import "Context.sol";
//import "IBEP20.sol";
//import "SafeMath.sol";
//import "Ownable.sol";
contract SampleTaken {
mapping(address => uint) public balances;
uint public totalSupply = 1000000 * 10 ** 18;
string public name ="Sample Token";
string public symbol ="KJA";
uint public decimals = 18;
/** Events aailable for the Contract**/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
constructor(){
balances[msg.sender] = totalSupply;
}
function balanceOf(address _ownerAddress) public view returns (uint){
return balances[_ownerAddress];
}
function transfer(address _toAddress, uint _noOfTokens) public view returns (bool){
require(balanceOf(msg.sender) >= _noOfTokens, "Total balance is less than the number of Tokens asked for !!!");
balances[_toAddress] +=_noOfTokens;
balances[msg.sender] -= _noOfTokens;
emit Transfer(msg.sender,_toAddress, _noOfTokens);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool){
require(balanceOf(_from) >= _value, "Balance is less than the number of Tokens asked for !!!");
// require(allowance[_from][msg.sender] >= _value, "Allowance too low");
balances[_to] += _value;
balances[_from] -= _value;
emit Transfer (_from, _to, _value);
return true;
}
}
Any help is much appreciated.
Regards
Your transfer() function is declared as a view function.
Functions can be declared view in which case they promise not to modify the state.
Source: Solidity docs
But these lines (within the transfer() function) modify the state:
balances[_toAddress] +=_noOfTokens;
balances[msg.sender] -= _noOfTokens;
emit Transfer(msg.sender,_toAddress, _noOfTokens);
If you want your function to modify the state, it cannot be a view (nor a pure) function - and you need to remove the view modifier:
function transfer(address _toAddress, uint _noOfTokens) public returns (bool){
Remove view or pure keyword from the function declaration and keep only public returns
Change
function transfer(address _toAddress, uint _noOfTokens) public view returns (bool)
to
function transfer(address _toAddress, uint _noOfTokens) public returns (bool)
Changed method:
function transfer(address _toAddress, uint _noOfTokens) public returns (bool){
require(balanceOf(msg.sender) >= _noOfTokens, "Total balance is less than the number of Tokens asked for !!!");
balances[_toAddress] +=_noOfTokens;
balances[msg.sender] -= _noOfTokens;
emit Transfer(msg.sender,_toAddress, _noOfTokens);
return true;
}

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.