简体   繁体   中英

How is an ERC20 token transfer signed in its smart contract

I'm new to ethereum and I've been trying to understand ERC20 smart contracts.

This is the transfer function from the OpenZeppelin ERC20 smart contract.

function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
    _transfer(_msgSender(), recipient, amount);
    return true;
}


function _transfer(
    address sender,
    address recipient,
    uint256 amount
) internal virtual {
    require(sender != address(0), "ERC20: transfer from the zero address");
    require(recipient != address(0), "ERC20: transfer to the zero address");

    _beforeTokenTransfer(sender, recipient, amount);

    uint256 senderBalance = _balances[sender];
    require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
    unchecked {
        _balances[sender] = senderBalance - amount;
    }
    _balances[recipient] += amount;

    emit Transfer(sender, recipient, amount);

    _afterTokenTransfer(sender, recipient, amount);
}

By the looks of this, a caller can just pick any two addresses and, as long as the balances are enough, the tokens will transfer. But I know the transaction participants (at least the sender) need to sign. Can't figure out what I'm missing here for this to work.

There's an approve function as well, but it's similar where it just changes the values in an internal Hashmap without doing any cryptographic signature as far as I can tell.

the transaction participants (at least the sender) need to sign

Correct. The sender needs to sign the transaction with their private key in order to execute the public transfer() function (which invokes the internal _transfer() performing the actual balances settlement).

The signature is performed offchain, before the transaction is even broadcasted to the network and mined.

The contract function is executed during the mining process, but only the winning miner broadcasts the resulting state changes - the Transfer() event log, change of storage fields representing _balances[sender] and _balances[recipient] - to the rest of the network.

So you won't see the signature process in the Solidity code.

There's an approve function as well

That's used for approving another address to spend your tokens.

From the context, I'm assuming you've copy-pasted part of the OpenZeppelin ERC20 implementation. So here's a link to the code that they use to validate whether the sender is approved to spend someone else's tokens as part of the transferFrom() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM