Solidity

ReferenceError:在初始化之前無法訪問“契約”

  • November 2, 2020

我正在嘗試使用 Truffle 使用 (PCE_Contract_test.js) 測試單個智能合約 (PCE_Contract.sol)。當我執行 Truffle 測試時,控制台輸出是:

ReferenceError: Cannot access 'PCE_Contract' before initialization

PCE_Contract_test.js:

const PCE_Contract = artifacts.require("./PCE_Contract");

contract('PCE_Contract', () => {

it('should deploy SC properly', async() => {

 const PCE_Contract = await PCE_Contract.deployed();

 console.log(PCE_Contract.address);

 assert(PCE_Contract !== '');

});

});

PCE_Contract.sol:

pragma solidity ^0.7.0;

contract PCE_Contract {

 uint256 public LOCK_PERIOD  = 365 days;
 address public investor;

 mapping(address => Deposit) deposits;

 constructor(){
 
 investor = msg.sender;
 }

 struct Deposit {
     uint256 value;
     uint256 releaseTime;
 }

 function investment() public payable {
      require(msg.value > 0,
        "You must make a non-zero deposit.");

      if (deposits[investor].releaseTime == 0) {
          uint256 releaseTime = block.timestamp + LOCK_PERIOD;
          deposits[investor] = Deposit(msg.value, releaseTime);

      } else {
          deposits[investor].value += msg.value;
      }
  }

  function withdraw() public {

   require(deposits[investor].value > 0,
     "You have no deposits available.");

   require(deposits[msg.sender].releaseTime < block.timestamp,
     "Your lock period has not ended yet.");

   msg.sender.transfer(deposits[investor].value);

   deposits[msg.sender].value = 0;
   deposits[msg.sender].releaseTime = 0;
}

function getDeposit(address holder) public view
 returns (uint256 value, uint256 releaseTime)

 {
       return(deposits[holder].value, deposits[holder].releaseTime);
   }

}

Truffle v5.1.49 (core: 5.1.49) Solidity - ^0.7.0 (solc-js) Node v12.18.4 Web3.js v1.2.1

任何幫助表示讚賞!

你的問題在這裡:

const PCE_Contract = artifacts.require("./PCE_Contract");
...
{
   const PCE_Contract = await PCE_Contract.deployed();
   ...
}

第二個聲明PCE_Contract掩蓋了第一個聲明PCE_Contract

因此,您實際上是在聲明變數之前嘗試使用PCE_Contract它(正如錯誤消息告訴您的那樣)。

如果您將這兩個聲明放在同一個範圍內,那麼您甚至會在腳本執行之前得到錯誤。但是由於您將它們放在兩個不同的範圍內,因此腳本可以執行(隨後,錯誤在執行之前沒有發生,僅在執行期間發生)。


邊注:

您可以去掉 中的./前綴,因為 Truffle 從編譯器生成的 JSON 文件中導入工件,而不是從您的實際原始碼所在的 Solidity 文件中導入工件(因此語句artifacts.require("./PCE_Contract")中不需要相對路徑)。artifacts.require

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