Article directory
foreword
Blockchain technology is very popular now, you must have heard of smart contracts, so what exactly is a smart contract?
In fact, a smart contract is not smart at all. It is just a developed program deployed on the blockchain, and we can call the methods in it.
It has nothing to do with the current artificial intelligence, so is it difficult to develop a smart contract?
It's really not difficult, if you don't believe me, come with me, Bao Xue Bao Hui.
Environmental preparation
1. Install Node.js, npm
Node.js is a JavaScript runtime environment based on the Chrome V8 engine. We install Node.js here to install npm.
Go to the Nodejs official website to download the Node.js installation package , and follow the prompts to install it.
We enter node -v in the terminal, if you can see the version number, the installation is successful:
After installing nodejs, npm will be installed by default.
What is npm?
npm is actually a package manager for Node.js.
Simply put, npm is to help us quickly download various tools.
We enter npm -v in the terminal, if we can see the version number, the installation is successful:
2. Install Web3 JS - a javascript framework for developing Ethereum clients
Enter in the terminal: npm install web3
You can automatically download and install web3.js (all thanks to npm).
What is web3.js used for?
Simply put, the main function of web3.js is to provide a lot of class libraries for operating smart contracts, so that we can call smart contracts through JavaScript.
3. Install Ganache
Go to the official website to download Ganache and install it. Ganache is a local blockchain testing environment. It virtualizes a simple blockchain. We can deploy the smart contract locally for testing first, and then release it to the official chain after the test is completed. .
Open it after installation, click quickstart, and you can quickly create a test blockchain environment.
After the creation is completed, we can see the local blockchain environment, including the network ID, local service address and several test accounts, each of which has 100 ETH.
code deployment
1. Write the contract
remix is an online smart contract development environment that we can use directly in the browser, which is very convenient.
After opening the webpage, we can see an edit page, and add our own smart contract file SetName.sol under the contracts folder on the left:
The solidity language is used to write smart contracts. The following is a simple example, which are two methods for setting the name and lucky number and two methods for obtaining the value. The specific syntax will not be introduced here. Please refer to the relevant information.
// 合约版本号
pragma solidity >=0.7.0 <0.9.0;
contract SetName {
// 名字
string public name;
// 幸运号码
uint32 public luckNum;
// 构造方法,创建合约的时候自动调用(仅运行一次)
constructor() public {
name = "zhanyd";
}
// 设置名字
function setName(string _name) public {
name = _name;
}
// 获取名字
function getName() external view returns (string memory) {
return name;
}
// 设置幸运号码
function setLuckNum(uint32 _luckNum) public {
luckNum = _luckNum;
}
// 获取幸运号码
function getLuckNum() external view returns (uint32) {
return luckNum;
}
}
2. Deploy the contract
Click the deploy&run button on the left, and select Ganache Provider in the ENVIRONMENT drop-down box:
Fill in Ganache's local service address in the Ganache Provider pop-up box.
After clicking OK, the address in Ganache will be automatically loaded:
After selecting our smart contract setName, click the Deploy button to deploy the contract.
After deploying and playing, we can see that the contract we deployed has been generated under Deployed Contracts, and the method in the contract is displayed at the same time, and the system log will be displayed in the lower right corner.
At the same time, we can see the transaction that created the contract in the transactions tab in Ganache:
The smart contract is deployed here, is it very simple?
3. Call the contract
Let's call the contract and try it out:
Click the getName button to call the getName method in the contract and return the initial value zanyd of the name (remember the constructor() in the code above?).
We call the setLuckNum and setName methods respectively to set the lucky number and name, and log records generate two blocks:
We can see that two new blocks have been added in Ganache:
Click the getLuckNum and getName buttons to get the lucky number and name just set:
Well, it seems that the contract call was successful, but we can't always call the contract in the development environment, which is too troublesome.
We develop smart contracts for everyone to use together. It would be great if we could call them directly from the webpage in the browser!
DAPP
What are DAPPs?
DAPP is a decentralized application, simply put, it is an application that can call smart contracts.
Now let's develop a simple DAPP.
Remember the web3.js we installed at the beginning?
Now it will come in handy, web3.js is to allow us to call smart contracts with JavaScript code.
Let's write a simple HTML page first.
1. Write DAPP
<!DOCTYPE html>
<html>
<head>
<!-- 在线引入jquery -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<!-- 在线引入web3.min.js -->
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<title></title>
显示名字:<div id="show_name"></div>
显示幸运号码:<div id="show_luck_num"></div>
<from id="form">
<div>名字:<input type="text" name="name" id="name"></div>
<div>幸运号码:<input type="text" name="luckNum" id="luckNum"></div>
<input type="button" value="提交" onclick="submit()">
</from>
</head>
<body>
<script type="text/javascript">
let contract
let web3
$(function() {
// 初始化 Web3
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
}
// 测试是否连接成功
web3.eth.net.isListening()
.then(() => console.log('is connected'))
.catch(e => console.log('Wow. Something went wrong: '+ e));
// 设置合约 ABI
var contractAbi =
[
{
"inputs": [
{
"internalType": "uint32",
"name": "_luckNum",
"type": "uint32"
}
],
"name": "setLuckNum",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "string",
"name": "_name",
"type": "string"
}
],
"name": "setName",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getLuckNum",
"outputs": [
{
"internalType": "uint32",
"name": "",
"type": "uint32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getName",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "luckNum",
"outputs": [
{
"internalType": "uint32",
"name": "",
"type": "uint32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
// 设置合约地址
let contractAddress = '0xeB730Ef3Bc008376c88e09E6d23e364AEedA89a4';
// 获取智能合约对象
contract = new web3.eth.Contract(contractAbi,contractAddress);
// 调用合约对象的方法,返回名字
contract.methods.getName().call()
.then(function(result) {
console.log(result)
$('#show_name').text(result)
})
// 调用合约对象的方法,返回幸运号码
contract.methods.getLuckNum().call()
.then(function(result) {
console.log(result)
$('#show_luck_num').text(result)
})
})
// 提交事假
function submit() {
// from是Ganache模拟的一个账户地址
contract.methods.setName($('#name').val()).send({
from: '0x401Ec2d1E34d5Ae1fA07e5857Da9238CDC9dDf13'})
.then(function(result) {
console.log(result)
});
contract.methods.setLuckNum($('#luckNum').val()).send({
from: '0x401Ec2d1E34d5Ae1fA07e5857Da9238CDC9dDf13'})
.then(function(result) {
console.log(result)
});;
}
</script>
</body>
</html>
Note that the contract address is here:
The contract ABI is copied from here:
The contract ABI is to describe the methods in the smart contract in json format, so that the front-end knows what methods and parameters the contract has, and can call them in js.
If you copy my code directly, be sure to replace the contract address, contract ABI and account address.
2. Run DAPP
We open the HTML file directly, and we can see the name and lucky number read from the smart contract:
We enter the name and lucky number to be changed, and click the submit button:
Refresh the page to get the modified data:
Congratulations, your first smart contract has been developed!