ERC20代币中的msg.sender、from和spender有什么区别?

What is the difference between msg.sender, from and spender in ERC20 tokens?

我的合同

contract Token{
    string public name = "Dhruv";
    string public symbol = "DhruvToken";
    uint256 public decimals = 18;
    uint256 public totalSupply;

    mapping(address => uint) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    constructor() public{
        totalSupply = 1000000 * (10 ** decimals);
        balanceOf[msg.sender] = totalSupply;
    }

    //events
    event Transfer(address from, address to, uint256 value);
    event Approve(address indexed from, address indexed to, uint256 indexed value);

    function transfer(address _to, uint256 _value) public returns (bool success){
        require(balanceOf[msg.sender] >= _value);
        _transfer(msg.sender, _to, _value);
        return true;
    }

    //internal function can be accessed only within the smart contract
    function _transfer(address _from, address _to, uint256 _value)  internal{
        require(_to != address(0));
        balanceOf[_from] = balanceOf[_from] - _value;
        balanceOf[_to] = balanceOf[_to] + _value;
        emit Transfer(_from, _to, _value);
    }

    // approve the tokens
    function approve(address _spender, uint256 _value) public returns (bool success){
        require(_spender != address(0));
        allowance[msg.sender][_spender] = _value;
        emit Approve(msg.sender, _spender, _value);
        return true;

    }

    function transferFrom(address _from, address _to, uint256 _value)  public returns (bool success){
        // require(balanceOf[_from] >= _value);
        allowance[_from][msg.sender] =  allowance[_from][msg.sender] - _value;
        _transfer(_from, _to, _value);
        return true;
    }
}

调用函数

token.transferFrom(deployer, receiver, amount, { from: exchange })
token.approve(exchange, amount, { from: deployer });
token.allowance(deployer, exchange);

我的疑惑

请回答我的疑惑,我研究了很多,但这个疑惑还没有解决

抱歉,我想我无法回答您所有的问题。 没有更多上下文,据我了解,该合约的主要目的是让某人允许另一个人代表他向潜在的第三方发送代币。

对我来说一个有效的场景是:

-“A”部署合约。

-"B" 调用 token.approve 函数(所以 B 是这里的 msg.sender)以允许 C 代表它花费一个值。 (假设这个例子:10)

allowance[B][C] = 10;

-"C" 调用 token.transferFrom 函数将一些 B 的令牌发送给 D。(假设是 6。注意现在 C 是 msg.sender)

allowance[B][C] =  allowance[B][C] - 6; (10-6 --> C still can send 4 tokens from now on)

现在有了这三个函数调用:

token.transferFrom(deployer, receiver, amount, { from: exchange })

allowance[deployer][exchange] =  allowance[deployer][exchange] - _value;

token.approve(exchange, amount, { from: deployer });

allowance[deployer][exhange] = _value;

token.allowance(deployer, exchange);

您刚刚检索到可以发送的更新代币数量。 这些函数调用的顺序对我来说不太有意义,因为我希望先调用 approve 函数。

关于花括号,我不熟悉这种语法。我比较习惯

token.transferFrom(deployer, receiver, amount).send( { from: exchange } )

在 javascript 中。无论如何,它只是一种使用键值对作为函数参数的方法。可能第一个参数(在大括号之外)是用于 Token 成员函数,而大括号之间的参数是我在上面作为示例给出的发送函数的等价物。

希望对您有所帮助。