Сообщение об ошибке Solidity при выполнении смарт-контракта: «Вызываемая функция должна быть оплачена, если вы отправляете значение»

Я пытаюсь развернуть тестовый контракт ERC777 НА REMIX IDE; но виртуальная машина выдает мне ошибку ниже, когда я пытаюсь заключить контракт

Ошибка виртуальной машины: вернуться. revert Транзакция была возвращена в исходное состояние. Примечание. Вызываемая функция подлежит оплате, если вы отправляете значение, а отправляемое значение должно быть меньше вашего текущего баланса. Отладьте транзакцию, чтобы получить дополнительную информацию.

Ниже приведены параметры, используемые для развертывания.

Параметры - Пусто

Заполненные параметры

Параметры: тестирование, TST, ["0xdD870fA1b7C4700F2BD7f44238821C26f7392148"], 10000

Не могли бы вы проверить мой код и сообщить, что было упущено.

// Файл: контракты \ open-zeppelin-contract \ token \ ERC777 \ ERC777.sol

pragma solidity ^0.5.0;

contract ERC777 is IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;

IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);

mapping(address => uint256) private _balances;

uint256 private _totalSupply;

string private _name;
string private _symbol;

// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024

// keccak256("ERC777TokensSender")
bytes32 constant private TOKENS_SENDER_INTERFACE_HASH =
    0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;

// keccak256("ERC777TokensRecipient")
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
    0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;

// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;

// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;

// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;

// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;

/**
 * @dev `defaultOperators` may be an empty array.
 */
constructor(
    string memory name,
    string memory symbol,
    address[] memory defaultOperators
) public {
    _name = name;
    _symbol = symbol;

    _defaultOperatorsArray = defaultOperators;
    for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
        _defaultOperators[_defaultOperatorsArray[i]] = true;
    }

    // register interfaces
    _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
    _erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}

/**
 * @dev See `IERC777.name`.
 */
function name() public view returns (string memory) {
    return _name;
}

/**
 * @dev See `IERC777.symbol`.
 */
function symbol() public view returns (string memory) {
    return _symbol;
}

/**
 * @dev See `ERC20Detailed.decimals`.
 *
 * Always returns 18, as per the
 * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
 */
function decimals() public pure returns (uint8) {
    return 18;
}

/**
 * @dev See `IERC777.granularity`.
 *
 * This implementation always returns `1`.
 */
function granularity() public view returns (uint256) {
    return 1;
}

/**
 * @dev See `IERC777.totalSupply`.
 */
function totalSupply() public view returns (uint256) {
    return _totalSupply;
}

/**
 * @dev Returns the amount of tokens owned by an account (`tokenHolder`).
 */
function balanceOf(address tokenHolder) public view returns (uint256) {
    return _balances[tokenHolder];
}

/**
 * @dev See `IERC777.send`.
 *
 * Also emits a `Transfer` event for ERC20 compatibility.
 */
function send(address recipient, uint256 amount, bytes calldata data) external {
    _send(msg.sender, msg.sender, recipient, amount, data, "", true);
}

/**
 * @dev See `IERC20.transfer`.
 *
 * Unlike `send`, `recipient` is _not_ required to implement the `tokensReceived`
 * interface if it is a contract.
 *
 * Also emits a `Sent` event.
 */
function transfer(address recipient, uint256 amount) external returns (bool) {
    require(recipient != address(0), "ERC777: transfer to the zero address");

    address from = msg.sender;

    _callTokensToSend(from, from, recipient, amount, "", "");

    _move(from, from, recipient, amount, "", "");

    _callTokensReceived(from, from, recipient, amount, "", "", false);

    return true;
}

/**
 * @dev See `IERC777.burn`.
 *
 * Also emits a `Transfer` event for ERC20 compatibility.
 */
function burn(uint256 amount, bytes calldata data) external {
    _burn(msg.sender, msg.sender, amount, data, "");
}

/**
 * @dev See `IERC777.isOperatorFor`.
 */
function isOperatorFor(
    address operator,
    address tokenHolder
) public view returns (bool) {
    return operator == tokenHolder ||
        (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
        _operators[tokenHolder][operator];
}

/**
 * @dev See `IERC777.authorizeOperator`.
 */
function authorizeOperator(address operator) external {
    require(msg.sender != operator, "ERC777: authorizing self as operator");

    if (_defaultOperators[operator]) {
        delete _revokedDefaultOperators[msg.sender][operator];
    } else {
        _operators[msg.sender][operator] = true;
    }

    emit AuthorizedOperator(operator, msg.sender);
}

/**
 * @dev See `IERC777.revokeOperator`.
 */
function revokeOperator(address operator) external {
    require(operator != msg.sender, "ERC777: revoking self as operator");

    if (_defaultOperators[operator]) {
        _revokedDefaultOperators[msg.sender][operator] = true;
    } else {
        delete _operators[msg.sender][operator];
    }

    emit RevokedOperator(operator, msg.sender);
}

/**
 * @dev See `IERC777.defaultOperators`.
 */
function defaultOperators() public view returns (address[] memory) {
    return _defaultOperatorsArray;
}

/**
 * @dev See `IERC777.operatorSend`.
 *
 * Emits `Sent` and `Transfer` events.
 */
function operatorSend(
    address sender,
    address recipient,
    uint256 amount,
    bytes calldata data,
    bytes calldata operatorData
)
external
{
    require(isOperatorFor(msg.sender, sender), "ERC777: caller is not an operator for holder");
    _send(msg.sender, sender, recipient, amount, data, operatorData, true);
}

/**
 * @dev See `IERC777.operatorBurn`.
 *
 * Emits `Burned` and `Transfer` events.
 */
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
    require(isOperatorFor(msg.sender, account), "ERC777: caller is not an operator for holder");
    _burn(msg.sender, account, amount, data, operatorData);
}

/**
 * @dev See `IERC20.allowance`.
 *
 * Note that operator and allowance concepts are orthogonal: operators may
 * not have allowance, and accounts with allowance may not be operators
 * themselves.
 */
function allowance(address holder, address spender) public view returns (uint256) {
    return _allowances[holder][spender];
}

/**
 * @dev See `IERC20.approve`.
 *
 * Note that accounts cannot have allowance issued by their operators.
 */
function approve(address spender, uint256 value) external returns (bool) {
    address holder = msg.sender;
    _approve(holder, spender, value);
    return true;
}

/**
* @dev See `IERC20.transferFrom`.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits `Sent`, `Transfer` and `Approval` events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
    require(recipient != address(0), "ERC777: transfer to the zero address");
    require(holder != address(0), "ERC777: transfer from the zero address");

    address spender = msg.sender;

    _callTokensToSend(spender, holder, recipient, amount, "", "");

    _move(spender, holder, recipient, amount, "", "");
    _approve(holder, spender, _allowances[holder][spender].sub(amount));

    _callTokensReceived(spender, holder, recipient, amount, "", "", false);

    return true;
}

/**
 * @dev Creates `amount` tokens and assigns them to `account`, increasing
 * the total supply.
 *
 * If a send hook is registered for `account`, the corresponding function
 * will be called with `operator`, `data` and `operatorData`.
 *
 * See `IERC777Sender` and `IERC777Recipient`.
 *
 * Emits `Minted` and `Transfer` events.
 *
 * Requirements
 *
 * - `account` cannot be the zero address.
 * - if `account` is a contract, it must implement the `tokensReceived`
 * interface.
 */
function _mint(
    address operator,
    address account,
    uint256 amount,
    bytes memory userData,
    bytes memory operatorData
)
internal
{
    require(account != address(0), "ERC777: mint to the zero address");

    // Update state variables
    _totalSupply = _totalSupply.add(amount);
    _balances[account] = _balances[account].add(amount);

    _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);

    emit Minted(operator, account, amount, userData, operatorData);
    emit Transfer(address(0), account, amount);
}

