Attached is the source code for the smart contract, could you advise if there's a function in it I can use to recover the 1.5 bnb? I still have access to the creation wallet and the contract isn't renounced.
it would be nice to try and work this out if possible as I am still learning to code.
/**
*Submitted for verification at BscScan.com on 2021-08-27
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract Context {
function _msgSender() internal virtual view returns (address payable) {
return msg.sender;
}
function _msgData() internal virtual view returns (bytes memory) {
this;
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Pair {
function sync() external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
}
// change "name1" into ur name
contract BlueMoon is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
//change "name1" and "symbol"
string private _name = "BlueMoon";
string private _symbol = "BMOON";
uint8 private _decimals = 8;
mapping(address => uint256) internal _reflectionBalance;
mapping(address => uint256) internal _tokenBalance;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 private constant MAX = ~uint256(0);
// change this for total supply (100e8 = 100) (100000000e8 = 100000000) (dont forget the e8 it has to be there)
uint256 internal _tokenTotal = 1_000_000_000e8;
// change this for total supply ^^^^^^^^^^^^^^^^^^^^^
uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal));
mapping(address => bool) isTaxless;
mapping(address => bool) internal _isExcluded;
address[] internal _excluded;
uint256 public _feeDecimal = 2;
// thats the distribution to holders (400 = 4%)
uint256 public _taxFee = 100;
// thats the amount for liquidity pool
uint256 public _liquidityFee = 1000;
// this amount gets burned by every transaction
uint256 public _burnFee = 100;
// this goes to a specific wallet (line 403)
uint256 public _marketingFee = 300;
uint256 public _taxFeeTotal;
uint256 public _burnFeeTotal;
uint256 public _liquidityFeeTotal;
uint256 public _marketingFeeTotal;
address public marketingWallet;
bool public isTaxActive = true;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public maxTxAmount = _tokenTotal;
uint256 public minTokensBeforeSwap = 10_000e8;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived, uint256 tokensIntoLiqudity);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() public {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // for BSC
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // for Ethereum
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); // for Sushi testnet
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
//paste the wallet adress, that earns the marketingFee here
marketingWallet = 0xD64E87ad309f21De5725e91EAFB82c50e486D374;
//paste the wallet ^^^^^^^^^^^^^^^^^^^^^ adress, that earns the marketingFee here
isTaxless[_msgSender()] = true;
isTaxless[address(this)] = true;
_reflectionBalance[_msgSender()] = _reflectionTotal;
emit Transfer(address(0), _msgSender(), _tokenTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public override view returns (uint256) {
return _tokenTotal;
}
function balanceOf(address account) public override view returns (uint256) {
if (_isExcluded[account]) return _tokenBalance[account];
return tokenFromReflection(_reflectionBalance[account]);
}
function transfer(address recipient, uint256 amount)
public
override
virtual
returns (bool)
{
_transfer(_msgSender(),recipient,amount);
return true;
}
function allowance(address owner, address spender)
public
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override virtual returns (bool) {
_transfer(sender,recipient,amount);
_approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub( amount,"ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tokenAmount <= _tokenTotal, "Amount must be less than supply");
if (!deductTransferFee) {
return tokenAmount.mul(_getReflectionRate());
} else {
return
tokenAmount.sub(tokenAmount.mul(_taxFee).div(10** _feeDecimal + 2)).mul(
_getReflectionRate()
);
}
}
function tokenFromReflection(uint256 reflectionAmount)
public
view
returns (uint256)
{
require(
reflectionAmount <= _reflectionTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getReflectionRate();
return reflectionAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(
account != address(uniswapV2Router),
"ERC20: We can not exclude Uniswap router."
);
require(!_isExcluded[account], "ERC20: Account is already excluded");
if (_reflectionBalance[account] > 0) {
_tokenBalance[account] = tokenFromReflection(
_reflectionBalance[account]
);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "ERC20: Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tokenBalance[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= maxTxAmount, "Transfer Limit exceeded!");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap;
if (!inSwapAndLiquify && overMinTokenBalance && sender != uniswapV2Pair && swapAndLiquifyEnabled) {
swapAndLiquify(contractTokenBalance);
}
uint256 transferAmount = amount;
uint256 rate = _getReflectionRate();
if(isTaxActive && !isTaxless[_msgSender()] && !isTaxless[recipient] && !inSwapAndLiquify){
transferAmount = collectFee(sender,amount,rate);
}
_reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate));
_reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate));
if (_isExcluded[sender]) {
_tokenBalance[sender] = _tokenBalance[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount);
}
emit Transfer(sender, recipient, transferAmount);
}
function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) {
uint256 transferAmount = amount;
//#dev tax fee
if(_taxFee != 0){
uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(taxFee);
_reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate));
_taxFeeTotal = _taxFeeTotal.add(taxFee);
}
//#dev liquidity fee
if(_liquidityFee != 0){
uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(liquidityFee);
_reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate));
if(_isExcluded[address(this)]){
_tokenBalance[address(this)] = _tokenBalance[address(this)].add(liquidityFee);
}
_liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee);
emit Transfer(account,address(this),liquidityFee);
}
//#dev burn fee
if(_burnFee != 0){
uint256 burnFee = amount.mul(_burnFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(burnFee);
_tokenTotal = _tokenTotal.sub(burnFee);
_reflectionTotal = _reflectionTotal.sub(burnFee.mul(rate));
_burnFeeTotal = _burnFeeTotal.add(burnFee);
emit Transfer(account,address(0),burnFee);
}
//#dev Marketing fee
if(_marketingFee != 0){
uint256 marketingFee = amount.mul(_marketingFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(marketingFee);
_reflectionBalance[marketingWallet] = _reflectionBalance[marketingWallet].add(marketingFee.mul(rate));
if (_isExcluded[marketingWallet]) {
_tokenBalance[marketingWallet] = _tokenBalance[marketingWallet].add(marketingFee);
}
_marketingFeeTotal = _marketingFeeTotal.add(marketingFee);
emit Transfer(account,marketingWallet,marketingFee);
}
return transferAmount;
}
function _getReflectionRate() private view returns (uint256) {
uint256 reflectionSupply = _reflectionTotal;
uint256 tokenSupply = _tokenTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_reflectionBalance[_excluded[i]] > reflectionSupply ||
_tokenBalance[_excluded[i]] > tokenSupply
) return _reflectionTotal.div(_tokenTotal);
reflectionSupply = reflectionSupply.sub(
_reflectionBalance[_excluded[i]]
);
tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]);
}
if (reflectionSupply < _reflectionTotal.div(_tokenTotal))
return _reflectionTotal.div(_tokenTotal);
return reflectionSupply.div(tokenSupply);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
if(contractTokenBalance > maxTxAmount)
contractTokenBalance = maxTxAmount;
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
}
function setPair(address pair) external onlyOwner {
uniswapV2Pair = pair;
}
function setMarketingWallet(address account) external onlyOwner {
marketingWallet = account;
}
function setTaxless(address account, bool value) external onlyOwner {
isTaxless[account] = value;
}
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner {
swapAndLiquifyEnabled = enabled;
SwapAndLiquifyEnabledUpdated(enabled);
}
function setTaxActive(bool value) external onlyOwner {
isTaxActive = value;
}
function setTaxFee(uint256 fee) external onlyOwner {
_taxFee = fee;
}
function setBurnFee(uint256 fee) external onlyOwner {
_burnFee = fee;
}
function setLiquidityFee(uint256 fee) external onlyOwner {
_liquidityFee = fee;
}
function setMarketingFee(uint256 fee) external onlyOwner {
_marketingFee = fee;
}
function setMaxTxAmount(uint256 amount) external onlyOwner {
maxTxAmount = amount;
}
function setMinTokensBeforeSwap(uint256 amount) external onlyOwner {
minTokensBeforeSwap = amount;
}
receive() external payable {}
}
as far as im aware im sure most contracts have some sort of clear stuck balance function in them which you can use. but I dont see one here. is it an oversight? or can it still be called using other functions.
Thanks for any advise. am willing to try what is recommended.
Related
I'm trying to make a contract and I want to add the "black list" function and the function to manipulate the transaction price.
But solidity shows me an error.
"ParserError: Function, variable, struct or modifier declaration expected."
I copy the functions from other contracts but I don't understand how to synchronize them.
Can someone explain to me what i'm doing wrong.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract FixedStaking is ERC20 {
mapping(address => uint256) public staked;
mapping(address => uint256) private stakedFromTS;
constructor() ERC20("FixedStaking", "FTX") {
_mint(msg.sender,1000000000000000000000000000);
}
function stake (uint256 amount) external {
require(amount > 0, "amoint is <= 0");
require(balanceOf(msg.sender) >= amount, "balance is <= amount");
_transfer(msg.sender, address(this), amount);
if (staked[msg.sender] > 0) {
claim();
}
stakedFromTS[msg.sender] = block.timestamp;
staked[msg.sender] += amount;
}
function unstake (uint256 amount) external {
require(amount > 0, "amount is <= 0");
require(staked[msg.sender] >= amount, "amount is > staked");
claim();
staked[msg.sender] -= amount;
_transfer(address(this), msg.sender, amount);
}
function claim() public {
require(staked[msg.sender] >0, "staked is <= 0");
uint256 secondsStaked = block.timestamp - stakedFromTS[msg.sender];
uint256 rewards = staked[msg.sender] * secondsStaked / 3.154e7;
_mint(msg.sender,rewards);
stakedFromTS[msg.sender] = block.timestamp;
}
function updateTransferFee() public onlyOwner {
require (newTransferFee <= 10000, "transfer fee cannot exceed 10%");
transferFee = newTransferFee;
emit UpdateTransferFee(transferFee);
}
contract BlackList is ERC20 {
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
}
My contract for ERC1155 marketplace to mint buy and sell the NFT.
The nft is getting minted , However the NFT is not showing in market place and not able to purchase. I am facing this error.I have also applied setApprovedforAll method while minting still no help.
Should create and execute market sales:
Error: VM Exception while processing transaction: reverted with reason string 'ERC1155: caller is not owner nor approved'
at NFT1155.balanceOf (#openzeppelin/contracts/token/ERC1155/ERC1155.sol:71)
at NFT1155.isApprovedForAll (#openzeppelin/contracts/token/ERC1155/ERC1155.sol:110)
at NFT1155.createMarketSale (contracts/NFT1155.sol:165)
at async HardhatNode._mineBlockWithPendingTxs (node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1772:23)
at async HardhatNode.mineBlock (node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:466:16)
at async EthModule._sendTransactionAndReturnHash (node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1496:18)
at async HardhatNetworkProvider.request (node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:118:18)
at async EthersProviderWrapper.send (node_modules/#nomiclabs/hardhat-ethers/src/internal/ethers-provider-wrapper.ts:13:20)
My contract for ERC1155 marketplace to mint buy and sell the NFT.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "#openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
import "#openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "#openzeppelin/contracts/utils/Counters.sol";
import "hardhat/console.sol";
contract NFT1155 is ERC1155, Ownable, ERC1155Supply {
//contract address goes here and id will be dynamic and will be passed in the _mint function calls
//example https://ipfs.io/ipfs/QmT51bbxTbSiYGcF2X39sG6DGYyAX2413A1sZfiACMgJGP?filename={id}.json
//if the if id 1 then https://ipfs.io/ipfs/QmT51bbxTbSiYGcF2X39sG6DGYyAX2413A1sZfiACMgJGP?filename=1.json will return the data that needs to be minted
constructor() ERC1155("") {}
mapping(uint256 => string) internal _tokenURIs;
mapping(uint256 => MarketItem) private idToMarketItem;
Counters.Counter private _itemsSold;
struct MarketItem {
uint256 tokenId;
address payable seller;
address payable owner;
uint256 price;
bool sold;
}
event MarketItemCreated(
uint256 indexed tokenId,
address seller,
address owner,
uint256 price,
bool sold
);
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
//To chnage the URL String after the contract is deployed
function setURI(string memory newuri) public onlyOwner {
_setURI(newuri);
}
function mintToken(
string memory tokenURI,
uint256 amount,
uint256 price
) public returns (uint256) {
uint256 newItemId = _tokenIds.current();
_mint(address(this), newItemId, amount, "");
_setTokenUri(newItemId, tokenURI);
//createMarketItem(newItemId, price, amount);
_tokenIds.increment();
return newItemId;
}
function createMarketItem(
uint256 tokenId,
uint256 price,
uint256 amount
) private {
require(price > 0, "Price must be at least 1 wei");
idToMarketItem[tokenId] = MarketItem(
tokenId,
payable(msg.sender),
payable(address(this)),
price,
false
);
setApprovalForAll(address(this), true);
safeTransferFrom(msg.sender, address(this), tokenId, amount, "");
emit MarketItemCreated(
tokenId,
msg.sender,
address(this),
price,
false
);
}
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
bytes calldata _data
) external returns (bytes4) {
return
bytes4(
keccak256(
"onERC1155Received(address,address,uint256,uint256,bytes)"
)
);
}
function _setTokenUri(uint256 tokenId, string memory tokenURI) private {
_tokenURIs[tokenId] = tokenURI;
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public onlyOwner {
_mintBatch(to, ids, amounts, data);
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override(ERC1155, ERC1155Supply) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
/* allows someone to resell a token they have purchased */
function resellToken(
uint256 tokenId,
uint256 price,
uint256 amount
) public payable {
require(
idToMarketItem[tokenId].owner == msg.sender,
"Only item owner can perform this operation"
);
idToMarketItem[tokenId].sold = false;
idToMarketItem[tokenId].price = price;
idToMarketItem[tokenId].seller = payable(msg.sender);
idToMarketItem[tokenId].owner = payable(address(this));
_itemsSold.decrement();
safeTransferFrom(msg.sender, address(this), tokenId, amount, "");
}
/* Creates the sale of a marketplace item */
/* Transfers ownership of the item, as well as funds between parties */
function createMarketSale(uint256 tokenId, uint256 amount) public payable {
uint256 price = idToMarketItem[tokenId].price;
address seller = idToMarketItem[tokenId].seller;
console.log(
" ~ file: NFT1155.sol ~ line 147 ~ createMarketSale ~ price",
msg.value,
price
);
// require(
// msg.value == price,
// "Please submit the asking price in order to complete the purchase"
// );
idToMarketItem[tokenId].owner = payable(msg.sender);
idToMarketItem[tokenId].sold = true;
idToMarketItem[tokenId].seller = payable(address(0));
_itemsSold.increment();
safeTransferFrom(address(this), msg.sender, tokenId, amount, "");
setApprovalForAll(address(this), true);
// payable(owner).transfer(listingPrice);
payable(seller).transfer(msg.value);
}
/* Returns all unsold market items */
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint256 itemCount = _tokenIds.current();
uint256 unsoldItemCount = _tokenIds.current() - _itemsSold.current();
uint256 currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint256 i = 0; i < itemCount; i++) {
if (idToMarketItem[i + 1].owner == address(this)) {
uint256 currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/* Returns only items that a user has purchased */
function fetchMyNFTs() public view returns (MarketItem[] memory) {
uint256 totalItemCount = _tokenIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].owner == msg.sender) {
uint256 currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
/* Returns only items a user has listed */
function fetchItemsListed() public view returns (MarketItem[] memory) {
uint256 totalItemCount = _tokenIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == msg.sender) {
itemCount += 1;
}
}
MarketItem[] memory items = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (idToMarketItem[i + 1].seller == msg.sender) {
uint256 currentId = i + 1;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
}
The problem is that because of the way you are minting, you don't own the token, the contract does.
Since you don't own the token, it doesn't appear in marketplaces and you can't call approve or transfer because you are not the owner of the token.
Here is the culprit:
_mint(address(this), newItemId, amount, "");
You are minting to address(this) which is the address of the contract itself.
You'll need a way to send the token from the contract to whomever you want using a custom function, or the probably better solution, you can just mint to the address calling your mintToken function by doing:
_mint(msg.sender, newItemId, amount, "");
Best of luck!!
When You call safeTransferFrom, require statement is not passing
function safeTransferFrom(address from,address to,uint256 id,uint256 amount,bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
Most likely you are transferring a token from the account that does not own the token,
You are using safeTransferFrom which is a public function. Try using _safeTransferFrom.You should add a custom function users can call, and internally use _safeTransferFrom
after reading many post i can't found the issues about this Smart contract who compile but it think i miss something about the inheritance and the Abstract contract.
This is the SC :
// solium-disable linebreak-style
pragma solidity >=0.4.21 <0.6.0;
import "../node_modules/#openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../node_modules/#openzeppelin/contracts/math/SafeMath.sol";
/**
* #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 payable 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.
*/
constructor (Ownable) public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* #dev Allows the current owner to transfer control of the contract to a newOwner.
* #param newOwner The address to transfer ownership to.
*/
function transferOwnership(address payable newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Sample is Ownable {
event NewResource (uint resourceId, string name , uint quality);
uint qualityUnits = 16;
uint qualityModulo = qualityUnits;
uint cooldownTime = 1 days;
struct Resource {
string name;
uint quality;
uint32 rarity;
uint256 cooldownTime;
uint16 stockGain;
uint16 stockLoss;
uint32 readyTime;
uint256 extractionTime;
uint256 extractionId;
uint256 magnetiteId;
uint256 hematiteId;
uint256 class;
uint256 sediments;
uint qualityUnits;
}
//mapping address and apply stocks
mapping (uint => address) public resourceToOwner;
mapping (address => uint) ownerResourceGain;
Resource[] public resources;
/// #dev function to crack the resource stacks
function _createResource (string memory _name , uint _quality) internal {
uint id = resources.push(Resource(_name,_quality ,1 , uint256( now + cooldownTime), 0 , 0, 0,
0, 0, 0, 0, 0, 0, 16) )+1;
resourceToOwner[id] = msg.sender;
ownerResourceGain[msg.sender]++;
emit NewResource(id, _name , _quality);
}
//function to generate rand stats for resources
function _generateRandomQuality(string memory _str ) private view returns (uint) {
uint rand = uint(keccak256(abi.encode(_str)));
return rand % qualityModulo;
}
//function to generate the resource stacks
function createResourceStack(string memory _name) public {
require(ownerResourceGain[msg.sender] ==0);
uint randomQuality = _generateRandomQuality(_name);
randomQuality = randomQuality - randomQuality % 100;
_createResource(_name, randomQuality);
}
}
contract CoreRefined is Sample {
//address public newContractAddress;
function getResourcesStats(uint256 _id)
external
view
returns (
bool isRefiningInProcess,
bool isReady,
uint256 cooldownTime,
//uint256 nextActionAt,
uint256 extractionTime,
uint256 extractionId,
uint256 magnetiteId,
uint256 hematiteId,
uint256 class,
uint256 sediments
)
{
Resource storage stats = resources[_id];
isRefiningInProcess = (stats.quality != 0);
isReady = (stats.cooldownTime <= block.number);
cooldownTime = uint256(stats.cooldownTime);
extractionTime = uint256(stats.extractionTime);
extractionId = uint256(stats.extractionId);
magnetiteId = uint256(stats.magnetiteId);
hematiteId = uint256(stats.hematiteId);
class = uint256(stats.class);
sediments = stats.sediments;
}
}
/// #title RefiningInterface for resource modification called refining
/// #dev Refining function inside for improving stats of resources.
contract RefiningInterface is Sample {
function refining(uint256 _id) external view returns (
bool isRefiningInProcess,
bool isReady,
uint256 cooldownTime,
uint256 nextActionsAt,
uint256 extractionTime,
uint256 extractionId,
uint256 magnetiteId,
uint256 hematiteId,
uint256 class,
uint256 sediments
);
}
contract ResourceRefined is Sample , CoreRefined {
ResourceRefined CoreRefinedContract;
modifier onlyOwnerOf(uint _resourceId) {
require(msg.sender == resourceToOwner[_resourceId]);
_;
}
function SetAnotherContractAddress (address _address) external onlyOwner {
CoreRefinedContract
= ResourceRefined(_address);
}
function triggerCooldown (Resource storage _resource ) internal {
_resource.readyTime = uint32(now+cooldownTime);
}
function _isReady ( Resource storage _resource ) internal view returns (bool) {
return (_resource.readyTime <= now);
}
function refinedAndMultiply( uint _resourceId, uint _targetQuality, string memory _types) internal onlyOwnerOf(_resourceId) {
Resource storage myResource = resources[_resourceId];
require(_isReady(myResource));
_targetQuality % qualityModulo;
uint newQuality = (myResource.quality + _targetQuality) / 2;
if(keccak256(abi.encode((_types))) == keccak256(abi.encode("Resources"))) {
newQuality = newQuality - newQuality % 100 + 99;
}
_createResource("NoName", newQuality);
triggerCooldown(myResource);
}
function refineOnInterface(uint256 _resourceId, uint256 _idResources ) public {
uint256 materialUsed;
(,,,,,,,,materialUsed) = CoreRefinedContract.getResourcesStats(_idResources);
refinedAndMultiply(_resourceId,materialUsed,"Resources");
}
}
contract ResourceHelper is ResourceRefined {
//cost ether for rarityUp fee
uint rarityForFee = 0.001 ether;
//modify rarity !=not LEVEL
modifier aboveCostLevel (uint _rarity ,uint _resourceId){
require(resources[_resourceId].rarity >= _rarity);
_;
}
//function to withdraw FIX ISSUE
/*function withdraw() external onlyOwner {
owner.transfer(this).balance;
}*/
//rarityfee for resources improvements
function setRarityFee(uint _fee) external onlyOwner {
rarityForFee = _fee;
}
//Rarity improvement function
/// #dev this function is set by using RefinedResource.sol contract in order to gain better resources
function rarityUp(uint _resourceId) external payable {
require(msg.value == rarityForFee);
resources[_resourceId].rarity++;
}
//change the name of resources
function changeName(uint _resourceId, string calldata _Newname) external aboveCostLevel(2, _resourceId) onlyOwnerOf (_resourceId){
resources[_resourceId].name = _Newname;
}
//change the qualityUnits
function changeQualityUnits(uint _resourceId, uint _newQualityUnits) external aboveCostLevel(2, _resourceId) onlyOwnerOf (_resourceId) {
resources[_resourceId].qualityUnits = _newQualityUnits;
}
//grabe the resources ! array of it.
function getTheResourceToOwner( address _owner) external view returns (uint[] memory) {
uint[] memory result = new uint[](ownerResourceGain[_owner]);
uint counter = 0;
//loop
for (uint i = 0; i < resources.length; i++) {
if (resourceToOwner[i] == _owner){
result[counter] = i;
counter++;
}
}
return result;
}
}
contract ResourceUp is ResourceHelper {
uint randNonce = 0;
uint resourceUpProba = 70;
/*function randMod(uint _modulus) internal returns(uint) {
randNonce++;
return uint(keccak256( (abi.encodePacked(now, msg.sender,randNonce))) % uint(_modulus));
}*/
function setUp(uint _resourceId, uint _targetId) external onlyOwnerOf(_resourceId) {
Resource storage myResource = resources[_resourceId];
Resource storage anotherResource = resources[_targetId];
uint rand = 100;
if (rand <= resourceUpProba) {
myResource.stockGain++;
myResource.rarity++;
anotherResource.stockLoss++;
refinedAndMultiply(_resourceId, anotherResource.quality, "resource");
} else {
myResource.stockLoss++;
anotherResource.stockGain++;
triggerCooldown(myResource);
}
}
}
contract Harvest is ResourceUp, ERC721 {
using SafeMath for uint256;
mapping (uint => address) resourceApproval;
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ownerResourceGain[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return resourceToOwner[_tokenId];
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownerResourceGain[_to] = ownerResourceGain[_to].add(1);
ownerResourceGain[msg.sender] = ownerResourceGain[msg.sender].sub(1);
resourceToOwner[_tokenId] = _to;
_transfer(_from, _to, _tokenId);
}
function transferTo(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
transferTo(_to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
resourceApproval[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function harvest(uint256 _tokenId) public {
require(resourceApproval[_tokenId] == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
}
My depoy js file :
const Harvest = artifacts.require("Harvest");
module.exports = function(deployer) {
deployer.deploy(Harvest)
};
The output of the truffle migrate
* Import abstractions into the '.sol' file that uses them instead of deploying them separately.
* Contracts that inherit an abstraction must implement all its method signatures exactly.
* A contract that only implements part of an inherited abstraction is also considered abstract.
verions :
Truffle v5.1.9 (core: 5.1.9)
Solidity v0.5.16 (solc-js)
Node v10.16.3
Web3.js v1.2.1
Thank you for your support.
The problem is with Ownable constructor
constructor (Ownable) public {
owner = msg.sender;
}
It is defined in a way that it will receive one parameter of type Ownable.
To fix the error define it without any input parameter:
constructor() public {
owner = msg.sender;
}
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.
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.