Solidity

為什麼松露測試會為同一個智能合約提供兩個不同的合約地址?

  • April 22, 2020

我正在練習智能合約,並註意到它在測試時為部署的同一個合約給出了兩個不同的地址。

const Test = artifacts.require('./Test.sol');

contract('Test', function(accounts) {

   describe('Test1 attributes', () => {
       let dInstance;
       beforeEach(async () => {
           dInstance = await Test.new();
       });

       it('has the address', async () => {
           const address = dInstance.address;
           const bal = await web3.eth.getBalance(address);
           assert(address != "0x" + "0".repeat(40),'has contract address');
           console.log('Current Contract:', address);
           console.log('Current Contract balance:', bal);
       });
   });

   describe('Test2 attributes', () => {
       let dInstance;
       beforeEach(async () => {
           dInstance = await Test.new();
       });

       it('has the address', async () => {
           const address = dInstance.address;
           const bal = await web3.eth.getBalance(address);
           assert(address != "0x" + "0".repeat(40),'has contract address');
           console.log('Current Contract:', address);
           console.log('Current Contract balance:', bal);
       });
   });


})

松露測試通過了,我可以看到同一個合約有兩個不同的地址。

Contract: Test
   Test1 attributes
Current Contract: 0xCFefb2b6a91901ceb0A7Ea02a688958b0E2E1279
Current Contract balance: 0
     ✓ has the address
   Test2 attributes
Current Contract: 0xe478Aad670D90474c28b63C150bc3E404Cd0F5A3
Current Contract balance: 0
     ✓ has the address


 2 passing (273ms)

你能告訴我可能是什麼原因嗎?我將不勝感激就此進行討論。謝謝。

因為您beforeEach在開始時使用 each ,所以在 each 中的 eachdescribe之前重新部署合約(創建它的新實例)。it``describe

將其更改為before,合約將只在每個中部署一次describe(當然,您仍然會獲得不同的地址)。

將其before移到所有describe範圍之外,每次執行測試時,合約只會部署一次。

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