Solidity

“選舉”在部署時遇到了無效的操作碼。松露遷移

  • December 4, 2021

我剛剛開始使用 Solidity,遇到了一個我無法解決的問題。嘗試遷移時顯示以下錯誤

truffle migrate --reset
2_deploy_contracts.js
=====================

  Replacing 'Election'
  --------------------

Error:  *** Deployment Failed ***

"Election" hit an invalid opcode while deploying. Try:
  * Verifying that your constructor params satisfy all assert conditions.
  * Verifying your constructor code doesn't access an array out of bounds.
  * Adding reason strings to your assert statements.

我不明白為什麼會這樣,我嘗試了很多解決方案,但仍然沒有效果。更新 truffle 版本沒有幫助,隨後對 Election.sol 結構的更改也沒有幫助。我正在使用 ganache v2.5.4

選舉.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.20;
pragma experimental ABIEncoderV2;
contract Election {
   struct Elections {
       uint id;
       string title;
       string description;
       uint creationDate;
       uint expirationDate;
       Candidate[] candidates;
   }
   uint public electionsCount;
   Elections[] elections;

   struct Candidate {
       uint id;
       string name;
       uint voteCount;
   }
   uint public candidatesCount;

   function addElections (string memory _title, string memory _description, uint _amountOfHours, string[] memory _names) private {
       electionsCount ++;
       elections[electionsCount].id = electionsCount;
       elections[electionsCount].title = _title;
       elections[electionsCount].description = _description;
       elections[electionsCount].creationDate = block.timestamp;
       elections[electionsCount].expirationDate = block.timestamp + _amountOfHours;

       Candidate[] memory candidates;
       for (uint i = 0; i < _names.length; i++) {
           candidatesCount ++;
           string memory name = _names[i];
           candidates[candidatesCount] = Candidate(candidatesCount, name, 0);
           elections[electionsCount].candidates.push(candidates[i]);
       }
   }
   string[] names= ["AAAA", "BBBBB", "CCCCCC"];

   constructor () public {
       addElections("Voted", "vote for your candidate", 8, names);
   }
}

該函式addElections存在一些問題:

  1. 該函式將一個項目附加到elections數組中。為此,您必須使用數組的push()操作。
// Push an empty an item
elections.push();

// Get a reference to the new item
electionsCount = elections.length - 1;

// Update the reference
elections[electionsCount].id = electionsCount;
elections[electionsCount].title = _title;
elections[electionsCount].description = _description;
elections[electionsCount].creationDate = block.timestamp;
elections[electionsCount].expirationDate = block.timestamp + _amountOfHours;
  1. 第二部分使用數組candidates,但從未初始化。這真的沒有必要,所以我們可以放棄它。
for (uint i = 0; i < _names.length; i++) {
   candidatesCount ++;
   string memory name = _names[i];
   elections[electionsCount].candidates.push(Candidate(candidatesCount, name, 0));
}

引用自:https://ethereum.stackexchange.com/questions/114770