WeChat  

Further consultation

How to Write a DApp Smart Contract Using Solidity? A Complete Tutorial

latest articles
1.DApp Development & Customization: Merging Diverse Market Needs with User Experience 2.Analysis of the Core Technical System in DApp Project Development 3.How to achieve cross-chain interoperability in Web3 projects? 4.How does the tokenization of points reconstruct the e-commerce ecosystem? 5.How to Set and Track Data Metrics for a Points Mall? 6.What is DApp Development? Core Concepts and Technical Analysis 7.Inventory of commonly used Web3 development tools and usage tips 8.Development of a Distribution System Integrated with Social E-commerce 9.Six Key Steps for Businesses to Build a Points Mall System 10.What is DApp Development? A Comprehensive Guide from Concept to Implementation
Popular Articles
1.Future Trends and Technology Predictions for APP Development in 2025 2.Analysis of the DeFi Ecosystem: How Developers Can Participate in Decentralized Finance Innovation 3.From Zero to One: How PI Mall Revolutionizes the Traditional E-commerce Model 4.DAPP Development | Best Practices for Professional Customization and Rapid Launch 5.Recommended by the Web3 developer community: the most noteworthy forums and resources 6.From Cloud Computing to Computing Power Leasing: Building a Flexible and Scalable Computing Resource Platform 7.How to Develop a Successful Douyin Mini Program: Technical Architecture and Best Practices 8.Shared Bike System APP: The Convenient Choice in the Era of Smart Travel 9.How to Create a Successful Dating App: From Needs Analysis to User Experience Design 10.From Design to Development: The Complete Process of Bringing an APP Idea to Life

With the rapid development of blockchain technology, decentralized applications (DApps) have become a hot topic for many developers. DApps are not just a new type of application; through blockchain technology, they enable the decentralization of data and transactions, ensuring user privacy and security. In the process of developing decentralized applications, smart contracts are their core component. Solidity, as the most popular smart contract programming language currently, is widely used for developing DApps on the Ethereum platform. So, how do you write a DApp smart contract using Solidity? This tutorial will guide you step-by-step on how to write a Solidity smart contract from scratch and implement DApp functionality.

1. Introduction to Solidity

Solidity is a high-level programming language developed by the Ethereum team for writing smart contracts on the Ethereum blockchain. It is similar to JavaScript and is designed to address the development challenges of smart contracts on the blockchain. Solidity supports static typing, object-oriented programming, inheritance, libraries, and other features, helping developers quickly write smart contracts.

Why Choose Solidity?

As a smart contract language, Solidity has the following characteristics:

  • Highly Integrated: Solidity is designed for the Ethereum network, enabling seamless integration with Ethereum's Virtual Machine (EVM) and offering high compatibility.

  • Wide Support: Ethereum is the most popular smart contract platform globally, making Solidity the mainstream language for developing smart contracts, with abundant learning resources and development tools.

  • Powerful Smart Contract Capabilities: Solidity supports various data structures and operations, enabling the implementation of complex smart contract logic.

2. Setting Up the Development Environment

Before starting to write Solidity smart contracts, we need to set up the development environment. Below are the common development tools and steps.

2.1 Installing Node.js and npm

Node.js is a JavaScript runtime based on the Chrome V8 engine, which helps us run JavaScript code in a local environment. npm is Node.js's package management tool, commonly used to install and manage dependency libraries.

  • Visit the Node.js official website to download and install Node.js.

  • After installation, check if the installation was successful by executing the following commands in the command line:

    node -vnpm -v

2.2 Installing the Truffle Framework

Truffle is a powerful Ethereum development framework that provides developers with features such as smart contract compilation, deployment, and testing. Truffle helps us quickly create, compile, deploy, and test Solidity smart contracts.

Enter the following command in the command line to install Truffle globally:

npm install -g truffle

After installation, you can check if Truffle is successfully installed with the following command:

truffle version

2.3 Installing Ganache

Ganache is part of the Truffle development suite. It is a local Ethereum blockchain simulator used for testing and debugging smart contracts. During development, Ganache provides a local, independent blockchain environment, allowing developers to deploy and test contracts without connecting to the mainnet.

You can download and install it from the Ganache official website.

2.4 Creating a Truffle Project

To create a new Truffle project, use the following commands:

mkdir MyDApp
cd MyDApptruffle init

This will initialize a new Truffle project, generating the necessary files and directory structure, including directories such as contracts (for storing Solidity smart contracts), migrations (for storing deployment scripts), and test (for storing test code).

WeChat Screenshot_20250404213236.png

3. Writing Smart Contracts

In the contracts directory of the Truffle project, create a new Solidity file, for example, SimpleStorage.sol, which will define our smart contract.

3.1 Contract Code Example

Below is a simple Solidity smart contract for storing and retrieving an integer value.

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

contract SimpleStorage {
    uint256 private storedData;

    // Function to set the stored data
    function set(uint256 x) public {
        storedData = x;
    }

    // Function to get the stored data
    function get() public view returns (uint256) {
        return storedData;
    }}
  • storedData is the contract's state variable used to store integer values.

  • The set function is used to modify the value of storedData, and anyone can call this function.

  • The get function is used to query the value of storedData, and its return type is uint256.

3.2 Contract Compilation

In the Truffle project directory, execute the following command to compile the smart contract:

truffle compile

This will compile all Solidity files in the contracts directory and generate the corresponding bytecode and ABI (Application Binary Interface).

4. Deploying Smart Contracts

Deploying a smart contract is the process of publishing it to the Ethereum network. We can deploy the contract to a local Ganache instance, or to Ethereum's testnet or mainnet.

4.1 Configuring Deployment Scripts

Create a new deployment script in the migrations directory, with the filename 2_deploy_contracts.js. This file is used to define how to deploy the smart contract to the blockchain.

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

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

4.2 Deploying to Ganache

Ensure Ganache is running and listening on 127.0.0.1:7545. Then execute the following command to deploy the contract to Ganache:

truffle migrate

This will deploy the smart contract to the Ganache network and output the deployment results. You can view the contract address and transaction history through Ganache's interface.

4.3 Deploying to Testnet

To deploy the smart contract to Ethereum testnets (such as Rinkeby or Ropsten), you first need to create a wallet, obtain testnet ETH, and configure Truffle's truffle-config.js file, specifying network parameters and wallet keys.

module.exports = {
  networks: {
    rinkeby: {
      provider: () => new HDWalletProvider('your mnemonic', 'https://rinkeby.infura.io/v3/your_infura_project_id'),
      network_id: 4,
      gas: 4500000,
      gasPrice: 10000000000,
    },
  },
  compilers: {
    solc: {
      version: "^0.8.0",
    },
  },};

After configuration, execute the following command to deploy the contract to the Rinkeby testnet:

truffle migrate --network rinkeby

微信截图_20250404213316.png

5. Interacting with Smart Contracts

After the contract is deployed, you can interact with the smart contract through Web3.js. Web3.js is a JavaScript library for interacting with Ethereum nodes.

5.1 Installing Web3.js

First, install Web3.js in your project:

npm install web3

5.2 Creating a DApp Frontend

You can use frontend technologies like HTML and JavaScript to create the DApp interface and use Web3.js to interact with the smart contract.




    
    SimpleStorage DApp
    


    

Simple Storage DApp

         Set Value     Get Value     Stored Value: