scam token - cannot be sold/swapped - smartcontracts

Recently I bought a token from pancakeswap. Looks, like it's scammed - it's new, there are only buy operations, and no sell operations.
And I also cannot swap it back.
I'm providing its contract source code and would be happy if someone explains why it cannot be sold:
#
# Panoramix v4 Oct 2019
# Decompiled source of bsc:0xEF45178482b5868668D4ae8f2556D4F23c4Ffe51
#
# Let's make the world open source
#
def storage:
owner is addr at storage 0
newOwner is addr at storage 1
symbol is array of uint256 at storage 2
name is array of uint256 at storage 3
decimals is uint8 at storage 4
stor5 is uint256 at storage 5
unknown1ee59f20Address is addr at storage 6
balanceOf is mapping of uint256 at storage 7
allowance is mapping of uint256 at storage 8
def name(): # not payable
return name[0 len name.length]
def unknown1ee59f20(): # not payable
return unknown1ee59f20Address
def decimals(): # not payable
return decimals
def balanceOf(address _owner): # not payable
require calldata.size - 4 >= 32
return balanceOf[addr(_owner)]
def owner(): # not payable
return owner
def symbol(): # not payable
return symbol[0 len symbol.length]
def newOwner(): # not payable
return newOwner
def allowance(address _owner, address _spender): # not payable
require calldata.size - 4 >= 64
return allowance[addr(_owner)][addr(_spender)]
#
# Regular functions
#
def _fallback() payable: # default function
revert
def totalSupply(): # not payable
require balanceOf[0] <= stor5
return (stor5 - balanceOf[0])
def transferOwnership(address _newOwner): # not payable
require calldata.size - 4 >= 32
require caller == owner
newOwner = _newOwner
def unknown81f4f399(addr _param1): # not payable
require calldata.size - 4 >= 32
require caller == owner
unknown1ee59f20Address = _param1
def acceptOwnership(): # not payable
require caller == newOwner
log OwnershipTransferred(
address previousOwner=owner,
address newOwner=newOwner)
owner = newOwner
newOwner = 0
def approve(address _spender, uint256 _value): # not payable
require calldata.size - 4 >= 64
allowance[caller][addr(_spender)] = _value
log Approval(
address owner=_value,
address spender=caller,
uint256 value=_spender)
return 1
def transfer(address _to, uint256 _value): # not payable
require calldata.size - 4 >= 64
if unknown1ee59f20Address == _to:
revert with 0, 'Please wait'
require _value <= balanceOf[caller]
balanceOf[caller] -= _value
require _value + balanceOf[_to] >= balanceOf[_to]
balanceOf[addr(_to)] = _value + balanceOf[_to]
log Transfer(
address from=_value,
address to=caller,
uint256 value=_to)
return 1
def approveAndCall(address _spender, uint256 _amount, bytes _extraData): # not payable
require calldata.size - 4 >= 96
require _extraData <= 4294967296
require _extraData + 36 <= calldata.size
require _extraData.length <= 4294967296 and _extraData + _extraData.length + 36 <= calldata.size
allowance[caller][addr(_spender)] = _amount
mem[ceil32(_extraData.length) + 128] = _amount
log Approval(address owner, address spender, uint256 value):
Mask(8 * -ceil32(_extraData.length) + _extraData.length + 32, 0, 0),
mem[_extraData.length + 160 len -_extraData.length + ceil32(_extraData.length)],
caller,
_spender,
require ext_code.size(_spender)
call _spender with:
gas gas_remaining wei
args caller, _amount, this.address, Array(len=_extraData.length, data=_extraData[all])
if not ext_call.success:
revert with ext_call.return_data[0 len return_data.size]
return 0, 1
def transferFrom(address _from, address _to, uint256 _value): # not payable
require calldata.size - 4 >= 96
if not _from:
if unknown1ee59f20Address == _to:
revert with 0, 'Please wait'
else:
if unknown1ee59f20Address:
if unknown1ee59f20Address == _to:
revert with 0, 'Please wait'
else:
unknown1ee59f20Address = _to
require _value <= balanceOf[addr(_from)]
balanceOf[addr(_from)] -= _value
require _value <= allowance[addr(_from)][caller]
allowance[addr(_from)][caller] -= _value
require _value + balanceOf[addr(_to)] >= balanceOf[addr(_to)]
balanceOf[addr(_to)] += _value
log Transfer(
address from=_value,
address to=_from,
uint256 value=_to)
return 1
I would greately appreciate for any help to swap it back and return back my investment.

This contract blacklists the last address that sent tokens from a contract.
What does it mean?
This means if you buy tokens from a DeFi contract pool (like Pancake swap / uniswap, 1Inch, etc) you cannot sell through them immediately (transfer the tokens) because the pool address will be blacklisted.
If you want to sell that tokens, you can either:
Sell them in a different Defi exchange (if it was Pancakeswap, make it uniswap or 1inc, etc.).
Or create a contract that hold the tokens for you and then release them. This will (not reccomended).
How they do it?
The contract contains a variable that stores an address.
It reverts all operations from that address.
It the last address that he received tokens with TransferFrom:
def storage:
...
unknown1ee59f20Address is addr at storage 6
...
When someone buy tokens from a pool like PancakeSwap / Uniswap it calls the transferFrom method it records the last address that received the tokens.
def transferFrom(address _from, address _to, uint256 _value): # not payable
require calldata.size - 4 >= 96
if not _from:
if unknown1ee59f20Address == _to:
revert with 0, 'Please wait'
else:
if unknown1ee59f20Address:
if unknown1ee59f20Address == _to:
revert with 0, 'Please wait'
else:
unknown1ee59f20Address = _to # <-- Address Blacklisted HERE !!!!
Since this contract stores just one addess globally, using a different contract will overwrite this variable.

Related

Transfer Eth through smart contract to other account?

In the below code eth will be transferred in the form of Wei by default, but I want the amount will transfer in the form of Ether, how can I do that?
function (uint amount) public payable {
someaddress.transfer(amount);
}
Wei is the smallest unit of Ether, specifically 1 ETH == 1,000,000,000,000,000,000 (or 1e18) wei.
The transfer() function always accepts the amount in wei. So if you want to pass just 1 as the input param, meaning that you want to send 1 full ETH, you can multiply the value by 1e18 effectively converting ETH to wei.
function (uint ethAmount) public payable {
uint weiAmount = ethAmount * 1e18;
someaddress.transfer(weiAmount);
}
Note: There's also the ether global unit, but in the current Solidity version (0.8), this can be used only in combination with number literals - not with variables.
uint weiAmount = 1 ether; // ok
uint weiAmount = ethAmount ether; // syntax error

Implementing a Tax Feature in an ERC20 token

Good day Everyone, I am trying to implement a tax feature in an ERC20 token.
I successfully implemented something similar to a project that involved the creation of a TRC20 token using the code below as a reference:
pragma solidity ^0.6.0;
contract TransfertTokenAndPercentageToTargetAddress{
// pay 1% of all transactions to target address
address payable target = TUEtmARJ2m147RDJ5hy37mhZhEqx2Fnv8r; // I converted the tron address, I didn't use it as shown
// state variables for your token to track balances and to test
mapping (address => uint) public balanceOf;
uint public totalSupply;
// create a token and assign all the tokens to the creator to test
constructor(uint _totalSupply) public {
totalSupply = _totalSupply;
balanceOf[msg.sender] = totalSupply;
}
// the token transfer function with the addition of a 1% share that
// goes to the target address specified above
function transfer(address _to, uint amount) public {
// calculate the share of tokens for your target address
uint shareForX = amount/100;
// save the previous balance of the sender for later assertion
// verify that all works as intended
uint senderBalance = balanceOf[msg.sender];
// check the sender actually has enough tokens to transfer with function
// modifier
require(senderBalance >= amount, 'Not enough balance');
// reduce senders balance first to prevent the sender from sending more
// than he owns by submitting multiple transactions
balanceOf[msg.sender] -= amount;
// store the previous balance of the receiver for later assertion
// verify that all works as intended
uint receiverBalance = balanceOf[_to];
// add the amount of tokens to the receiver but deduct the share for the
// target address
balanceOf[_to] += amount-shareForX;
// add the share to the target address
balanceOf[target] += shareForX;
// check that everything works as intended, specifically checking that
// the sum of tokens in all accounts is the same before and after
// the transaction.
assert(balanceOf[msg.sender] + balanceOf[_to] + shareForX ==
senderBalance + receiverBalance);
}
}
Then I tried to follow the same approach for an ERC20 token using the template from openzeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC20
The following code shows the result of the modification:
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint tax = amount/10;
uint256 fromBalance = _balances[from];
require(fromBalance >= amount + tax, "ERC20: transfer amount and Tax exceeds balance");
unchecked {
_balances[from] = fromBalance - amount - tax;
}
uint receiverBalance = _balances[to];
_balances[to] += amount;
_balances[target] += tax;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
// assert(_balances[from] + _balances[to] + tax == fromBalance + receiverBalance);
}
The token was successfully minted but the transfer function won't work. Any suggestions are highly appreciated.

Solidity swap and liquify BUSD instead of BNB

