1

Since eth does not have a contract address, how does one allow a contract to spend it. For example - I put in a swap request - 10 eth for its amount in usdt for example - could the contract spend my entire balance (if malicious)?

2 Answers 2

0

You can't allow a smart contract to spend your ETH by default, but it is possible to implement a wallet smart contract that allows other smart contracts to spend the ETH held on your behalf if you grant them enough allowance. Here's an example of what that could look like:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;

contract Wallet {
    // balances[owner]
    mapping(address => uint256) public balances;

    // allowances[owner][spender]
    mapping(address => mapping(address => uint256)) public allowances;

    function approve(address spender, uint256 amount) external  {
        allowances[msg.sender][spender] = amount;
    }

    function transferFrom(address from, address to, uint256 amount) external {
        assert(allowances[from][msg.sender] >= amount);
        allowances[from][msg.sender] -= amount;
        balances[from] -= amount;
        balances[to] += amount;

    }

    function withdraw(uint256 amount) external  {
        payable(msg.sender).transfer(amount);
    }

    receive() external payable {
        balances[msg.sender] += msg.value;
    }
}
3
  • 3
    Worth mentioning that this is essentially what WETH is
    – natewelch_
    Sep 15, 2022 at 16:52
  • 1
    Yeah, just use WETH unless you have special requirements, surely
    – user253751
    Sep 15, 2022 at 21:46
  • 1
    Ye I understand how weth works... Was trying to understand how something like Uniswap swaps your eth since there are no allowances for eth
    – user106332
    Sep 16, 2022 at 7:39
0

I contract cannot spend all your balance, only the balance that you send to it.

If you have 100 eth in your wallet and you create a transaction with 10 eth and sign it and send it for the contract, then the contract will only be able to spend those 10 eths that are not yours anymore. The contract will not be able to spend your remaining 90 eth, it's not possible. Only the one holding your private key can spend it.

If you want to allow a contract to spend x amount of your eth, then you need to create a smart contract that will work as the middle man, receive your eth (the amount that you send it), and it should check if the sender requesting it is the contract you are allowing to spend it.

2
  • Isn't there a WETH token that does this already?
    – user253751
    Sep 15, 2022 at 21:46
  • My question is moreso directed at something like Uniswap... Swapping eth for usdt does not send that eth to the contract however the contract still facilitates the swap - this is what is confusing me
    – user106332
    Sep 16, 2022 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.