Contract Development
Write and deploy EVM contracts
Now we will demonstrate the full process of contract development, deployment and testing using Hardhat.
Set up Environment
Contract Design
Contract Logic
The contract we use as an example here is for sending red packets, which is used when users send crypto assets as gifts. The core functions are:
Send red packets
Receive red packets
Before sending red packets, the user need to determine the amount of tokens to be sent and the number of red packets. For instance, 100 tokens will be sent in 10 red packets (to 10 different wallets). For ease of understanding, each red packet contains the same amount, i.e., each contains 10 tokens.
Consequently, we define the data structure:
EIP20Interface public token; // support token address
uint public nextPacketId; // the next redpacket ID
// packetId -> Packet, store all the redpacket
mapping(uint => Packet) public packets;
//packetId -> address -> bool, store receive redpacket record
mapping(uint => mapping(address => bool)) public receiveRecords;
struct Packet {
uint[] assetAmounts;// Number of tokens per copy
uint receivedIndex; // Number of red packets received
}Define Contract Events
When executing the contract, we can trace the process by adding events.
Here we design two events:
When the user send a red packet, the contract generates an ID for the red packets, which will be sent through this event notification:
2. When a user receives a red packet, this event notification is sent to record the ID and token amount of the received red packet:
Define Functions
sendRedPacket
Sends red packets. Any system is able to call the function and send certain amount of tokens to the contract address. Other addresses can receive red packets from this contract address.
receivePacket
Receives red packets. Any address can call this function by red packet ID to receive a red packet, meaning that you need to specify which one to receive.
View the full code here.
Compile and Test Contract using Hardhat
Create a Hardhat Project
Configure hardhat.config
Include TestNet node information:
accounts field takes the array of selected private key. There should be enough ONG balance in the corresponding address to pay for transactions. You can apply for TestNet ONG here.
File Preparation
Add the contract file in the contracts folder. To support ERC-20 token transfer, we also need EIP20Interface.sol, UniversalERC20.sol, and TokenDemo.sol which you can download from here.
Include Code in the test Folder
Compile Contract
Run this command in the root directory to compile the contract.
Then the following folders are generated.
Test Contract
You will get the following result:
Web3 APILast updated