I got an error in solidity like "TypeError: "block.blockhash()" has been deprecated in favor of "blockhash()"" - solidity

I get gemini-doller contract code from etherscan through this link"https://etherscan.io/address/0x056fd409e1d7a124bd7017459dfea2f387b6d5cd#code" while test it in remix
i found some errors in line number 28 its like "TypeError: "block.blockhash()" has been deprecated in favor of "blockhash()"" can anyone please resolve it.
pragma solidity ^0.5.1;
/** #title A contract for generating unique identifiers
*
* #notice A contract that provides a identifier generation scheme,
* guaranteeing uniqueness across all contracts that inherit from it,
* as well as unpredictability of future identifiers.
*
* #dev This contract is intended to be inherited by any contract that
* implements the callback software pattern for cooperative custodianship.
*
* #author Gemini Trust Company, LLC
*/
contract LockRequestable {
// MEMBERS
/// #notice the count of all invocations of `generateLockId`.
uint256 public lockRequestCount;
// CONSTRUCTOR
constructor() public {
lockRequestCount = 0;
}
// FUNCTIONS
function generateLockId() internal returns (bytes32 lockId) {
return keccak256(abi.encodePacked(block.blockhash(block.number - 1), address(this), ++lockRequestCount));
}
}
contract CustodianUpgradeable is LockRequestable {
// TYPES
/// #dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// #dev The address of the account or contract that acts as the custodian.
address public custodian;
/// #dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian);
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0));
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != 0x0000000000000000000000000000000000000000);
return changeRequest.proposedNew;
}
/// #dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// #dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
}
contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// #dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// #dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// #dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl));
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0));
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0));
return ERC20Impl(changeRequest.proposedNew);
}
/// #dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
/// #dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
}
contract ERC20Interface {
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// #notice Returns the name of the token.
string public name;
/// #notice Returns the symbol of the token.
string public symbol;
/// #notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** #notice Returns the total token supply.
*
* #return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** #dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** #dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** #notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* #dev Will fire the `Approval` event.
*
* #return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** #notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* #return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
}
contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// #dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// #dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// #dev The reference to the store.
ERC20Store public erc20Store;
/// #dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
bytes32 public sweepMsg;
mapping (address => bool) public sweptSet;
/// #dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != 0x0000000000000000000000000000000000000000);
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** #notice Core logic of the `increaseApproval` function.
*
* #dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* #param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** #notice Core logic of the `decreaseApproval` function.
*
* #dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* #param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0)); // disallow unspendable approvals
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject ‘null’ results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** #notice Burns the specified value from the sender's balance.
*
* #dev Sender's balanced is subtracted by the amount they wish to burn.
*
* #param _value The amount to burn.
*
* #return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0));
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i=0; i<numSignatures; ++i) {
address from = ecrecover(sweepMsg, _vs[i], _rs[i], _ss[i]);
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0));
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i=0; i<lenFroms; ++i) {
address from = _froms[i];
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0)); // ensure burn is the cannonical transfer to 0x0
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
// METHODS (ERC20 sub interface impl.)
/// #notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// #notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// #notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
// EVENTS
/// #dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// #dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
}
contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// #dev The total token supply.
uint256 public totalSupply;
/// #dev The mapping of balances.
mapping (address => uint256) public balances;
/// #dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
}
if you want more information regarding it please feel free to put comment below
Thankyou:)

I got an error in solidity like “TypeError: ”block.blockhash()“ has been deprecated in favor of ”blockhash()“”
It is because new changes in new compiler version '0.5.0'.
Just remove block from block.blockhash(block.number-1) like this :
blockhash(block.number-1).

I got an error in solidity like “Operator != not compatible with types address and int_const 0”
Because you are trying to compare address type with uint Type, See
here require(changeRequest.proposedNew != 0); in this line
proposedNew is address variable and 0 is uint.
If you want to correct it
try require(changeRequest.proposedNew !=
0x0000000000000000000000000000000000000000);
and also in require(_sweeper !=
0x0000000000000000000000000000000000000000);.

Related

Solidty smart contract blacklist function

