Conflux DApp Development Tutorial

English | simplified Chinese

directory

  • Introduction to the
  • The preparatory work
  • Intelligent contract
  • Call the contract
  • Paid function
  • The front-end project
  • conclusion

Introduction to the

Conflux DApp Development tutorial will use Conflux Studio to develop a simple token application called Coin under the Tethys network.

Through this development tutorial, you will learn how to write and invoke Conflux smart contracts, configure payment for smart contracts, and how to use Web front-end projects to interact with smart contracts to implement a complete DApp that includes both the front end and smart contracts.

Please feel free to let us know in Issues if you have any problems reading this tutorial.

The preparatory work

Install the IDE

Please download Conflux Studio from the GitHub Download page. Currently, Conflux Studio supports macOS, Windows, and Linux operating systems. Download the corresponding version based on the operating system.

After installing Conflux Studio correctly and starting it for the first time, Conflux Studio will display the welcome page and follow the instructions to download, install, and start Docker, Conflux Node, and Conflux Truffle.

Create a wallet

After completing all installation steps, you first need to create key pairs for subsequent contract deployment and invocation.

From any interface in Conflux Studio, tap the key icon in the lower left corner of the app to open the key Manager. Click the Create button to open the new key pair popup, enter the name of the key pair, and click the Save button. When you’re done, you’ll see the address of the key pair you just generated in the key manager. A key pair consists of a private key and a public key, which is often referred to as an address in a smart contract.

Export the private key by clicking the eye button behind each address to open the View private Key popup, which displays the address and the private key. You will need to export the private key through the manager in a later tutorial.

To successfully complete the tutorial, you first need to create three key pairs:

  • minter_keyThe signature used for Coin contract deployment is the most frequently used key pair in this tutorial
  • receiver_keyIt is used for Coin contract to receive transfers and will be used later in transfers
  • sponsor_keyIt is used for the Coin contract payment function, which will be described laterPaid functionUsed when

Connects to a Conflux network

The tutorial will deploy the contract and invoke the contract on the Oceanus network. Click the inverted triangle of the Network TAB at the top to open the drop-down menu, and click Select Oceanus Network to switch.

After the switch is complete, you can view the current network as Oceanus on the home page. The left side of the page contains the node URL, Chain ID, and TPS information of the current network, while the right side of the page contains the information of the current network block.

Request to test CFX

Click the Explorer TAB at the top to open the block browser and paste the key pair address in the address bar to see the CFX balance information for the current address on the left.

In the blockchain world, the method of applying for a test Token is commonly referred to as Faucet, and currently 100 CFX tokens are requested per Faucet on the Oceanus network.

There are two ways to obtain CFX:

  • After entering the address, click the tap button to the right of the address bar and Conflux Studio will automatically apply CFX for the address
  • You can also type it directly into your browserhttps://wallet.confluxscan.io/faucet/dev/ask?address={address}Provided to apply CFX

Apply CFX tokens for minter_key and sponsor_key in Conflux Studio using the above method. Upon completion of the application, the balance on both accounts will be updated from 0 CFX to 100 CFX.

The current balance information is:

  • minter_keyThe balance provided 100 CFX
  • receiver_keyThe balance provided 0 CFX
  • sponsor_keyThe balance provided 100 CFX

Intelligent contract

Create a project

Click the Project TAB at the top left to switch to the Project list page, click the New button in the page to open the Project creation window, enter the name of the Project and select coin template, click Create Project to complete the creation of the Project.

Contract code

A Coin contract is a simple token contract in which:

  • throughmintMethod can increase the number of tokens
  • throughsendMethod transfers a certain number of tokens to other users, and records the transfer information in the event
  • throughbalanceOfMethod to query the token balance of the specified account address
  • throughadd_privilegeMethod to add a payer whitelist to the contract
  • throughremove_privilegeMethod to remove the payer whitelist for a contract

The Conflux smart contract is developed using Solidity. Open the contracts/ coin.sol file in the directory and this is the core code of this project:

// Specify the version of Solidity, Through Pragmas (https://solidity.readthedocs.io/en/latest/layout-of-source-files.html#pragmas) tells the compiler to this code can be compatible version 0.5.0 to 0.7.0
pragma solidity >=0.5. 0 <0.7. 0;

// Import the SponsorWhitelistControl contract
import "./SponsorWhitelistControl.sol";