/**
 * @dev Send tokens
 * @param operator address operator requesting the transfer
 * @param from address token holder address
 * @param to address recipient address
 * @param amount uint256 amount of tokens to transfer
 * @param userData bytes extra information provided by the token holder (if any)
 * @param operatorData bytes extra information provided by the operator (if any)
 * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
 */
function _send(
    address operator,
    address from,
    address to,
    uint256 amount,
    bytes memory userData,
    bytes memory operatorData,
    bool requireReceptionAck
)
    private
{
    require(from != address(0), "ERC777: send from the zero address");
    require(to != address(0), "ERC777: send to the zero address");

    _callTokensToSend(operator, from, to, amount, userData, operatorData);

    _move(operator, from, to, amount, userData, operatorData);

    _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}

/**
 * @dev Burn tokens
 * @param operator address operator requesting the operation
 * @param from address token holder address
 * @param amount uint256 amount of tokens to burn
 * @param data bytes extra information provided by the token holder
 * @param operatorData bytes extra information provided by the operator (if any)
 */
function _burn(
    address operator,
    address from,
    uint256 amount,
    bytes memory data,
    bytes memory operatorData
)
    private
{
    require(from != address(0), "ERC777: burn from the zero address");

    _callTokensToSend(operator, from, address(0), amount, data, operatorData);

    // Update state variables
    _totalSupply = _totalSupply.sub(amount);
    _balances[from] = _balances[from].sub(amount);

    emit Burned(operator, from, amount, data, operatorData);
    emit Transfer(from, address(0), amount);
}

function _move(
    address operator,
    address from,
    address to,
    uint256 amount,
    bytes memory userData,
    bytes memory operatorData
)
    private
{
    _balances[from] = _balances[from].sub(amount);
    _balances[to] = _balances[to].add(amount);

    emit Sent(operator, from, to, amount, userData, operatorData);
    emit Transfer(from, to, amount);
}

function _approve(address holder, address spender, uint256 value) private {
    // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is
    // currently unnecessary.
    //require(holder != address(0), "ERC777: approve from the zero address");
    require(spender != address(0), "ERC777: approve to the zero address");

    _allowances[holder][spender] = value;
    emit Approval(holder, spender, value);
}

/**
 * @dev Call from.tokensToSend() if the interface is registered
 * @param operator address operator requesting the transfer
 * @param from address token holder address
 * @param to address recipient address
 * @param amount uint256 amount of tokens to transfer
 * @param userData bytes extra information provided by the token holder (if any)
 * @param operatorData bytes extra information provided by the operator (if any)
 */
function _callTokensToSend(
    address operator,
    address from,
    address to,
    uint256 amount,
    bytes memory userData,
    bytes memory operatorData
)
    private
{
    address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
    if (implementer != address(0)) {
        IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
    }
}

/**
 * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
 * tokensReceived() was not registered for the recipient
 * @param operator address operator requesting the transfer
 * @param from address token holder address
 * @param to address recipient address
 * @param amount uint256 amount of tokens to transfer
 * @param userData bytes extra information provided by the token holder (if any)
 * @param operatorData bytes extra information provided by the operator (if any)
 * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
 */
function _callTokensReceived(
    address operator,
    address from,
    address to,
    uint256 amount,
    bytes memory userData,
    bytes memory operatorData,
    bool requireReceptionAck
)
    private
{
    address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
    if (implementer != address(0)) {
        IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
    } else if (requireReceptionAck) {
        require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
    }
}
}

// Файл: TestToken.sol

pragma solidity ^0.5.0;

contract TestToken is ERC777 {

constructor(
  string memory name,
  string memory symbol,
  address[] memory defaultOperators,
  uint256 totalSupply
)
public payable ERC777(name, symbol, defaultOperators)
{
  // mint new tokens to address that deploys contract
  _mint(msg.sender, msg.sender, totalSupply, "", "");
}
}

person gussy_88    schedule 12.11.2019    source источник


Ответы (1)


Эта строка вызвала ошибку:

_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));

И вы инициируете _erc1820 этой строкой:

IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);

Убедитесь, что вы развернули ERC1820Registry контракт на 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 на виртуальной машине.

person StillFantasy    schedule 12.11.2019
comment
Спасибо за Ваш ответ; Я считаю, что ERC1820Registry развернут. вы можете просмотреть весь контракт здесь pastebin.com/54YjKvRz, но ничего не изменится @StillFantasy - person gussy_88; 12.11.2019
comment
@ gussy_88 Привет, у меня отлично работает. Вы уверены, что erc1820Registry развернут на виртуальной машине? И если вы закрыли браузер раньше или обновили его, вам нужно будет повторно развернуть контракт снова, потому что remix каждый раз предоставляет вам новую виртуальную машину. - person StillFantasy; 12.11.2019
comment
что вы делаете, что его развернули; сам по себе это абстрактный контракт, поэтому его нельзя развернуть до развертывания основного контракта. не могли бы вы уточнить, пожалуйста, @StillFantasy - person gussy_88; 12.11.2019
comment
@ gussy_88 Я нашел код ERC1820Registry на Github. Я развернул его, а затем заменил 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 в вашем коде новым адресом контракта. После этого ваш контракт может быть развернут без ошибок. - person StillFantasy; 12.11.2019
comment
Я думаю, вы что-то неправильно поняли, ваш контракт не развертывается ERC1820Registry. Эта строка: IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); означает загрузку контракта реестра по этому адресу. - person StillFantasy; 12.11.2019
comment
можешь уточнить, как его развернуть? поскольку я впервые имею дело с ERC1820; я должен разделить его и сначала развернуть? ИЛИ что нужно сделать перед заключением основного контракта? @StillFantasy - person gussy_88; 12.11.2019
comment
@ gussy_88 скопируйте и вставьте этот код в другой файл, разверните это, получите его адрес, замените 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 этим адресом в вашем основном контракте - person StillFantasy; 12.11.2019
comment
Виноват; я полностью упустил вашу точку зрения; я уже сделал это самостоятельно; Я просто пропустил один из ваших комментариев, поэтому запутался. в любом случае; Я сделал это, и теперь я получаю то, что ниже не имеет смысла. создание TestToken с ошибкой: выполнение транзакции завершилось неудачно и при статусе транзакции 0x0 Транзакция добыта, но выполнение не удалось @StillFantasy - person gussy_88; 12.11.2019
comment
@ gussy_88 Закончился бензин? - person StillFantasy; 12.11.2019
comment
Видимо да; спасибо за подсказку. Развернуто! @StillFantasy - person gussy_88; 12.11.2019
comment
@ gussy_88 Нет проблем. Буду признателен, если вы примете мой ответ, поставив галочку - person StillFantasy; 12.11.2019
comment
@StillFantasy, как мы можем развернуть erc1820Registry на виртуальной машине, например, чтобы развернуть ее на ремиксной виртуальной машине? - person Marko Blazekovic; 15.10.2020
comment
@MarkoBlazekovic Просто разверните github.com/0xjac/ERC1820/blob/master/ контракты / - person StillFantasy; 15.10.2020
comment
@StillFantasy, но мне нужно развернуть его на адрес 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24, иначе мне нужно изменить также другой контракт, где он жестко запрограммирован, что должно означать, что я также должен развернуть этот github.com/OpenZeppelin/openzeppelin-contracts/blob/master/ с измененным адресом на виртуальную машину JS после развертывания erc1820 а затем импортируйте тот, который я развернул, а не тот, что был на github. Правильно? - person Marko Blazekovic; 16.10.2020
comment
@MarkoBlazekovic Да, я думаю, что в виртуальной машине единственный способ - развернуть новый и заменить жестко запрограммированный адрес на новый - person StillFantasy; 16.10.2020