简体   繁体   中英

How to deploy multiple contracts with Truffle

I trying to deploy multiple contracts in Truffle to learn how it works.

This is the code:

//SPDX-License-Identifier: MIT

pragma solidity 0.8.11;

contract first{

    string public name;
    string public symbol;
    uint public totalSupply;

    mapping(address=>uint) public balances;

    function setAll(string memory _name, string memory _symbol, uint _totalSupply)public virtual{
        name = _name;
        symbol = _symbol;
        totalSupply = _totalSupply;
    }

    function mint()public{
        balances[tx.origin] += 1;
        totalSupply -= 1;
    }

}


contract second {

    string public name;
    string public symbol;
    uint public totalAmount;

    address public _first;

    constructor(address fiirst){
        _first = fiirst;
    }

    function set(string memory _name, string memory _symbol, uint _totalAmount)public{
        first _fir = first(address(_first));
        _fir.setAll(_name, _symbol, _totalAmount);
        _fir.mint();
        _totalAmount -= 1;
        name = _name;
        symbol = _symbol;
        totalAmount =_totalAmount;
    }
}

This is deploy_contracts.js:

const first = artifacts.require("first");

module.exports = function (deployer) {
  deployer.deploy(first, "BABACOIN", "BAB", 3000);
};


const second = artifacts.require("second");

module.exports = function (deployer) {
  const addContract = first.address;
  deployer.deploy(second, addContract);
};

How can I pass the address of the first contract to deploy the second one?

I tried first.address but get an error.

Once I deploy the contract, how can I set a different Ganache address to interact with the contract in Truffle console?

You can try using:

const first = artifacts.require("first");

const second = artifacts.require("second");


module.exports = async function (deployer) {

 await deployer.deploy(first, "BABACOIN", "BAB", 3000);

 await deployer.deploy(second, first.address);

};

Below statements are taken from MDN Web Docs - Making asynchronous programming easier with async and await .

Here, the async keyword is added to functions to tell them to return a promise rather than directly returning the value.

You can read about promise here - Promise .

await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.

This is why the code works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM