Search code examples
ethereumerc20

Can a contract that is approuved spend my tokens even if I'm not the one initiating the transaction?


So let say I "approuve" contract A to spend X in the USDT contract. contract A can now spend my USDT up to X amount.

Usually when using uniswap or pancakeswap I am the one who trigger the swap method and then the contract spends my usdt.

But lets forget uniswap and pancake swap, in the case of a shady contract, if I approuved this contract to spend my USDT.

can it spend my usdt without ME initiating a transaction? could the contract creator call a method like "take_everybody_usdt" and then the contract would transfert everyone USDT to his wallet?

Thanks.


Solution

  • can it spend my usdt without ME initiating a transaction?

    Assuming you have already gave approval the contract address by sending a transaction executing the approve() function, then yes. A malicious contract can transfer your tokens even if you don't initiate the other transaction.

    In the example below, anyone can execute the function. It doesn't need to be executed by just you as the approver.

    pragma solidity 0.8;
    
    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
    
    contract MaliciousContract {
        function transferUsersTokensOut(IERC20 token, address from, address to, uint256 amount) public {
            // assuming `from` has approved `MaliciousContract` to spend their tokens,
            // this function transfers `amount` (<= the approved amount) of `from`'s tokens out
            token.transferFrom(from, to, amount);
        }
    }