Talking about blockchain DAPP learning

bluishfish 2022-04-06 12:50:13 阅读数:786

talking blockchain dapp learning

f1ee83a8c17f90f3b31b689ab8065665.gif

Preface

The meta universe is on fire recently , I've been talking to my friends , So what is the meta universe (VR Virtual reality , The digital twin of the real world ), Then someone talked about web3.0, In reality, the meta universe and web3.0 Are still some vague feelings , But there are some practical technical solutions , Today I won't talk about the meta universe ( In fact, the Internet itself is a ubiquitous meta universe .

I won't say it because VR I don't know much about technology , But now there are many domestic fool tools thingjs, Yunuo technology has good products , Don't say it abroad ), Today I'm going to talk about web3.0 An Internet that everyone can have in the future ; To put it simply web1.0 It's a read-only network ( On behalf of Netease ),web2.0 It's a read-write network ( On behalf of Weibo and wechat ).

The first two generations of networks are centralized networks. It is difficult to guarantee the information rights of network users, that is, it is difficult to confirm the rights of content ,web3.0 To ensure your ownership . ok , How to ensure ownership , It's actually a blockchain , In fact, the meta universe cannot avoid this problem , It seems that all future networks need blockchain , However, at this stage, both the main chain and the side chain of the blockchain are slow , To write so many block rights confirmation, the technology is still slow at this stage, which is still realistic .

b39bd4ea0129deda6cba266cc1084c38.png

Why study web3.0

company ( Male : Several people's property ; department : Meaning of operation ). Modern society is developing , Economic production cooperation between the company and the company , The economic production cooperation between people is becoming more and more complex , In particular, there are more and more cooperation under the Internet , How to confirm the value of the property of these people or many people in one or more economic production activities is a problem that the Internet needs to solve . Work at home , professional , The need for new social relations of production is constantly giving birth to web3.0 And the perfection of the meta universe .

Study web3.0 What skills need to be mastered

Solidity Intelligent contract Write language

Solidity Language is a contract oriented high-level programming language , It is used to realize smart contract on Ethereum blockchain network . Its development tools Remix, Its online editor is recommended [https://remix.ethereum.org], Online editor and matemask Seamless docking , Blockchain smart contract must be able to be combined with smart wallet .

truffle

Is a virtual machine based on Ethereum (EVM) Localized smart contract development environment , Test framework and chaining tools .

geth

geth You can build a complete Ethereum node , I won't give you too much introduction here , Because development uses local memory to virtualize Ganache That's enough .

Ganache

Ganache You can quickly start the personal Ethereum blockchain , And you can use it to run tests , Carry out orders 、 Check status , At the same time, control the operation mode of the chain .

node js

I introduced web3.0 Our technical solutions are based on npm Installed , Include truffle,Ganache Are based on npm install . The following article assumes that everyone knows node js knowledge .

Start coding

The portable solidity Voting code

db7289d24040bcebb5af47d086782df8.png

Here is a simple contract about voting

pragma solidity ^0.4.0;
contract Voting{
// Voting list
bytes32[] public candidateList;
// The corresponding number of votes
mapping(bytes32=>uint8) public votesReceived;
// Construct a voting list
constructor(bytes32[] memory candidateListName) public{
candidateList = candidateListName;
}
// Judge whether the voting information is on the waiting list
function valiCandidate(bytes32 candidateName) internal view returns(bool)
{
for(uint8 i=0;i〈candidateList.length;i++)
{
if (candidateName==candidateList[i])
{
return true;
}
}
return false;
}
// Increase voting for voters
function voteForCandidate(bytes32 candidateName) public{
require(valiCandidate(candidateName));
votesReceived[candidateName] = votesReceived[candidateName] + 1;
}
function totalVotesFor(bytes32 candidateName) view public returns(uint8){
require(valiCandidate(candidateName));
// Number of votes returned
return votesReceived[candidateName];
}
}

install ganache

Remember to add -g Global installation

npm install ganache-cli -g# 6.12
npm install ganache -g# 7.0
ganache-cli -d # To start it ganache
3a284c6e4485100e118dcea7f2a58a8c.png

install truffle

Remember to add -g Global installation

npm install truffle -g

initialization truffle dapp frame (web3.0)

mkdir voting
cd voting
truffle unbox webpack

The initialized project directory structure is as follows

e6d4963ed0d2dde32b8e50622aaa3cf4.pngAPP Under the directory is a node js Of web3.0 project ;build The following is the compiled directory of the contract, which is used to call ;contracts yes remix The contract written in ,migrations The following is the contract deployment file ;test The directory is the test file ;truffle-config.js It's a configuration file .

truffle-config.js To configure

Uncheck some comments 127.0.0.1 port 8545 Indicates that the link is local Ganache.b16a5689ccfa2307b3436a30a5c097cd.png

take voting.sol Deploy to project contracts Catalog

1227cae95e07ec381456d48a52738d5d.png
truffle compile

The default contract of the project is placed in this directory : Execute the order (truffle compile), Compile , The compilation is completed in build/contracts There will be one more Voting.json file

stay migrations New under the directory 3_deploy_contracts.js file

const Voting = artifacts.require("Voting");
//0x4100000000000000000000000000000000000000000000000000000000000000 representative A
//0x4200000000000000000000000000000000000000000000000000000000000000 representative B
module.exports = function(deployer) {
// Initialize contract The second is the bidding list parameters
deployer.deploy(Voting, ["0x4100000000000000000000000000000000000000000000000000000000000000","0x4200000000000000000000000000000000000000000000000000000000000000"]);
};

Carry out orders :truffle migrate // Deployment contract

truffle migrate

d2afb41d564a0a546da720b8941832a8.pngcontract address Is the address of the contract account Is the address of the deployment account .

app Directory code implementation and operation

stay app/src/ There are voting.js and voting.html Two documents :

voting.js Code :

import Web3 from "web3";
import votingArtifact from "../../build/contracts/Voting.json";
const aInBytes32 ="0x4100000000000000000000000000000000000000000000000000000000000000";
const bInBytes32 ="0x4200000000000000000000000000000000000000000000000000000000000000";
const App = {
web3: null,
account: null,
meta: null,
start: async function() {
const { web3 } = this;
try {
const networkId = await web3.eth.net.getId();
const deployedNetwork = votingArtifact.networks[networkId];
this.voting = new web3.eth.Contract(
votingArtifact.abi,
deployedNetwork.address,
);
const accounts = await web3.eth.getAccounts();
this.account = accounts[0];
this.ready();
this.refreshBalance();
} catch (error) {
console.error("Could not connect to contract or chain.");
}
},
ready:async function(){
try{
this.refresh("Alice",aInBytes32);
this.refresh("Bob",bInBytes32);
}catch(err){
console.log(err)
}
},
refresh:async function(id,nameBytes32){
const {totalVotesFor} = this.voting.methods;
const tickets = await totalVotesFor(nameBytes32).call();
const el = document.getElementById(id);
el.innerHTML = tickets.toString();
},
voteForCandidate:async function(){
try{
const {voteForCandidate} = this.voting.methods;
const condidateName = document.getElementById("candidate").value;
console.log(condidateName)
if (condidateName == "Alice")
{
await voteForCandidate(aInBytes32).send({from:this.account});
this.refresh("Alice",aInBytes32);
}
else{
await voteForCandidate(bInBytes32).send({from:this.account});
this.refresh("Bob",bInBytes32);
}
}catch(err){
console.log(err)
}
}
};
window.App = App;
window.addEventListener("load", function() {
if (window.ethereum) {
// use MetaMask's provider
App.web3 = new Web3(window.ethereum);
window.ethereum.enable(); // get permission to access accounts
} else {
console.warn(
"No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
App.web3 = new Web3(
new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
);
}
App.start();
});

First line import web3; The second line imports the voting contract ; Three or four lines are two voting items

import Web3 from "web3";
import votingArtifact from "../../build/contracts/Voting.json";
const aInBytes32 ="0x4100000000000000000000000000000000000000000000000000000000000000";
const bInBytes32 ="0x4200000000000000000000000000000000000000000000000000000000000000";

This code obtains the blockchain's network and wallet accounts , initialization voting contract

start: async function() {
const { web3 } = this;
try {
// get contract instance
const networkId = await web3.eth.net.getId();
const deployedNetwork = votingArtifact.networks[networkId];
this.voting = new web3.eth.Contract(
votingArtifact.abi,
deployedNetwork.address,
);
// get accounts
const accounts = await web3.eth.getAccounts();
this.account = accounts[0];
this.ready();
this.refreshBalance();
} catch (error) {
console.error("Could not connect to contract or chain.");
}
},
});

Voting method

voteForCandidate:async function(){
try{
const {voteForCandidate} = this.voting.methods;
const condidateName = document.getElementById("candidate").value;
console.log(condidateName)
if (condidateName == "Alice")
{
await voteForCandidate(aInBytes32).send({from:this.account});
this.refresh("Alice",aInBytes32);
}
else{
await voteForCandidate(bInBytes32).send({from:this.account});
this.refresh("Bob",bInBytes32);
}
}catch(err){
console.log(err)
}
}

voting.html Code

<!DOCTYPE html>
<html>
<head>
<title>My Voting Dapp</title>
</head>
<style>
input {
display: block;
margin-bottom: 12px;
}
</style>
<body>
<h1>Voting Dapp</h1>
<p>Alice <strong id="Alice">loading...</strong> tickets</p>
<p>Bob <strong id="Bob">loading...</strong> tickets</p>
<input type="text" id="candidate" />
<button onclick="App.voteForCandidate()">Send</button>
<script src="voting.js"></script>
</body>
</html>

initialization DAPP Project and launch

npm install
npm run dev

dafbead345261405879bf248f0a6f168.png visit http://localhost:8080/voting.html100f406ada124d85594060eaa271518d.png Input Alice--》 Click on send(matemask The wallet will tell you what you need to spend eth Just confirm , I this is a local analog currency, just spend it )228c13bf34160fb5b3088817cc1e9fc4.png After confirmation, you will find Alice The number of votes becomes 2 了 , This one is on the blockchain and cannot be changed in series .

96fdad6293833a08d8ef3e573cbccb23.png

summary

In the contract solidity In language storage It takes time gas Will permanently exist in the block , We used this feature to write the voting contract , Such a vote will not be changed for a long time , There is another kind. memory There is memory, no need to spend gas. So we can find web3.0 Or say dapp That is to save the content that needs credit guarantee in the blockchain through smart contract , Play the role of decentralized trust , It also ensures the guarantee of ownership . In this way web3.0 It also provides the right confirmation function and ownership for the previous read-write network , The cornerstone of laying the foundation for the meta universe .

版权声明:本文为[bluishfish]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2022/04/202204061243285985.html