Solidity.

Post

Share your knowledge.

0x4ec1...6edc.
Jun 29, 2023
Expert Q&A

The Trade functionality in my Solidity Contract is not Working

The Trade functionality in my Solidity Contract is not Working. Giving Error "Unknown error: "Execution reverted with reason: Pancake: TRANSFER_FAILED.". Try increasing your slippage tolerance.". It is Deployed in BSC Testnet. I am adding liquidity through PCS Router from BSCScan. Here is my code and it is under Development/ testing:

  '''
     pragma solidity >=0.8.4 < 0.8.20;
    
    interface IFactory {
        function createPair(address tokenA, address tokenB) external returns (address pair);
   }

interface IRouter {
function factory() external pure returns (address);

function WETH() external pure returns (address);

function addLiquidityETH(
    address token,
    uint256 amountTokenDesired,
    uint256 amountTokenMin,
    uint256 amountETHMin,
    address to,
    uint256 deadline
)
    external
    payable
    returns (
        uint256 amountToken,
        uint256 amountETH,
        uint256 liquidity
    );

function swapExactTokensForETHSupportingFeeOnTransferTokens(
    uint256 amountIn,
    uint256 amountOutMin,
    address[] calldata path,
    address to,
    uint256 deadline
) external;

function swapExactETHForTokensSupportingFeeOnTransferTokens(
    uint amountOutMin,
    address[] calldata path,
    address to,
    uint deadline
) external payable;

  }

contract MyToken {


string public name = "ClastroCompetes";
string public symbol = "Clastio";
uint8 public decimals = 18;
uint256 public totalSupply = 10_000_000 * (10 ** decimals);

address public Owner;

mapping(address => uint256) public balanceOf;
mapping (address => mapping(address => uint256)) public Allowance;
uint256 private BUY_TAX_RATE = 5;   // 1% buy tax
uint256 private SELL_TAX_RATE = 10;  // 2% sell tax
IRouter router;
address pair;

address[] WhiteListed;

address public taxAddress = 0xE89145e7d9a9b6a4BCacb82659b8bE0e0fFC70A0;  // Address where the tax amount will be deposited

event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event TransferOwnerShip(address indexed from,address indexed to);
event Approval(address indexed owner, address indexed spender, uint value);

////////////////////////////////////////////////////

constructor(address routerAddress) { 
   
    IRouter _router = IRouter(routerAddress);
    address _pair = IFactory(_router.factory()).createPair(address(this), _router.WETH()); //create a pair with BNB
    router = _router;
    pair = _pair;

    balanceOf[msg.sender] = totalSupply;
    Owner = msg.sender;
    WhiteListed.push(Owner);
}


////////////////////////////////////////////////////

modifier onlyOwner
{
    require(msg.sender == Owner, "Only Owner can call this Function");
    _;
}

modifier Whitelisted
{
    bool isWhiteListed = false;

    for(uint256 i = 0; i < WhiteListed.length; i++)
    {
        if(WhiteListed[i] == msg.sender)
        {
            isWhiteListed = true;
            break;
        }
    }

    require(isWhiteListed == true, "Can't Call by this Address");
    _;
}

////////////////////////////////////////////////////
fallback() external payable {}
receive() external payable {}

function withdrawNativeToken(uint256 amount) public onlyOwner{
   address msgSender = msg.sender;
   require(amount <= address(this).balance, string(abi.encodePacked("Not Sufficient Balance in the Contract. Current Balance is ", address(this).balance)));
   (bool success, ) = msgSender.call{value: amount}("");
   require(success, "Error Withdrawing...");
}

function swapTokensForBNB(uint256 tokenAmount) public Whitelisted {
    // generate the pair path of token -> weth
    address[] memory path = new address[](2);
    path[0] = address(this);
    path[1] = router.WETH();

    Approve(address(router), tokenAmount);

    // make the swap
    try router.swapExactTokensForETHSupportingFeeOnTransferTokens(
        tokenAmount,
        0, // accept any amount of ETH
        path,
        address(this),
        block.timestamp
    ) {} catch {
        return;
    }
}

function addLiquidity(uint256 tokenAmount, uint256 BNBamount) public Whitelisted payable 
{

    Approve(address(router), tokenAmount);

    try router.addLiquidityETH{value: BNBamount}(
        address(this),
        tokenAmount,
        0,
        0,
        Owner,
        block.timestamp + 1000
    ){} catch {return;}
}

function WhiteListAddress(address Address_to_be_White_listed) public onlyOwner returns(string memory)
{
  WhiteListed.push(Address_to_be_White_listed);
  return("Succesfully WhiteListed");
}

function CheckWhiteListedAddress(address See_Address_to_be_WhiteListed) public view returns(bool isWhiteListed)
{
    isWhiteListed = false;

    for(uint256 i = 0; i < WhiteListed.length; i++)
    {
        if(WhiteListed[i] == See_Address_to_be_WhiteListed)
        {
            isWhiteListed = true;
            break;
        }
    }

    return isWhiteListed;
}

//**********************************************

function transferFrom(address from, address to, uint256 value) public
{
   require(balanceOf[from] >= value, 'balance too low');     //checks that balance of the address is greater or equal to value of the functiom
    require(Allowance[from][msg.sender] >= value, 'allowance too low');

    uint256 _value = value * (10 ** decimals);

    balanceOf[to] += _value;     //adds the amt of token to the recieve address
    balanceOf[from] -= _value;   //subs the amt of token from the sender address
    emit Transfer(from, to, _value); //call the event
}

function transfer(address to, uint256 value) public {
    require(balanceOf[msg.sender] >= value, "Insufficient balance");
   
    uint256 tax = 0;
    uint256 _value = value * (10 ** decimals);
                                
    Approve(address(router), _value);

    if (msg.sender != address(this) && to == address(this)) {
        // Sell transaction
        tax = ( _value * SELL_TAX_RATE) / 100;
        balanceOf[taxAddress] += tax ;
    }
    if (msg.sender == address(this)) {
        // Buy transaction
        tax = ( _value * BUY_TAX_RATE) / 100;
        balanceOf[taxAddress] += tax ;
    } 

    uint256 tokensToTransfer = _value - tax;
    
    balanceOf[msg.sender] -= _value;
    balanceOf[to] += tokensToTransfer;
    
    emit Transfer(msg.sender, to, tokensToTransfer);
    
    if (tax >= 0) {
        emit Transfer(msg.sender, taxAddress, tax);
    }
}

function Approve(address spender, uint256 value)  public
{
   Allowance[msg.sender][spender] = value;
   emit Approval(msg.sender, spender, value);
}

function burn(uint256 value) external onlyOwner{
    require(balanceOf[msg.sender] >= value, "Insufficient balance");
    
    uint256 _value = value * (10 ** decimals);

    balanceOf[msg.sender] -= _value;
    totalSupply -= _value;
    
    emit Burn(msg.sender, _value);
    emit Transfer(msg.sender, address(0), _value);
}

function TransferOwnership(address _owner) public onlyOwner
{
    emit TransferOwnerShip(Owner, _owner);
    Owner = _owner;
}

function RenounceOwner() public onlyOwner
{
    emit TransferOwnerShip(Owner, address(0));
    TransferOwnership(address(0));

}

  }

'''

  • Smart Contract
  • Solidity
0
2
Share
Comments
.

Answers

2
Daniel.
Jun 29 2023, 18:55

Have you tried calling swapExactTokensForETHSupportingFeeOnTransferTokens on the router directly instead of swapTokensForBNB on your contract?

Take a look at the implementation of swapExactTokensForETHSupportingFeeOnTransferTokens - https://github.com/pancakeswap/pancake-swap-periphery/blob/d769a6d136b74fde82502ec2f9334acc1afc0732/contracts/PancakeRouter.sol#L379

function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    )
        external
        virtual
        override
        ensure(deadline)
    {
        require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH');
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amountIn
        );
        _swapSupportingFeeOnTransferTokens(path, address(this));
        uint amountOut = IERC20(WETH).balanceOf(address(this));
        require(amountOut >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).withdraw(amountOut);
        TransferHelper.safeTransferETH(to, amountOut);
    }

Notice that it tries to transfer tokens from msg.sender. For the call to swapExactTokensForETHSupportingFeeOnTransferTokens msg.sender is your contract and not the address that invokes swapTokensForBNB.

0
Best Answer
Comments
.
0x4ec1...6edc.
Jun 30 2023, 07:42

Thanks, Daniel for Replying. I am not calling the "SwapExactTokensforBNB' directly from my Contract. I am just trying to Trade my token on PancakeSwap Website. It is giving the Error "Unknown error: "Execution reverted with reason: Pancake: TRANSFER_FAILED.". Try increasing your slippage tolerance." Please let me know if you have any idea to resolve it. Kind Regards.

Do you know the answer?

Please log in and share it.

We use cookies to ensure you get the best experience on our website.
More info