Build Ethereum DApps with Truffle Suite

Truffle Suite is a development framework for building Ethereum DApps. It includes tools such as Truffle, Ganache, Drizzle, etc., which can help developers easily write, test and deploy smart contracts.

In this article, we will introduce how to build a simple DApp using Truffle Suite and demonstrate how to use the Metamask browser plugin to interact with the DApp. We will assume that you are already familiar with the Solidity language and the Truffle development framework.

1. Create a smart contract

First, we need to create a smart contract. Here, we'll create a contract called SimpleStorage that allows users to set and get an integer value.

Open a command line window, enter the directory where you want to create the project, and run the following command:

truffle init

Then, create a file called SimpleStorage.sol and copy the following code:

pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private _value;

    function setValue(uint256 value) public {
        _value = value;
    }

    function getValue() public view returns (uint256) {
        return _value;
    }
}

This contract defines a contract named SimpleStorage, which contains a private variable _value and two public functions setValue and getValue. The setValue function takes a value of type uint256 and stores it in the _value variable. The getValue function returns the current value of the _value variable.

2. Deploy smart contracts

Next, we need to deploy our smart contract. In a command line window, run the following command:

truffle migrate

This will deploy our smart contract using the default local ethereum node.

3. Create the front-end application

Now, we can create our front-end application. In a command line window, run the following command:

npm init -y
npm install --save [email protected]

Then, create a file called index.html and copy the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>SimpleStorage DApp</title>
  </head>
  <body>
    <h1>SimpleStorage DApp</h1>
    <form id="setForm">
      <label for="value">Value:</label>
      <input type="number" id="value" name="value" />
      <button type="submit">Set Value</button>
    </form>
    <p id="getValue"></p>

    <script src="./index.js"></script>
  </body>
</html>

The code defines a simple HTML page that contains a form and a paragraph element. Forms are used to set new values ​​and paragraph elements are used to display current values.

4. Create a JavaScript file

Next, we need to create a JavaScript file called index.js and copy the following code:

const Web3 = require('web3');

window.addEventListener('load', async () => {
  if (typeof web3 !== 'undefined') {
    window.web3 = new Web3(web3.currentProvider);
  } else {
    window.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
  }

  const contractAddress = '0x...'; // 这里填写部署后的智能合约地址
  const abi = [
    {
      constant: false,
      inputs: [{ name: 'value', type: 'uint256' }],
      name: 'setValue',
      outputs: [],
      payable: false,
      stateMutability: 'nonpayable',
      type: 'function',
    },
    {
      constant: true,
      inputs: [],
      name: 'getValue',
      outputs: [{ name: '', type: 'uint256' }],
      payable: false,
      stateMutability: 'view',
      type: 'function',
    },
  ];

  const simpleStorage = new web3.eth.Contract(abi, contractAddress);

  const setForm = document.getElementById('setForm');
  setForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    const value = document.getElementById('value').value;
    await simpleStorage.methods.setValue(value).send({ from: web3.eth.defaultAccount });
    alert('Value set successfully!');
  });

  const getValueElement = document.getElementById('getValue');
  setInterval(async () => {
    const value = await simpleStorage.methods.getValue().call();
    getValueElement.textContent = `Current value: ${value}`;
  }, 1000);
});

This code uses the Web3 library to connect to the Ethereum network and get an instance of our deployed smart contract. It also defines a form event listener that sets the new value and displays an alert message on success. Finally, it also periodically retrieves the current value and displays it in the paragraph element.

5. Run the DApp in the browser

Now, we can run our DApp in the browser. In a command line window, run the following command:

npm install -g http-server
http-server

This will start a local HTTP server and open http://localhost:8080/ in your browser  . You should be able to see a simple form and a paragraph element for setting and displaying the current value.

6. Use the Metamask browser plugin to interact with the DApp

Finally, we can use the Metamask browser plugin to interact with our DApp. Make sure you have Metamask installed and a Rinkeby test network account created.

———————————————————— Prime Meridian ———————————————————

Below, we'll describe how to use Truffle Suite to build a simple voting application. The app allows users to create new polls and add options to each poll. Other users can vote and view current poll results.

1. Install Truffle Suite

First, we need to install Truffle Suite. Open a command line window and run the following command:

npm install -g truffle

2. Create a Truffle project

Next, we'll use Truffle to create a new project. In a command line window, go to the directory where you want to create the project, and run the following command:

truffle heat

This will create a new Truffle project and generate some default files and directories.

3. Write smart contracts

In a Truffle project, we can write smart contracts in the contracts directory. To create the voting application, we will write a contract called Voting. Open the contracts/Voting.sol file and copy the following code:

solidity
pragma solidity ^0.5.0;

contract Voting {
    mapping (bytes32 => uint256) public votes;

    function vote(bytes32 option) public {
        votes[option] += 1;
    }
}

This contract defines a contract called Voting that contains a map called votes. This map maps option names to vote counts.

The contract also defines a public function called vote that takes a byte array called option and increments the vote count for that option by one.

4. Write deployment scripts

In the Truffle project, we can use JavaScript scripts to deploy smart contracts. Open the migrations/2_deploy_contracts.js file and copy the following code:

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

module.exports = function(deployer) {
  deployer.deploy(Voting);
};

The script defines a contract called Voting and creates an instance of that contract when deployed.

5. Compile and deploy the smart contract

Now, we can use Truffle to compile and deploy smart contracts. In a command line window, run the following command:

truffle compile

This will compile our smart contract and generate some ABI and bytecode files.

Next, run the following command to deploy the smart contract:

truffle migrate

This will deploy our smart contract and save it locally on the Ethereum network.

6. Create a voting DApp

Now, we can use Truffle to create a simple voting DApp. In a command line window, run the following command:

truffle unbox react

This will create us a basic DApp using React and Web3.js.

Next, open the src/App.js file and copy the following code:

import React, { Component } from 'react';
import VotingContract from './contracts/Voting.json';
import getWeb3 from './getWeb3';

class App extends Component {
  state = {
    web3: null,
    accounts: null,
    contract: null,
    options: [],
    selectedOption: null,
    voted: false,
    loading: true,
  };

  componentDidMount = async () => {
    try {
      const web3 = await getWeb3();
      const accounts = await web3.eth.getAccounts();
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = VotingContract.networks[networkId];
      const contract = new web3.eth.Contract(
        VotingContract.abi,
        deployedNetwork && deployedNetwork.address,
      );

      const options = ['Option 1', 'Option 2', 'Option 3'];
      this.setState({ web3, accounts, contract, options }, this.listenToEvents);
    } catch (error) {
      console.error(error);
    } finally {
      this.setState({ loading: false });
    }
  };

  vote = async (option) => {
    const { accounts, contract } = this.state;
    await contract.methods.vote(option).send({ from: accounts[0] });
    this.setState({ voted: true });
  };

  listenToEvents = () => {
    const { contract } = this.state;
    contract.events.Vote({}, (error, event) => {
      console.log(event);
    });
  };

  render() {
    const { web3, accounts, contract, options, selectedOption, voted, loading } = this.state;

    if (loading) {
      return <div>Loading...</div>;
    }

    return (
      <div>
        <h1>Voting DApp</h1>
        <p>Connected to Ethereum network with address: {accounts[0]}</p>

        <h2>Options:</h2>
        <ul>
          {options.map((option) => (
            <li key={option}>
              {option}{' '}
              {!voted && (
                <button onClick={() => this.vote(option)}>Vote</button>
              )}
            </li>
          ))}
        </ul>

        {voted && (
          <p>You have voted for {selectedOption}.</p>
        )}
      </div>
    );
  }
}

export default App;

This code will create a DApp called Voting that contains a list of options and a voting button. When the user clicks the voting button, the DApp will call the smart contract's vote function, passing the option name as a parameter.

In addition, the code also listens to the Vote event of the smart contract and prints out the event data in the console.

7. Run the voting DApp

Finally, we can use Truffle to run our voting DApp. In a command line window, run the following command:

npm run start

This will start our DApp, and open it in the browser. Now we can try to create a new poll and vote on it.

In conclusion, Truffle Suite is a very useful development framework that can help us build Ethereum DApps easily. In this article, we used Truffle and React to create a simple voting application and demonstrated how to compile, deploy, and run a smart contract. If you are doing Ethereum DApp development, then Truffle Suite is definitely a tool worth trying.

Guess you like

Origin blog.csdn.net/weixin_62757215/article/details/130321714