Trying to merge 2 smart contracts and having some issues. I just want to move my blacklist function from an old contract to my new one. I'll include the line of code. I need adding as I've done the rest just can't find where to put it. In the old contract it was under the _transfer function however my new code doesn't have this exact function.
I'll include the full contract below. the line of code I need adding to make the blacklist function work is:
require(!_isBlackList[from] && !_isBlackList[to],"You are black listed by Owner");
And it needs to sit somewhere in the following code:
// SPDX-License-Identifier: unlicensed
pragma solidity ^0.8.6;
/**
* BEP20 standard interface
*/
interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
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);
}
abstract contract Ownable {
address internal owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(address _owner) {
owner =_owner;
}
modifier onlyOwner() {
require(isOwner(msg.sender), "!OWNER"); _;
}
function isOwner(address account) public view returns (bool) {
return account == owner;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
function Ownershiplock(uint256 time) public virtual onlyOwner {
_previousOwner = owner;
owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(owner, address(0));
}
function Ownershipunlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked");
emit OwnershipTransferred(owner, _previousOwner);
owner = _previousOwner;
}
}
/**
* Router Interfaces
*/
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
function factory() external pure returns (address);
function WWBNB() 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 addLiquidityWBNB(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountWBNBMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountWBNB, uint liquidity);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactWBNBForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForWBNBSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/**
* Contract Code
*/
contract ZelBNB is IBEP20, Ownable {
address WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
string constant _name = "ZelBNB"; //
string constant _symbol = "ZBNB"; //
uint8 constant _decimals = 9;
uint256 _totalSupply = 1 * 10**6 * 10**_decimals;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) public isFeeExempt;
mapping (address => bool) public isTxLimitExempt;
mapping (address => bool) private _isBlackList;
// Detailed Fees
uint256 public liquidityFee;
uint256 public devFee;
uint256 public marketingFee;
uint256 public buybackFee;
uint256 public totalFee;
uint256 public BuyliquidityFee = 3;
uint256 public BuydevFee = 0;
uint256 public BuymarketingFee = 5;
uint256 public BuybuybackFee = 2;
uint256 public BuytotalFee = BuyliquidityFee + BuydevFee + BuymarketingFee + BuybuybackFee;
uint256 public SellliquidityFee = 3;
uint256 public SelldevFee = 0;
uint256 public SellmarketingFee = 5;
uint256 public SellbuybackFee = 2;
uint256 public SelltotalFee = SellliquidityFee + SelldevFee + SellmarketingFee + SellbuybackFee;
// Max wallet & Transaction
uint256 public _maxBuyTxAmount = _totalSupply / (100) * (2); // 1%
uint256 public _maxSellTxAmount = _totalSupply / (100) * (2); // 1%
uint256 public _maxWalletToken = _totalSupply / (100) * (2); // 1%
// Fees receivers
address public autoLiquidityReceiver = 0xF3902ad7681324F723CE91760B252B4bDf594517;
address public marketingFeeReceiver = 0x9d01b64acdbef3E0DB64B2f4bFC092a68218b2F3;
address public devFeeReceiver = 0xF3902ad7681324F723CE91760B252B4bDf594517;
address public buybackFeeReceiver = 0x9d01b64acdbef3E0DB64B2f4bFC092a68218b2F3;
IDEXRouter public router;
address public pair;
bool public swapEnabled = true;
uint256 public swapThreshold = _totalSupply / 1000 * 1; // 0.1%
uint256 public maxSwapSize = _totalSupply / 100 * 1; //1%
uint256 public tokensToSell;
bool inSwap;
modifier swapping() { inSwap = true; _; inSwap = false; }
constructor () Ownable(msg.sender) {
router = IDEXRouter(0xD99D1c33F9fC3444f8101754aBC46c52416550D1);
pair = IDEXFactory(router.factory()).createPair(WBNB, address(this));
_allowances[address(this)][address(router)] = type(uint256).max;
isFeeExempt[msg.sender] = true;
isTxLimitExempt[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
receive() external payable { }
function totalSupply() external view override returns (uint256) { return _totalSupply; }
function decimals() external pure override returns (uint8) { return _decimals; }
function symbol() external pure override returns (string memory) { return _symbol; }
function name() external pure override returns (string memory) { return _name; }
function getOwner() external view override returns (address) { return owner; }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, type(uint256).max);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(inSwap){ return _basicTransfer(sender, recipient, amount); }
if(sender == pair){
buyFees();
}
if(recipient == pair){
sellFees();
}
if (sender != owner && recipient != address(this) && recipient != address(DEAD) && recipient != pair || isTxLimitExempt[recipient]){
uint256 heldTokens = balanceOf(recipient);
require((heldTokens + amount) <= _maxWalletToken,"Total Holding is currently limited, you can not buy that much.");
}
// Checks max transaction limit
if(sender == pair){
require(amount <= _maxBuyTxAmount || isTxLimitExempt[recipient], "TX Limit Exceeded");
}
if(recipient == pair){
require(amount <= _maxSellTxAmount || isTxLimitExempt[sender], "TX Limit Exceeded");
}
//Exchange tokens
if(shouldSwapBack()){ swapBack(); }
_balances[sender] = _balances[sender] - amount;
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(recipient, amount) : amount;
_balances[recipient] = _balances[recipient] + amountReceived;
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender] - amount;
_balances[recipient] = _balances[recipient] + (amount);
emit Transfer(sender, recipient, amount);
return true;
}
// Internal Functions
function buyFees() internal{
liquidityFee = BuyliquidityFee;
devFee = BuydevFee;
marketingFee = BuymarketingFee;
buybackFee = BuybuybackFee;
totalFee = BuytotalFee;
}
function sellFees() internal{
liquidityFee = SellliquidityFee;
devFee = SelldevFee;
marketingFee = SellmarketingFee;
buybackFee = SellbuybackFee;
totalFee = SelltotalFee;
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function takeFee(address sender, uint256 amount) internal returns (uint256) {
uint256 feeAmount = amount / 100 * (totalFee);
_balances[address(this)] = _balances[address(this)] + (feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount - (feeAmount);
}
function shouldSwapBack() internal view returns (bool) {
return msg.sender != pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
function swapBack() internal swapping {
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxSwapSize){
tokensToSell = maxSwapSize;
}
else{
tokensToSell = contractTokenBalance;
}
uint256 amountToLiquify = tokensToSell / (totalFee) * (liquidityFee) / (2);
uint256 amountToSwap = tokensToSell - (amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WBNB;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForWBNBSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountBNB = address(this).balance - (balanceBefore);
uint256 totalBNBFee = totalFee - (liquidityFee / (2));
uint256 amountBNBLiquidity = amountBNB * (liquidityFee) / (totalBNBFee) / (2);
uint256 amountBNBbuyback = amountBNB * (buybackFee) / (totalBNBFee);
uint256 amountBNBMarketing = amountBNB * (marketingFee) / (totalBNBFee);
uint256 amountBNBDev = amountBNB - amountBNBLiquidity - amountBNBbuyback - amountBNBMarketing;
(bool MarketingSuccess,) = payable(marketingFeeReceiver).call{value: amountBNBMarketing, gas: 500}("");
require(MarketingSuccess, "receiver rejected WBNB transfer");
(bool buybackSuccess,) = payable(buybackFeeReceiver).call{value: amountBNBbuyback, gas: 500}("");
require(buybackSuccess, "receiver rejected WBNB transfer");
(bool devSuccess,) = payable(devFeeReceiver).call{value: amountBNBDev, gas: 500}("");
require(devSuccess, "receiver rejected WBNB transfer");
addLiquidity(amountToLiquify, amountBNBLiquidity);
}
function addLiquidity(uint256 tokenAmount, uint256 BNBAmount) private {
if(tokenAmount > 0){
router.addLiquidityWBNB{value: BNBAmount}(
address(this),
tokenAmount,
0,
0,
autoLiquidityReceiver,
block.timestamp
);
emit AutoLiquify(BNBAmount, tokenAmount);
}
}
// External Functions
function checkSwapThreshold() external view returns (uint256) {
return swapThreshold;
}
function checkMaxWalletToken() external view returns (uint256) {
return _maxWalletToken;
}
function checkMaxBuyTxAmount() external view returns (uint256) {
return _maxBuyTxAmount;
}
function checkMaxSellTxAmount() external view returns (uint256) {
return _maxSellTxAmount;
}
function isNotInSwap() external view returns (bool) {
return !inSwap;
}
// Only Owner allowed
function setBuyFees(uint256 _liquidityFee, uint256 _buybackFee, uint256 _marketingFee, uint256 _devFee) external onlyOwner {
BuyliquidityFee = _liquidityFee;
BuybuybackFee = _buybackFee;
BuymarketingFee = _marketingFee;
BuydevFee = _devFee;
BuytotalFee = _liquidityFee + (_buybackFee) + (_marketingFee) + (_devFee);
}
function setSellFees(uint256 _liquidityFee, uint256 _buybackFee, uint256 _marketingFee, uint256 _devFee) external onlyOwner {
SellliquidityFee = _liquidityFee;
SellbuybackFee = _buybackFee;
SellmarketingFee = _marketingFee;
SelldevFee = _devFee;
SelltotalFee = _liquidityFee + (_buybackFee) + (_marketingFee) + (_devFee);
}
function setFeeReceivers(address _autoLiquidityReceiver, address _marketingFeeReceiver, address _buybackFeeReceiver, address _devFeeReceiver) external onlyOwner {
autoLiquidityReceiver = _autoLiquidityReceiver;
marketingFeeReceiver = _marketingFeeReceiver;
buybackFeeReceiver = _buybackFeeReceiver;
devFeeReceiver = _devFeeReceiver;
}
function setSwapBackSettings(bool _enabled, uint256 _percentage_min_base10000, uint256 _percentage_max_base10000) external onlyOwner {
swapEnabled = _enabled;
swapThreshold = _totalSupply / (10000) * (_percentage_min_base10000);
maxSwapSize = _totalSupply / (10000) * (_percentage_max_base10000);
}
function setIsFeeExempt(address holder, bool exempt) external onlyOwner {
isFeeExempt[holder] = exempt;
}
function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner {
isTxLimitExempt[holder] = exempt;
}
function setMaxWalletPercent_base1000(uint256 maxWallPercent_base1000) external onlyOwner {
_maxWalletToken = _totalSupply / (1000) * (maxWallPercent_base1000);
}
function setMaxBuyTxPercent_base1000(uint256 maxBuyTXPercentage_base1000) external onlyOwner {
_maxBuyTxAmount = _totalSupply / (1000) * (maxBuyTXPercentage_base1000);
}
function setMaxSellTxPercent_base1000(uint256 maxSellTXPercentage_base1000) external onlyOwner {
_maxSellTxAmount = _totalSupply / (1000) * (maxSellTXPercentage_base1000);
}
function isBlackList(address Account)external view returns(bool){
return _isBlackList[Account];
}
function SetBlackListAccountStatus(address Account, bool status)external onlyOwner(){
_isBlackList[Account] = status;
}
// Stuck Balances Functions
function rescueToken(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return IBEP20(tokenAddress).transfer(msg.sender, tokens);
}
function clearStuckBalance(uint256 amountPercentage) external onlyOwner {
uint256 amountBNB = address(this).balance;
payable(msg.sender).transfer(amountBNB * amountPercentage / 100);
}
event AutoLiquify(uint256 amountBNB, uint256 amountTokens);
}
any help would be great! thanks
GM there!
_transfer is an internal function provided by the ERC20 Openzeppelin library, you can override it in the contract and add your lines in the contract like this
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
require(!_isBlackList[from] && !_isBlackList[to],"You are black listed by Owner");
super._transfer(sender, recipient, amount);
}
Hope this helps, Cheers~

Solidity issues with transferFrom()

I'm only about a week into Solidity so please don't go easy on me. I'm writing a new token contract and am having issues using the transferFrom() function. I can do normal transfers and approve another address to spend funds but am unable to transfer from someone else's wallet (while approved).
Any help is appreciated!
Code:
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.12 <0.9.0;
interface IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, 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 from, address to, 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);
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
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 swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
contract TestContract is IERC20 {
uint256 public constant BUYFEE = 42069;//4.2069
uint256 public constant SELLFEE = 8008135;//8.008135
address public COMMUNITYWALLET = 0x761Eb6556c69B6484e2FDbd76C527cC4e3628Ae0;
uint8 public CTAX = 50;
uint8 public LTAX = 50;
uint8 public TTAX = 100;
uint256 public THRESHOLD;
string private _name = "Test";
string private _symbol = "TEST";
uint8 private _decimals = 18;
uint256 private _totalSupply= 1000000000 * 10 ** 18;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowance;
mapping(address => bool) private _isRouter;
mapping(address => bool) private _isExcluded;
address private _ownerAddress;
address private _dead = 0x000000000000000000000000000000000000dEaD;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
event SetTaxes(uint256 communityTax, uint256 liquidityTax);
event SetCommunityWallet(address communityWallet);
event ClearStuckEth(address communityWallet, uint256 ethCleared);
event ClearStuckTokens(address recipient, uint256 contractTokenBalance);
event Liquidate(uint256 ethForCommunity, uint256 ethForLiquidity, uint256 tokensForLiquidity);
event UpdateTokenThreshold(uint256 tokenThreshold);
event TransferOwnership(address oldOwner, address ownerAddress);
event AddToExcluded(address pAddress);
event RemoveFromExcluded(address pAddress);
constructor(uint8 pThresholdPercent) {
_ownerAddress = msg.sender;
_update(msg.sender, _totalSupply);
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
_isRouter[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true;
_isExcluded[_ownerAddress] = true;
_updateTokenThreshold(pThresholdPercent);
}
receive() external payable {}
modifier protected() {
require(msg.sender == _ownerAddress);
_;
}
function transfer(address pTo, uint256 pToken) external returns (bool) {
_transfer(msg.sender, pTo, pToken);
return true;
}
function approve(address pSpender, uint256 pToken) external returns (bool) {
_approve(msg.sender, pSpender, pToken);
return true;
}
function transferFrom(address pSpender, address pRecipient, uint256 pToken) external returns (bool) {
_transfer(pSpender, pRecipient, pToken);
_approve(pSpender, msg.sender, _allowance[pSpender][msg.sender] - pToken);
return true;
}
function totalSupply() external view returns (uint256) {return _totalSupply;}
function decimals() external view returns (uint8) {return _decimals;}
function symbol() external view returns (string memory) {return _symbol;}
function name() external view returns (string memory) {return _name;}
function getOwner() external view returns (address) { return _ownerAddress; }
function balanceOf(address pAddress) external view returns (uint256) {return _balance[pAddress];}
function allowance(address pOwner, address pSpender) external view returns (uint256) {return _allowance[pOwner][pSpender];}
function _transfer(address pFrom, address pTo, uint256 pToken) private {
require(pFrom != address(0));
require(pTo != address(0));
require(pToken > 0);
require(pToken <= _balance[pFrom]);
uint256 fee = 0;
if(_balance[address(this)] >= THRESHOLD) { _liquidate(); }
if(!_isExcluded[pFrom] && !_isExcluded[pTo]) {
if(_isRouter[pFrom]) {
fee = _calculateBuyTax(pToken);//Tax on buys
_balance[address(this)] += fee;
}
else if(_isRouter[pTo]) {
fee = _calculateSellTax(pToken);//Tax on sells
_balance[address(this)] += fee;
}
}
_balance[msg.sender] -= pToken;
_balance[pTo] += (pToken - fee);
emit Transfer(msg.sender, pTo, pToken);
}
function _approve(address pOwner, address pSpender, uint256 pToken) private {
require(pOwner != address(0));
require(pSpender != address(0));
_allowance[pOwner][pSpender] = pToken;
emit Approval(pOwner, pSpender, pToken);
}
function _update(address pRecipient, uint256 pToken) private {
require(pRecipient != address(0));
_balance[pRecipient] += pToken;
emit Transfer(address(0), pRecipient, pToken);
}
function _liquidate() private {
uint256 tokensForLiquidity = (THRESHOLD * LTAX / 100);
uint256 amountToSwap = THRESHOLD - tokensForLiquidity;
_swapTokensForEth(amountToSwap);
uint256 totalEthBalance = address(this).balance;
uint256 ethForCommunity = totalEthBalance * CTAX / 100;
uint256 ethForLiquidity = totalEthBalance - ethForCommunity;
if (totalEthBalance > 0) {
payable(COMMUNITYWALLET).call{value:ethForCommunity};
}
if (tokensForLiquidity > 0) {
_addLiquidity(tokensForLiquidity, ethForLiquidity);
_balance[_dead] += tokensForLiquidity;
}
_balance[address(this)] -= THRESHOLD;
emit Liquidate(ethForCommunity, ethForLiquidity, tokensForLiquidity);
}
function _swapTokensForEth(uint256 pToken) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), pToken);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
pToken,
0,
path,
address(this),
block.timestamp + 15
);
}
function _addLiquidity(uint256 pToken, uint256 pEth) private returns (bool) {
_approve(address(this), address(uniswapV2Router), pToken);
uniswapV2Router.addLiquidityETH{value: pEth}(address(this), pToken, 0, 0, _dead, block.timestamp + 15);
return true;
}
function _calculateBuyTax(uint256 pToken) private pure returns (uint256) {
return (pToken * BUYFEE) / 10**6;
}
function _calculateSellTax(uint256 pToken) private pure returns (uint256) {
return (pToken * SELLFEE) / 10**8;
}
function _updateTokenThreshold(uint256 pThresholdPercent) private {
THRESHOLD = _totalSupply * pThresholdPercent / 100;
emit UpdateTokenThreshold(THRESHOLD);
}
function setTaxes(uint8 pCommunityTax, uint8 pLiquidityTax) external protected {
CTAX = pCommunityTax;
LTAX = pLiquidityTax;
TTAX = CTAX + LTAX;
require(TTAX >= 0 && TTAX <= 100);
emit SetTaxes(CTAX, LTAX);
}
function setCommunityWallet(address payable pCommunityWallet) external protected {
COMMUNITYWALLET = pCommunityWallet;
emit SetCommunityWallet(COMMUNITYWALLET);
}
function transferOwnership(address pOwner) external protected {
address oldOwner = _ownerAddress;
_ownerAddress = pOwner;
emit TransferOwnership(oldOwner, _ownerAddress);
}
function clearStuckEth() external protected {
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0){
payable(COMMUNITYWALLET).call{value:contractETHBalance};
}
emit ClearStuckEth(COMMUNITYWALLET, contractETHBalance);
}
function clearStuckTokens() external protected {
uint256 contractTokenBalance = _balance[address(this)];
if(contractTokenBalance > 0) {
_balance[COMMUNITYWALLET] += _balance[address(this)];
_balance[address(this)] = 0;
}
emit ClearStuckTokens(COMMUNITYWALLET, contractTokenBalance);
}
function manualLiquidate() external protected {
_liquidate();
}
function updateTokenThreshold(uint256 pThresholdPercent) external protected returns (bool) {
_updateTokenThreshold(pThresholdPercent);
return true;
}
function addToExcluded(address pAddress) external protected {
_isExcluded[pAddress] = true;
emit AddToExcluded(pAddress);
}
function removeFromExcluded(address pAddress) external protected {
_isExcluded[pAddress] = false;
emit RemoveFromExcluded(pAddress);
}
}
this was a small mistake and it is the correct code that is to be changed,
function transferFrom(address pSpender, address pRecipient, uint256 pToken) external returns (bool) {
_allowance[from][pSpender] = safeSub(_allowance[pSpender][msg.sender], pToken);
_transfer(pSpender, pRecipient, pToken);
return true;
}
function _approve(address pOwner, address pSpender, uint256 pToken) public returns (bool success) {
_allowance[pOwner][pSpender] = tokens;
emit Approval(pOwner, pSpender, tokens);
return true;
}
if this is still having issue, do share me the contract link.
I was able to transfer after switching browsers and it may have just been a caching issue. This contract has been updated since and works. Thanks.

Remix error The transaction has been reverted to the initial state

I am testing my smart contract on remix. While testing Start Airdrop function is running successfully but as I approach getAirrop function I receive error :
transact to getAirdrop errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
my smart contract code is :
/**
*Submitted for verification at BscScan.com on 2021-05-29
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.10;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TokenERC20 is ERC20Interface, Owned{
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "SHIB";
name = "Shiba";
decimals = 0;
_totalSupply = 1000000000000000;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function () external payable {
revert();
}
}
contract Shiba is TokenERC20 {
uint256 public aSBlock;
uint256 public aEBlock;
uint256 public aCap;
uint256 public aTot;
uint256 public aAmt;
uint256 public sSBlock;
uint256 public sEBlock;
uint256 public sCap;
uint256 public sTot;
uint256 public sChunk;
uint256 public sPrice;
function getAirdrop(address _refer) public returns (bool success){
require(aSBlock <= block.number && block.number <= aEBlock);
require(aTot < aCap || aCap == 0);
aTot ++;
if(msg.sender != _refer && balanceOf(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){
balances[address(this)] = balances[address(this)].sub(aAmt / 1);
balances[_refer] = balances[_refer].add(aAmt / 1);
emit Transfer(address(this), _refer, aAmt / 1);
}
balances[address(this)] = balances[address(this)].sub(aAmt);
balances[msg.sender] = balances[msg.sender].add(aAmt);
emit Transfer(address(this), msg.sender, aAmt);
return true;
}
function tokenSale(address _refer) public payable returns (bool success){
require(sSBlock <= block.number && block.number <= sEBlock);
require(sTot < sCap || sCap == 0);
uint256 _eth = msg.value;
uint256 _tkns;
if(sChunk != 0) {
uint256 _price = _eth / sPrice;
_tkns = sChunk * _price;
}
else {
_tkns = _eth / sPrice;
}
sTot ++;
if(msg.sender != _refer && balanceOf(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){
balances[address(this)] = balances[address(this)].sub(_tkns / 2);
balances[_refer] = balances[_refer].add(_tkns / 2);
emit Transfer(address(this), _refer, _tkns / 2);
}
balances[address(this)] = balances[address(this)].sub(_tkns);
balances[msg.sender] = balances[msg.sender].add(_tkns);
emit Transfer(address(this), msg.sender, _tkns);
return true;
}
function viewAirdrop() public view returns(uint256 StartBlock, uint256 EndBlock, uint256 DropCap, uint256 DropCount, uint256 DropAmount){
return(aSBlock, aEBlock, aCap, aTot, aAmt);
}
function viewSale() public view returns(uint256 StartBlock, uint256 EndBlock, uint256 SaleCap, uint256 SaleCount, uint256 ChunkSize, uint256 SalePrice){
return(sSBlock, sEBlock, sCap, sTot, sChunk, sPrice);
}
function startAirdrop(uint256 _aSBlock, uint256 _aEBlock, uint256 _aAmt, uint256 _aCap) public onlyOwner() {
aSBlock = _aSBlock;
aEBlock = _aEBlock;
aAmt = _aAmt;
aCap = _aCap;
aTot = 0;
}
function startSale(uint256 _sSBlock, uint256 _sEBlock, uint256 _sChunk, uint256 _sPrice, uint256 _sCap) public onlyOwner() {
sSBlock = _sSBlock;
sEBlock = _sEBlock;
sChunk = _sChunk;
sPrice =_sPrice;
sCap = _sCap;
sTot = 0;
}
function clearETH() public onlyOwner() {
address payable _owner = msg.sender;
_owner.transfer(address(this).balance);
}
function() external payable {
}
}
require(aSBlock <= block.number && block.number <= aEBlock);
This condition passes only if the block number is between aSBlock (value 6,666,666) and aEBlock (value 9,999,999).
The current block number on the BSC mainnet is around 8,000,000, so it would pass on the mainnet.
However, Remix EVM emulator uses its own block numbers - starting from #1 when you load the EVM emulator (by opening the IDE) and incrementing with each transaction (i.e. automining).
Unless you've made almost 6.7 million transactions in your current Remix instance, it will fail the condition.
Then you also have a logical error in your test scenario (or in the getContract() function - I'm not sure), where you're trying to subtract a balance but the address doesn't have enough balance.
balances[address(this)] = balances[address(this)].sub(aAmt);
balances[address(this)] is 0
aAmt is 50,000,000,000,000
This throws an exception in the SafeMath sub() method - otherwise it would cause an integer underflow.
Note: address(this) is address of the contract.
Solution:
Use much lower aSBlock value (e.g. 1) when you're testing this contract in the Remix EVM emulator.
Fund your contract balance (balances[address(this)]) with enough tokens (more than aAmt) before executing the getAirdrop() function. Or change the getAirdrop() logic so that it doesn't subtract from the contract balance. Depends on your goal.

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.