ERC20: transfer amount exceeds balance from other contracts on local chain but works from TOKEN.sol

I can transfer ERC20 coins using the owner contract but when I try to do it from another contract it throws ERC20: transfer amount exceeds balance

TOKEN.sol

//SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;


import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/**
 * @title OtcTestToken1
 * @custom:security-contact jacek@degen.tips
 */
contract TOKEN is ERC20 {
    /**
     * @dev Total number of tokens in circulation
     */
    uint256 public constant TOKEN_INITIAL_SUPPLY = 1_000_000_000;

    constructor() ERC20("OtcTestToken1", "OtcTestToken1") {
        _mint(msg.sender, TOKEN_INITIAL_SUPPLY * 10 ** decimals());
        _mint(0xbC5FD5e787edF69751Be195Be87DDB1c904bB4FA, TOKEN_INITIAL_SUPPLY * 10 ** decimals());

    }
}

SendRecieveTokens.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./TOKEN.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract SendRecieveTokens {
    using SafeERC20 for IERC20;

    address public tokenAddress = 0x922D6956C99E12DFeB3224DEA977D0939758A1Fe;
    function sendTokens(address _recipient, uint256 _amount) external  {
        require(_recipient != address(0), "Invalid recipient address");
        require(_amount > 0, "Invalid amount");
        //IERC20(tokenAddress).safeIncreaseAllowance(msg.sender,_amount);
        //IERC20(tokenAddress).safeTransferFrom(msg.sender,_recipient, _amount);
        //TOKEN token = TOKEN(tokenAddress);
        IERC20(tokenAddress).safeTransfer(_recipient, _amount);
    }


}
1 Like

Does the second contract hold enough tokens?

1 Like

Thanks for the reply, makes sense, we can't add tokens to the contract but I added the allowance @FreezyEx

I tried this

        IERC20(tokenAddress).safeIncreaseAllowance(address(this),_amount);
        IERC20(tokenAddress).safeTransferFrom(msg.sender,_recipient, _amount);

safeIncreaseAllowance(address of the second contract, _amount)

but I'm getting this error

WriteOnlyFunctionForm.tsx:handleWrite ~ error ContractFunctionExecutionError: The contract function "sendTokens" reverted for the following reason:
ERC20: insufficient allowance

Contract Call:
  address:   0xf4B146FbA71F41E0592668ffbF264F1D186b2Ca8
  function:  sendTokens(address _recipient, uint256 _amount)
  args:                (0xe1927e8939aAec6d54B8C7c55333b713404dfF1d, 1)
  sender:    0xbC5FD5e787edF69751Be195Be87DDB1c904bB4FA

1 Like

You can't get allowance from the second contract. The only way is to manually give allowance to this second contract using your wallet

1 Like

How can I change this code to let users transfer tokens to one another?