When there are fees, normally contracts send tokens or BNB to wallets (i.e. marketing wallet) and auto add liquidity (swapandliquify) in BNB. I am attempting to replace BNB for both with BUSD. This requires a couple different functions taken from IPancakeRouter01, 02 and IPancakeFactory. Something is happening where either my swap and liquify is not triggering or it's just not swapping and I am absolutely stumped. Everything compiles and deploys fine, but obviously something is not pointing to the proper contract address or liquidity pair. My _transfer function is all good, I am sure of it. I am going to post the relevant parts of my code related to this issue.
//BUSD Contract Address
address constant public BUSD = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56;
IPancakeRouter02 _pancakeRouter = IPancakeRouter02(_pancakeRouterAddress);
// Create a pancake pair for this new token
pancakePair = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), BUSD);
// set the rest of the contract variables
pancakeRouter = _pancakeRouter;
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 totalFees = _buyLiquidityFee + _sellLiquidityFee + _buyMarketingFee + _sellMarketingFee + _buyWhaleBuybackFee + _sellWhaleBuybackFee;
uint256 _totalMarketingFee = _buyMarketingFee + _sellMarketingFee;
uint256 marketingPercent = _totalMarketingFee.div(totalFees);
uint256 marketingQuota = marketingPercent.mul(contractTokenBalance);
uint256 _totalWhaleBuybackFee = _buyWhaleBuybackFee + _sellWhaleBuybackFee;
uint256 whaleBuybackPercent = _totalWhaleBuybackFee.div(totalFees);
uint256 whaleBuybackQuota = whaleBuybackPercent.mul(contractTokenBalance);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
swapTokensForBNB(marketingQuota);
swapBNBForBUSD(address(this).balance);
transferOutBUSD(marketingWallet, address(this).balance.sub(initialBalance));
//transferOutBNB(marketingWallet, address(this).balance.sub(initialBalance));
uint256 initialBalance2 = address(this).balance;
swapTokensForBNB(whaleBuybackQuota);
transferOutBUSD(whaleBuybackWallet, address(this).balance.sub(initialBalance2));
//transferOutBNB(whaleBuybackWallet, address(this).balance.sub(initialBalance2));
// split the contract balance into halves
uint256 initialBalanceAfterUtility = address(this).balance;
uint256 half = initialBalanceAfterUtility.div(2);
uint256 otherHalf = initialBalanceAfterUtility.sub(half);
swapTokensForBNB(half);
swapBNBForBUSD(address(this).balance);
uint256 newBalance = address(this).balance.sub(initialBalanceAfterUtility);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the pancake pair path of token -> wbnb
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pancakeRouter.WETH();
_approve(address(this), address(pancakeRouter), tokenAmount);
// make the swap
pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp
);
}
function transferOutBNB(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
function swapBNBForBUSD(uint256 tokenAmount) private{
_approve(address(this), address(pancakeRouter), tokenAmount);
address[] memory path = new address[](2);
path[0] = pancakeRouter.WETH();
path[1] = BUSD; //pancakeRouter.BUSD();
pancakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function transferOutBUSD(address payable recipient, uint256 amount) private{
recipient.transfer(amount);
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(pancakeRouter), tokenAmount);
// add the liquidity
pancakeRouter.addLiquidity( // the return values of function not will are handled
address(this),
BUSD,
tokenAmount,
bnbAmount,
0,
0,
owner(),
block.timestamp
);
}
Instead of this,
//BUSD Contract Address
address constant public BUSD = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56;
Try this,
IERC20 public immutable BUSD =
IERC20(0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7);
a) For constant variables, the value has to be fixed at compile-time
b) For immutable, the value can be assigned at construction time.

Token balance shows 0 in rinkeby etherscan

I wrote a erc20 token contract and I deployed in rinkeby tetstnet. I given the toatl supply=1000000 but my token balance is showing 0 in metamask. How can I get the tokens and tell me the way to get the tokens. Below is my contract
pragma solidity ^0.5.0;
contract COCOTOKEN {
string public constant symbol = "COCO";
string public constant name = "COCOTOKEN";
uint8 public constant decimals = 18;
uint256 totalSupply = 1000000;
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor() public{
owner = msg.sender;
balances[owner] = totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) public returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
and the the deployed contract address is "0xc3384a37d041b99d437734a80e88b39e0efa630d".Why token balance is showing 0.In rinkeby etehrscan it showing liks following
On-chain Token Attributes Check Result:
Total Supply = 0
Name = COCOTOKEN
Symbol = COCO
Decimals = 18
ERC-165 Interface = {Not Available}
Implements ERC-721 = {Not Available}.
Can any one please tell me how to add tokens?
Because that is very small unit of your ether. just transfer for ether from faucet.
or just transfer in wei unit 1000000000000000000 then you will be see 1 ether on your screen.
You need to increase your totalSupply of with 18 digits of the decimal. for more explanation on decimal and totalSupply check this Answer.
The value that you assegned at the totalSupply is too low,you can check the erc20 token standard here. In the constructor they set the totalSupply like in the code below:
constructor() public {
symbol = "FIXED";
name = "Example Fixed Supply Token";
decimals = 18;
_totalSupply = 1000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
The total supply you are giving is like totalsupply = 1000000 * 10^-18 which would come to 0.0000000000001 so obviously it will show as zero when you try to perform any transaction.
Here is a complete implementation using OpenZeppelin which sets total supply to 1000000 and assigns the tokens to you at contract initialization.
pragma solidity 0.5.2;
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
contract TokenMock is ERC20
{
constructor () public {
_mint(msg.sender, 1000000);
}
}

How to receive ether in my token contract to transfer them automatically to payers

What I want to achieve when someone sends ether to my token address then automatically equivalent amount of token (I am also setting token price manually) must be sent back. The problem is I am not able to send ether to the token address. I am learning the code from ethereum.org . I copied the code from there , some little changes made .
Here's what I tried
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
/**
* #title SafeMath
* #dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 dividetoken
) public {
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = dividetoken;
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* #param _to The address of the recipient
* #param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* #param _from The address of the sender
* #param _to The address of the recipient
* #param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* #param _spender The address authorized to spend
* #param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* #param _spender The address authorized to spend
* #param _value the max amount they can spend
* #param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* #param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* #param _from the address of the sender
* #param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract mintableToken is owned, TokenERC20 {
using SafeMath for uint256;
uint256 public sellPrice;
uint256 public buyPrice;
uint256 public cap; //Hard Cap Amount
string public version ; //Version standard. Just an arbitrary versioning scheme.
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function mintableToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimals,
uint256 _cap,
string _version
) TokenERC20(initialSupply, tokenName, tokenSymbol,decimals) public {
require(_cap > 0);
cap = _cap;
version=_version;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// #notice Create `mintedAmount` tokens and send it to `target`
/// #param target Address to receive the tokens
/// #param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
require(totalSupply.add(mintedAmount) <= cap);
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// #notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// #param target Address to be frozen
/// #param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// #notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// #param newSellPrice Price the users can sell to the contract
/// #param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// #notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// #notice Sell `amount` tokens to contract
/// #param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
}
// TestCoin
contract TestCoin is mintableToken(0,"TestCoin","TEC",4,100000000,"Ver-2.0"){
function () payable public{
mintableToken.buy();
}
}
What to do next, or if some problem is there in the code . I am totally stucked for 3 days. Please if someone can contribute his valuable time to see into the code, it will be a great help.
Thanks in advance
Edit
When I am trying to send ether to the Token address the following error is showing
(error_22) Could not estimate gas. There are not enough funds in the
account, or the receiving contract address would throw an error. Feel
free to manually set the gas and proceed.
EDIT -2
The problem above is solved i.e. I am able to send ether to the token contract now . Below is the fully changed code (I will upgrade it to implement more conditional statements, I only want now that the equivalent amount of token should be reward back to the ether spender), This time it is not mintable token , it is fixed supply token
pragma solidity ^0.4.4;
contract Token {
/// #return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// #param _owner The address from which the balance will be retrieved
/// #return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// #notice send `_value` token to `_to` from `msg.sender`
/// #param _to The address of the recipient
/// #param _value The amount of token to be transferred
/// #return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// #notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// #param _from The address of the sender
/// #param _to The address of the recipient
/// #param _value The amount of token to be transferred
/// #return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// #notice `msg.sender` approves `_addr` to spend `_value` tokens
/// #param _spender The address of the account able to transfer the tokens
/// #param _value The amount of wei to be approved for transfer
/// #return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// #param _owner The address of the account owning tokens
/// #param _spender The address of the account able to transfer the tokens
/// #return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
//name this contract whatever you'd like
contract TestCoin is StandardToken {
function () payable public {
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function TestCoin(
) {
balances[msg.sender] = 1000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 1000000000000; // Update total supply (100000 for example)
name = "TestCoin"; // Set the name for display purposes
decimals = 4; // Amount of decimals for display purposes
symbol = "BPC"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
}
You need to understand how the tokens works in general and what token actually is. Token is just a smart-contract which keeps information about balances (mapping address => uint). So it just keeps the amount of tokens held by specified address. Nothing more. Another thing you need to know is fallback function(the one without the name). In your case it is empty.
function () payable public {
}
What do you need to do is the following modifications:
function () payable public {
balances[msg.sender] += msg.value;
}
It also looks like that you are trying to break Single Responsibility principle and add token sale functionality directly to your token contract what is not a good idea in general. I would recommend you to check out my repository and look at how it can be organized to keep things separated. To make it more easy to understand, I've added some tests to the tests folder, so feel free to read the tests to understand how everything works and whats an expected behaviour of the contracts.