Building the latest version of Truffle framework under Ubuntu in 2022

1. Install nodejs and npm

Uninstall and install node and npm in ubuntu - Programmer Sought

2. Installation

1. Environment
I have used Ubuntu18.04 and installed it as follows:
g++ installation, execute the command: sudo apt-get install g++
libssl-dev install, execute the command: sudo apt-get install libssl-dev

nodejs install, execute the command: sudo apt -get install nodejs

2. You also need to install
solc installation: sudo snap install solc

No need to install testrpc, it has been abandoned

testrpc安装:sudo npm install -g ethereumjs-testrpc



3. The installation instructions for Truffle to install Truffle are:

sudo npm install -g truffle

 No need to install ganache, it already has

Create project


Create an empty project

truffle init



Create a project containing metacoin

The new version of truffle introduces the concept of boxes, and all sample codes are provided in the form of boxes. Download the sample code for metacoin:

truffle unbox metacoin



Engineering structure

The project structure is shown in the figure:

The contracts directory contains Solidity contract code, of which Migrations.sol is required and the others are contract code (here is the sample MetaCoin code).

The migrations directory contains contract deployment scripts, 1_initial_migration.js is used to deploy Migrations.sol, and other scripts will be executed in sequence.

In the test directory is the test code.

MetaCoin

The code of MetaCoin mainly implements three interfaces: issuing coins, checking the balance, and checking the Eth balance.
 

contract MetaCoin {
    mapping (address => uint) balances;

    event Transfer(address indexed _from, address indexed _to, uint256 _value);

    function MetaCoin() public {
        balances[tx.origin] = 10000;
    }

    function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
        if (balances[msg.sender] < amount) return false;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Transfer(msg.sender, receiver, amount);
        return true;
    }

    function getBalanceInEth(address addr) public view returns(uint){
        return ConvertLib.convert(getBalance(addr),2);
    }

    function getBalance(address addr) public view returns(uint) {
        return balances[addr];
    }
}

Can install ganache graphical version

  Download address: https://www.trufflesuite.com/ganache. Download the version corresponding to the system, and then install it. This will be skipped and not spoken. We focus on the settings of truffle.

       Open Ganache, as shown below:

insert image description here

       The button on the left is Quick Start, its data will not be saved, and it will be a brand new development environment after each startup. The button on the right is to save the current data to the corresponding workspace, and there can be multiple workspaces. We select the new workspace on the right:
insert image description here

 The workspace can be given a meaningful name here, and the add project in the lower left corner will be skipped first, because we don't have a truffle project yet.

The top column of this interface is the navigation menu, the next line is various information, and the right side is the switch workspace and settings buttons. The third line is the mnemonic from which all addresses are generated.

       There are 10 accounts in the main interface of the interface, and the address of each account, the balance, the number of completed transactions, the index in the account array, the button to display the private key, etc. are listed separately. Clicking on that key icon will reveal its private key.

       Click Blocks on the navigation, you can see that the current Block is 0. This is because the Ganache mining mechanism determines that each transaction generates a block, so a block can only have one transaction (this is the author's experience, it may be wrong). A block will be generated after our transaction, not yet.


———————————————
Copyright statement: This article is an original article by CSDN blogger "Zero_Nothing", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting .
Original link: https://blog.csdn.net/weixin_39430411/article/details/104248037

After a series of configurations is complete, it is time to open the project folder with Visual Studio Code. If you don't have Visual Studio Code installed, you can download it from http://code.visualstudio.com. After opening the project folder, the contents of the directory are as follows:

in,

  • The contract folder is used to save the developed smart contract source code. Migrations.sol in the folder is the auxiliary code used by Truffle to help deploy Solidity smart contracts. Please do not change it at will.
  • The mirgations folder is the folder that holds the JavaScript code for deploying, compiling, and testing contracts.
  • The unit test source code is stored in the test folder.
  • The Truffle-config.js and truffle.js files are used to save the Truffle Framework configuration file information. In fact, the contents of the two files are the same. The truffle.js file is used for macOS and Linux operating systems. Under Windows, in order to avoid duplicate names, use truffle-config.js as the configuration file instead.

Compile and deploy the contract


Ganache runs on the local port 7545 by default. After running, 10 accounts are created by default, and each account has a balance of 100ETH.

Modify truffle.js

To deploy to the chain, you need to tell truffle the IP, port, and network ID. Modify truffle.js:

module.exports = {  
    networks: {  
        development: {  
            host: 'localhost',  
            port: '7545',  
            network_id: '*' // Match any network id  
        }  
    }  
}; 


Compile and deploy

truffle compile  

 If the contract is changed, truffle compile only compiles the changed contract. To force the compilation of the entire contract, use truffle compile --compile-all.


truffle migrate

migrations/2_deploy_contracts.js 

 with parameters if required

module.exports = function(deployer) {
  deployer.deploy(Greeter,"Hello, World!");//"参数在第二个变量携带"
};
var Voting = artifacts.require("./Voting.sol");
module.exports = function(deployer) {
deployer.deploy(Voting, ['Alice', 'Bob', 'Cary'], {gas:
290000});
};

As you can see from the above, the deployer expects the first parameter to be the contract name, following the constructor parameter.

In our case, there is only one parameter, which is an array of candidates. The third parameter is a hash that we use to specify the gas required to deploy the code. The amount of gas will vary with the size of your contract. For voting contracts, 290000 is enough.

contract address 

test contract


Test content

The test code has been written in the sample code of MetaCoin, mainly to test whether the interface of MetaCoin is available:

contract TestMetacoin {

// 测试已经部署的智能合约
function testInitialBalanceUsingDeployedContract() public {
    MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin());

    uint expected = 10000;

    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
}


// 测试新的智能合约
function testInitialBalanceWithNewMetaCoin() public {
    MetaCoin meta = new MetaCoin();

    uint expected = 10000;

    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
}

}


test contract

Directly enter the command to test the contract:

truffle test



The results showed that all 5 tests passed:

can use

js to call the test, you can also use to write a sol contract test 


———————————————
Copyright statement: This article is an original article by CSDN blogger "MyHerux", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting .
Original link: https://blog.csdn.net/MyHerux/article/details/80340095


 

Guess you like

Origin blog.csdn.net/u013288190/article/details/123840776