5

经常在solidity合约方法的参数里看到的“bytes _data”,究竟是做什么用的?

 3 years ago
source link: https://learnblockchain.cn/question/2121
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
经常在solidity合约方法的参数里看到的“bytes _data”,究竟是做什么用的?

经常在solidity合约方法的参数里看到的“bytes _data”,究竟是做什么用的?

举几个简单的例子:

比如在ERC20合约里,曾经有过这样的方法:

function approveAndCall(
address _spender, 
uint256 _value, 
bytes memory _extraData)
public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);

    if (approve(_spender, _value)) {
        spender.receiveApproval(msg.sender, _value, address(this),  _extraData);
        return true;
    }
}

以及ERC1155合约里,有这样的方法:

function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external

这两个方法中都出现了bytes参数,请问这个参数一般是干嘛用的,以及,如果要用这些接口,但是不需要额外加bytes参数,可否直接传值为0?

最佳答案 2天前

在你例子里,你可以把 bytes 理解为一个泛型参数。因为bytes 可以转化为各种不同的基本类型。

例如,在 safeTransferFrom 中,你可以在转账的时候把一个附加的信息给目标方,这个附加的信息可以一个单品 ID(uint), 或者是一个推荐人地址。

一个高级的用法时:bytes 包含了一个函数选择器编码及参数, 这样可以通过这个参数去实现动态调用其他的方法。

Tiny熊 - 布道者
擅长:智能合约,以太坊 | 采纳率 41% | 回答于 2天前

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK