Почему развертывание этого контракта стоит 1 Eth?

Truffle сообщает мне, что развертывание стоит 1 Eth. Это серьезно стоимость развертывания простого контракта (это мое первое развертывание в основной сети)? Или что-то еще происходит?

 mainnet: {
      provider: () =>
        new HDWalletProvider({
          mnemonic: { phrase: process.env.MNEMONIC },
          providerOrUrl: process.env.RPC_URL_1_WSS,
        }),
      network_id: 1, // Main's id
      from: process.env.DEPLOYERS_ADDRESS,
      gas: 4712388, // Gas limit used for deploys. Default is 4712388.
      gasPrice: 211000000000, //Gas price in Wei
      confirmations: 2, // # of confs to wait between deployments. (default: 0)
      timeoutBlocks: 200, // # of blocks before a deployment times out  (minimum/default: 50)
      skipDryRun: false, // Skip dry run before migrations? (default: false for public nets )
    },
  },
pragma solidity ^0.7.4;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";


contract EthMsg {
  address payable public owner;
  uint public messagesSentCount = 0;

  uint decimals = 8;
  uint scale = 10**decimals;

  uint public txtPriceUSD = 1.70 * 10**8;
  uint public txtPriceEth;

  using SafeMath for uint;

  AggregatorV3Interface internal priceFeed;

  event Spend(
    string textMsg,
    string recipient
  );
  event TextMsgError(
    string reason
  );

  constructor(address oracleAddress) {
    owner = msg.sender;
    priceFeed = AggregatorV3Interface(oracleAddress);
  }

  function sendTextMessage(
    string calldata textMsg,
    string calldata recipient
  ) external payable returns(bool) {

    (uint newTxtPriceEth,,) = this.pollTxtPrices();

    require(
      msg.value > newTxtPriceEth,
      'Please send the correct amount of ETH to make send a message'
    );

    emit Spend(textMsg, recipient);
    messagesSentCount += 1;
    return true;
  }

  function setTxtPrices(uint _txtPriceUSD) external ownerOnly() {
    (int price,) = getLatestPrice();
    uint ethPriceUSD = uint(price);

    txtPriceEth = scale.mul(_txtPriceUSD).div(ethPriceUSD);
    txtPriceUSD = _txtPriceUSD;
  }

  function pollTxtPrices() external view returns(uint, uint, uint) {
    (int price,) = getLatestPrice();

    uint newTxtPriceEth = scale.mul(txtPriceUSD).div(uint(price));

    return (newTxtPriceEth, txtPriceUSD, decimals);
  }

  function totalBalance() external view returns(uint) {
    return payable(address(this)).balance;
  }

  function withdrawFunds() external ownerOnly() {
    msg.sender.transfer(this.totalBalance());
  }

  function destroy() external ownerOnly() {
    selfdestruct(owner);
  }

  function getLatestPrice() public view returns (int, uint) {
    (
      ,int price,,,
    ) = priceFeed.latestRoundData();

    return (price, decimals);
  }

  function uintToWei(uint unum) private pure returns(uint p) {
    return unum * (1 wei);
  }

  modifier ownerOnly() {
    require(msg.sender == owner, 'only owner can call this');
    _;
  }
}

truffle migrate --network mainnet --reset

  Replacing 'Migrations'
   ----------------------

Error:  *** Deployment Failed ***

"Migrations" could not deploy due to insufficient funds
   * Account:  0x16c8CF300eRa61f6d8e7S201AB7163FCc6660f1d
   * Balance:  297068575000000000 wei
   * Message:  sender doesn't have enough funds to send tx. The upfront cost is: 994313868000000000 and the sender's account only has: 297068575000000000
   * Try:
      + Using an adequately funded account
      + If you are using a local Geth node, verify that your node is synced.

Первоначальная стоимость составляет 994313868000000000 Wei??

Это почти 1 ETH!


Ответы (2)

Во-первых, я не эксперт в этом, и вы вполне можете видеть меня новичком.

Эта первоначальная стоимость представляет собой цену газа * газ, который вы отправляете, который установлен в вашей конфигурации. Это не обязательно соответствует реальной стоимости. Важно то, сколько газа будет стоить ваше развертывание. Остальной отправленный газ не будет использован. В вашем случае вы готовы платить: 211000000000 вей за газ. Вы также заявляете, что готовы потратить не более 4712388 единиц газа. Затем в начале развертывания или пробного запуска он умножает цену газа, которую вы заплатите, на количество газа, которое вы готовы потратить, и рассчитывает «авансовые затраты». Если у вас нет этой суммы на вашем счету, это не удастся. Вы должны либо платить меньше за газ, либо уменьшить количество газа, которое вы готовы потратить. Я надеюсь, что это помогает.

Как указывал другой действительный ответ, возможная стоимость газа gas price* gas used. В вашем случае цена на газ 211000000000. В ваших вопросах не указано требуемое количество используемого газа, но указано максимально допустимое: 4712388.

Теперь, если мы предположим, что ваш контракт требует всего разрешенного газа, его стоимость газа будет: 4712388* 211000000000. И в результате получается 994 313 868 000 000 000 — ровно столько, сколько дает вам ваш деплойнер.

Так что да, расчеты верны. И, да, это почти 1 Eth.

Контракт выглядит простым, но он импортирует некоторые другие контракты, которые не являются простыми.