// Define the Coin contract
contract Coin {
    / / defines two State Variables (https://solidity.readthedocs.io/en/latest/structure-of-a-contract.html#state-variables)
    address public minter;
    mapping (address => uint) private balances;

    // Connect system contracts using SponsorWhitelistControl contracts
    SponsorWhitelistControl constant private SPONSOR = SponsorWhitelistControl(address(0x0888000000000000000000000000000000000001));

    // Events that define 'Sent' define the from/to/amount column
    event Sent(address from, address to, uint amount);

    // Constructor of the Coin contract, which specifies the address of minter
    constructor(a)public {
        // msg.sender assigns this address to minter for the account address signed when deploying the contract
        minter = msg.sender;
    }

    // Define the mint method to issue additional tokens
    function mint(address receiver, uint amount) public {
        require(msg.sender == minter);
        require(amount < 1e60);
        balances[receiver] += amount;
    }

    // Define the send method, by which tokens can be transferred to other accounts
    function send(address receiver, uint amount) public {
        require(amount <= balances[msg.sender], "Insufficient balance.");
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        // Emit the Sent event to record the transfer information
        emit Sent(msg.sender, receiver, amount);
    }

    // Define the balanceOf method, which is a view type method used to query account balances
    function balanceOf(address tokenOwner) public view returns(uint balance){
      return balances[tokenOwner];
    }

    // the add_privilege method is defined, and the system contract add_privilege method is invoked to add the address to the payroll whitelist
    function add_privilege(address account) public payable {
        address[] memory a = new address[](1);
        a[0] = account;
        SPONSOR.add_privilege(a);
    }

    The remove_privilege method is defined to call the system contract remove_privilege to remove the address from the contract payer whitelist
    function remove_privilege(address account) public payable {
        address[] memory a = new address[](1);
        a[0] = account;
        SPONSOR.remove_privilege(a); }}Copy the code

Compile and deploy contracts

Click the Build button in the toolbar to compile the contract. The compiled result will be saved in the Build/coin.json file.

Click the Deploy button in the toolbar to deploy, and the Deployment parameters window opens, where you can define constructor parameters, signer, gas Limit, and gas Price. From the constructor of the contract code, minter is assigned to msg.sender, which is the signer address selected in the arguments window.

After the deployment is complete, the deployment result is in the JSON file of Deploys, where you can find the current contract deployment address in contractCreated, which is represented by contract_ADDR in this article.

Call the contract

Click the Contract TAB at the top to switch to the Contract page, enter the contract_ADDR address in the address bar and load the Contract.

The contract page consists of three parts:

  • On the left is the contract invocation area
  • In the middle is the contract data query area
  • The event query area is on the right

Contract calls and queries

Secondary tokens,

Click on the contract call drop-down menu to select mint method and fill in the parameters field below with the following information:

  • receiverThe address to receive the token. Fill in theminter_keyaddress
  • amountTotal number of tokens issued. Fill in the integer 1000
  • ValueOptional, you can view the detailsValueExplanation. Fill in 0 or leave it blank
  • SignerThe signature address of this transaction, if the payment function is not enabled, the transaction commission will be deducted from this account address and passed in the contract codemsg.senderGet this address. Fill in theminter_keyaddress

After filling in, click the Execute button, and Conflux Studio will automatically construct the transaction and push it to the network. After successful execution, you can see the successful transaction in Result below.

Query the token balance

Click on the drop-down menu of the query area and select the balanceOf method, which is the query method defined in the code. Fill in the minter_key address in the tokenOwner below and click Execute. You can see in the Result below that the balance information of Coin token of the Minter_key account is 1000. Use the same method to query the token balance of the receiver_key account.

Transfer tokens,

Select the send method in the contract call field and fill in the Parameters:

  • receiverBeneficiary’s address. Fill in thereceiver_keyaddress
  • amountThe number of tokens transferred. Fill in the integer 200
  • SignerThe signature address of the transaction and the amount of tokens transferred will be deducted from the account. Fill in theminter_keyThe address,

Click Execute to complete the transfer and check the token balance again. You can see that there are only 800 tokens left in the Minter_key account and 200 tokens left in the Receiver_key account from 0.

The Value parameter

Each method invoked by the Conflux smart contract can take a Value argument, which is optional. If this Value is taken, the smart contract will transfer an additional number of CFX tokens specified in the Value to the receiver account for the amount specified in the Value, in addition to the logic for executing this method. Some smart contract methods require this parameter to complete the call, but the Coin contract does not.

The billing function that follows will use the Value parameter.

Query events

Select Sent in the Event area and click Execute. You can see the record of the transfer under Event Logs. The Sent event columns are defined by parameters to the Sent event in the code (where epoch is the time when the event occurred, and this is the default column). The parameters of the Sent method are defined in the code as from, to, and amount, which correspond to the address of the originator of the transfer, the address of the receiver, and the amount of the transfer respectively.

Paid function

Conflux Studio supports the payment function provided by Conflux system contracts.

Through the system contract, you can set up the payment function for other contracts. The system contract provides four methods:

  • add_privilegeAdd a contract whitelist. There is no handling charge for calling the contract method from the address in the whitelist. The fee is paid by the account. Add a special address0x0000000000000000000000000000000000000000The representative pays for all addresses that invoke the contract
  • remove_privilegeRemoved contract payer whitelist
  • set_sponsor_for_collateralCollateral account and amount of collateral for storage
  • set_sponsor_for_gasSet up gas fee accounts, the amount of gas fee and the maximum amount of gas fee per transaction

Enabling payment for a contract requires setting up the payment account, payment amount, and payment whitelist. The tutorial will use Conflux Studio to set up the account and amount of payment through the system contract and add the whitelist of payment through the Coin contract. Once the setup is complete, the minter_key account will not deduct the fee when calling the Coin contract method. The fee will be paid by the sponsor_key account.

Set up payment account and payment amount

The Conflux access system in the Studio address 0 x0888000000000000000000000000000000000001, before the contract call area can see four Settings of the mentioned payment method.

Select the set_sponsor_for_collateral method, which takes three parameters:

  • contract_addrSet up the contract address of the agent. Fill in thecontract_addr
  • ValueSet the payment amount. Fill in the integer 40
  • SignerAddress of paying account. Fill in thesponsor_keyaddress

Fill in the above parameters and execute the operation, the system contract will set up the storage fee agent account for Coin contract, at this time, the sponsor_key account will be deducted 40 CFX.

Select the set_sponsor_for_gas method, which takes four parameters:

  • contract_addrSet up the contract address of the agent. Fill in thecontract_addr
  • upper_boundSet an upper limit for each transaction. Fill in the 1000000000000
  • ValueSet the payment amount. Fill in the integer 40
  • SignerAddress of paying account. Fill in thesponsor_keyaddress

Fill in the above parameters and execute the operation again, the system contract will set up the commission account for Coin contract, at this time, the sponsor_key account will be deducted 40 CFX again.

After these two methods are called, the Coin contract payment account will be set up. The sponsor_key account will provide 40 CFX Token payment service for the Coin contract handling fee and storage fee respectively. Because there is no account address in the payment whitelist, you need to add the whitelist address to complete the payment setting.

Add payer whitelist

A method for setting the payroll whitelist is integrated into the Coin contract, which can be called to add or remove the payroll whitelist.

To access the contract_ADDR contract in Conflux Studio, select the add_privilege method:

  • accountAdd a whitelisted address. Fill in theminter_keyaddress
  • ValueDon’t fill in
  • SignerSigned address for the transaction. Fill in theminter_keyaddress

After running, the payment whitelist is successfully set, so far the payment function of Coin contract is set up.

An eye test

Check and record the CFX balance of the Minter_key account before performing the disbursement test. For example, in this tutorial, the initial balance of minter_key is 97.6210937497093952 CFX.

Go back to the Coin contract call page, call mint method again and use minter_key address to issue token 1000. After issuing token 1000, query the balance of minter_key again and it is still 97.6210937497093952 CFX.

You can see that the transaction for the additional token, which should have been paid by the Minter_key account, was paid by the sponsor_key account.

The front-end project

Front-end project source can go to the Conflux front end.

prepare

Download the project and install the dependencies

  • Download the front-end project:git clone https://github.com/ObsidianLabs/conflux-frontend-react
  • usenpm installoryarnPerform project-dependent installation

Install and configure the Conflux Portal

Conflux Portal is a browser plug-in provided by Conflux. Currently, it supports Chrome and Firefox. Users can use Conflux Portal to manage private keys and sign transactions.

Go to Conflux Portal GitHub to download and install it. The source code for the project is available on GitHub.

Here you need to import the addresses generated in Conflux Studio into the Conflux Portal. After installing the plug-in, select Import on the Conflux Portal page, paste the private key of Minter_key in Conflux Studio (how to export the private key is described in creating a wallet section) into the input box, and click the Import button to Import the private key.

Running front-end projects

Before you can run the project, you need to modify some of the default environment variables.

A contractCreated is generated after the contract is deployed in the previous tutorial, and this value is the address of the smart contract deployed on the network. Open the project root directory and find the.env file, which provides the project’s environment variables, and change the value of REACT_APP_CONFLUX_COIN_ADDRESS to contract_addr.

Start the front-end project using YARN Start. After the development server starts, the front-end page is displayed in the browser. If the front-end page is not displayed, visit http://localhost:3000 in the browser.

After the project runs, the page will display four card information, respectively

  • Upper left corner Conflux network information module
  • Conflux Portal module in the upper right corner
  • Coin contract module in the lower left corner
  • SponsorWhitelistControl contract module at bottom right

Connect the Conflux Portal

Click the Connect to Conflux Portal button in the upper right corner of the component, the Conflux Portal page will be opened, enter the password and select the account to complete the connection. After the connection is successful, you will see the current connected account address and CFX balance in the account under the button.

Run Coin contract token additional issuance and token transfer operations

The component in the lower left corner is the Coin contract component, through which you can call the function of token issuance and token transfer.

  • Additional issuance of tokens: Select the mint method and enter the minter_key address in receiver and the number of tokens issued in Amount 100. Click Push Transaction. Click the Confirm button in the ConfluxPortal Notification window that pops up to Confirm the transaction.

  • Token transfer: Select the send method and fill in the receiver address receiver_key address and the amount of tokens to transfer in the amount 20. Click Push Transaction. Click the Confirm button in the ConfluxPortal Notification window that pops up to Confirm the transaction.

Check the balance in the Coin contract

Select the balanceOf method and enter the Query address in the tokenOwner input box. Click the Query Data button to Query the account balance.

Viewing Sent Events

Select the Sent event and click Query Data to Query the records of the transfer events triggered by the transfer operation.

Front-end project analysis

React was used to develop the project. It is mainly composed of three parts: view component, JS-Conflux-SDK and Conflux Portal.

The.env environment variable in the project root directory, where two environment variables are defined, respectively

  • REACT_APP_CONFLUX_NODE_RPC: Indicates the network node address of Conflux. The default value is Oceanus network address
  • REACT_APP_CONFLUX_COIN_ADDRESS: Address of the deployed Coin smart contract

The view components

The view component is in the SRC/Components of the project, where app.js is the main entrance of the page and is responsible for arranging the page and reading the contract information.

ConfluxNetwork.js

Responsible for rendering Conflux network information, the value of Node URL is the value set by REACT_APP_CONFLUX_NODE_RPC in the.env environment variable file (default Oceanus network).

ConfluxPortal.js

Responsible for rendering the connection information of the Conflux Portal and providing interactive buttons to connect to the Conflux Portal.

  • connectConfluxPortalTo invoke the Conflux PortalenableMethod Enable conflux (the Conflux Portal instance is injected into Windows. portal by the browser plug-in)enableAfter the callgetAccountMethod to obtain an account on the Portal.
  • refreshBalanceCall the Conflux SDKgetBalanceMethod to update account balance information
  • renderPortalButtonRender the button that connects to the Portal based on the current state
ConfluxContract.js

Responsible for rendering Conflux contract information. Coin and SponsorWhitelistControl contracts are provided in this project.

Confluxcontract.js consists of three components, which are:

  • ConfluxContractResponsible for rendering the contract information according to the incoming contract ABI, including the contract address, contract methods and events, the interaction logic of the contract submission, and displaying the results of the execution
  • ContractMethodsResponsible for rendering a list of methods and events and their corresponding buttons in the contract ABI
  • ConfluxFormThe ABI is responsible for rendering the input form according to the method or event

lib

Lib In the SRC /lib section of the project, these files provide services for the view, including connecting to the network, structuring transactions, obtaining accounts, and reading contracts.

conflux.js

Conflux. js is a wrapper around js-Conflux-SDK. Js-conflux-sdk is a JavaScript SDK provided by Conflux. This front-end project uses SDK to connect the Conflux network, interact with the contract and construct instances in the contract.

conflux-portal.js

Conflux-portal. js is the encapsulation of Conflux Portal. The front-end project completes the transaction signature by invoking the browser plug-in. Call the enable method provided by the Conflux Portal to start the connection between the project and the Conflux Portal (check that the browser has installed the plug-in correctly in advance, which is determined by checking whether window. Conflux is empty in Constructor). Conflux-portal. js provides two main methods for getting the account getAccount and sending the transaction sendTransaction.

abi

Lib/abi folder provides two json file, Coin, respectively. The json and SponsorWhitelistControl json, the two files is the need to use the abi file construction contracts.

conclusion

In this development tutorial, we learned how to use Conflux Studio to complete a complete Coin DApp development, which includes:

  • Use keys to create accounts and export account private keys to the manager
  • Switch to the Oceanus network and view the network information
  • The account applies for a CFX Token
  • Create, compile, and deploy the project
  • Parse the Coin contract code, learn how to write the contract read and write methods and events
  • Use the contract browser to call Coin contract token issuance, transfer, balance query and query events
  • Set up and use the payment function of smart contracts
  • Import the private key into the Conflux Portal and connect to the front-end project
  • Invokes Coin contract token issuance, transfer, balance query and query events in the front-end project
  • Parse the front-end project code and learn how to connect to the network and implement transactions through the Conflux Portal and Conflux JavaScript SDK