Contract-Deployment

如何使用 Truffle 將建構子參數傳遞給合約?

  • April 5, 2021

我正在使用 testrpc 和 truffle 來部署合約。我想在部署時傳遞建構子參數。

   contract User { 
         string public userName;

         function User(string _name) {
                userName=_name;
         }

  }

我正在使用 contractname.deployed() 來部署契約。

     var user=User.deployed()

此部署命令不會初始化 userName 參數。

如何使用 truffle 將 _name 傳遞給該合約?

在 Truffle 中,建構子參數進入 /migrations。所以,像:

deployer.deploy(User, "foo");

User.deployed()將是使用 _name=“foo” 部署的使用者合約

讓我們考慮建構子接受兩個參數的測試合約:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

contract Test {
   address public owner;
   address public user1;
   address public user2;

   constructor (address _user1, address _user2)  {
       owner = msg.sender;
       user1 = _user1;
       user2 = _user2;
   }
}

Truffle-test 將使用MyContract.new($$ arg1, arg2, … $$,$$ tx params $$)將參數傳遞給建構子:

const TestContract = artifacts.require('Test');

contract('Test', function (accounts) {
   const [owner, user1, user2] = accounts;
   const txParams = { from: owner };

   beforeEach(async function () {
       this.testContract = await TestContract.new(user1, user2, txParams);
   });

   it('has an owner, user1 and user2', async function () {
       expect(await this.testContract.owner()).to.equal(owner);
       expect(await this.testContract.user1()).to.equal(user1);
       expect(await this.testContract.user2()).to.equal(user2);
   });
});

考慮到訪問狀態變數是使用getter-function

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