2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Here is the interaction between the browser and the smart contract
Two libraries
Web3
Truffle contract //Truffle simply wraps the front-end contract in the link, which is more convenient to use
comeReact ProjectIn the root directory of (created in Chapter 1),
Recreate a react project here
https://blog.csdn.net/u012118993/article/details/87288516
React creates a new project Use creat-react-app to quickly create a react project
(1)npm install -g create-react-app
Install globally (install to the whole system)
(2)create-react-app reactproject
Create a new react project and name it (note: the project name cannot be capitalized)
(3)cd reactproject
Enter the folder through the command and prepare to run the project
(4)npm start
Run the project
E:trufflewoniu-pet-shop
Create in the truffle directory
Install the following files in the react project
Install web3 (install to the folder below)
npm install web3 --save
Then install truffle-contract
npm install truffle-contract --save
Demo Completed
1. Linking Contract
2. Execute the internal functions of the contract
3. Add ant.design ui library support
4. Complete the project
Note the new
Contents of App.js
as follows
import React from 'react'
import Web3 from 'web3'
import TruffleContract from 'truffle-contract'
import AdoptionJson from './truffle/build/contracts/Adoption.json' //引入前面智能合约编译好得到的json文件
class App extends React.Component{
constructor(props){
super(props)
this.web3 = null
this.Adoption = null
this.init()
this.state = {
//name:'woniu'
}
}
init(){
//如果网页中的web3不是undefined
if(typeof window.web3 != 'undefined'){
}
}
render(){
return <button></button>//hello,{this.state.name}
}
}
export default App
If the metamask plugin is installed in the browser
In the browser, global variables have values
You can manually connect to metamask or automatically connect
Start the script. Previously, web3 was undefined in the browser console because the webpage was empty.
Start in the petshop built by the react project
Npm start
Open in browser
http://localhost:3000/
Video effects
Video Installing a New Package
There is an error in my own, because the init function is not saved
The actual effect after success is as follows
newly joined
init(){
//如果网页中的web3不是undefined
if(typeof window.web3 != 'undefined'){
this.web3Provider = window.web3.currentProvider; //metamask内置了web3的实例,实际可以手动链接
}else{
alert('请按照metamask')
}
}
After changing the code and saving it, you can access the network again without shutting down and restarting npm start
Refresh now
Of course, there is no pop-up window at this time. After deleting the metamask wallet, there will be a pop-up window
At this time, use chrome browser without wallet to access
A pop-up window appears, but some of the characters are garbled.
Add code
All the codes are as follows
import React from 'react'
import Web3 from 'web3'
import TruffleContract from 'truffle-contract'
import AdoptionJson from './truffle/build/contracts/Adoption.json' //引入前面智能合约编译好得到的json文件
//1.链接合约
//2.执行一下合约内部函数
//3.添加ant.design ui库支持
//4.完成项目
class App extends React.Component{
constructor(props){
super(props)
this.web3 = null
this.Adoption = null
this.init()
this.state = {
//name:'woniu'
}
}
init(){
//如果网页中的web3不是undefined
if(typeof window.web3 != 'undefined'){
this.web3Provider = window.web3.currentProvider; //metamask内置了web3的实例,实际可以手动链接
}else{
alert('please install metamask')
}
this.web3 = new Web3(this.web3Provider) //将我们的this.web3Provider装载进来
this.initAdoption()
}
initAdoption(){
this.Adoption = TruffleContract(AdoptionJson) //使用TruffleContract传入编译后的合约,然后创建实例,可以调用合约内部函数
this.Adoption.setProvider(this.web3Provider) //设置来源,链接合约
return this.markAdopted()
}
//部署,这个是异步的,使用this.Adoption.deployed().then()也可以,这里用
//this.markAdopted(){
//部署链接一下
// const adoptionInstance = this.Adoption.deployed().then()
//}
async markAdopted(){
//部署链接一下
//await同步方式获取异步数据
const adoptionInstance = await this.Adoption.deployed() //部署,这个是异步的,使用this.Adoption.deployed().then()也可以,这里用
//调用合约内部函数getAdopters
const adopters = await adoptionInstance.getAdopters.call()
console.log(adopters)
}
render(){
return <button></button>//hello,{this.state.name}
}
}
export default App
The refresh interface is as follows
Get the address of the contract
Use the variables above to get the local address and the default account address of metamask
https://blog.csdn.net/weixin_41937552/article/details/106990561?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242
The reason why the metamask address cannot be obtained here is as above
https://blog.csdn.net/weixin_39421014/article/details/103323245
You can turn off the privacy permission of metamask first
https://www.freesion.com/article/8518937500/
Privacy mode settings and compatible JS code
https://blog.csdn.net/JackieDYH/article/details/115380677?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-0&spm=1001.2101.3001.4242
Get account information
After the code is modified, modify it in the initialization function part.
You can use metamask to link to the website and print out the current metamask address
Next, change the code for the click event
Clicking on adoption here will pop up a box for payment, because you need to call the write function and write it to the chain. The adoption here does not require money transfer but requires the parent fee.
The local function that needs to be written to the blockchain is successfully called (as shown below when the button is clicked)
All the codes that finally ran successfully are as follows:
import React from 'react'
import Web3 from 'web3'
import TruffleContract from 'truffle-contract'
import AdoptionJson from './truffle/build/contracts/Adoption.json' //引入前面智能合约编译好得到的json文件
//1.链接合约
//2.执行一下合约内部函数
//3.添加ant.design ui库支持
//4.完成项目
class App extends React.Component{
constructor(props){
super(props)
this.web3 = null
this.Adoption = null
this.init()
this.state = {
//name:'woniu'
}
}
async init(){
//如果网页中的web3不是undefined
//if(typeof window.web3 != 'undefined'){
// this.web3Provider = window.web3.currentProvider; //metamask内置了web3的实例,实际可以手动链接
//}else{
// alert('please install metamask')
//}
//this.web3 = new Web3(this.web3Provider) //将我们的this.web3Provider装载进来
//this.initAdoption()
/* 新版的方式 */
//var web3Provider;
if (window.ethereum) {
this.web3Provider = window.ethereum;
try {
// 请求用户授权
await window.ethereum.enable();
} catch (error) {
// 用户不授权时
console.error("User denied account access")
}
} else if (window.web3) { // 老版 MetaMask Legacy dapp browsers...
this.web3Provider = window.web3.currentProvider;
} else {
this.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
this.web3 = new Web3(this.web3Provider);//web3js就是你需要的web3实例
this.web3.eth.getAccounts(function (error, result) {
if (!error)
console.log(result)//授权成功后result能正常获取到账号了
//this.account = result
});
//this.account =result
//this.account =account
this.initAdoption()
}
initAdoption(){
this.Adoption = TruffleContract(AdoptionJson) //使用TruffleContract传入编译后的合约,然后创建实例,可以调用合约内部函数
this.Adoption.setProvider(this.web3Provider) //设置来源,链接合约
return this.markAdopted()
}
//部署,这个是异步的,使用this.Adoption.deployed().then()也可以,这里用
//this.markAdopted(){
//部署链接一下
// const adoptionInstance = this.Adoption.deployed().then()
//}
async markAdopted(){
//部署链接一下
//await同步方式获取异步数据
const adoptionInstance = await this.Adoption.deployed() //部署,这个是异步的,使用this.Adoption.deployed().then()也可以,这里用
//调用合约内部函数getAdopters
const adopters = await adoptionInstance.getAdopters.call()
console.log(adopters)
}
async adopt(petId){
//const account = window.web3.eth.defaultAccount //获取metamask中默认的账户
// 授权获取账户
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
const myAccount = accounts[0]; //获取当前metamask的地址
const adoptionInstance = await this.Adoption.deployed() //再次进行部署
await adoptionInstance.adopt(petId,{from:myAccount}) //调用adopt只传递唯一一个参数,以及来源之前获取的地址,进行写入函数
this.markAdopted()
}
render(){
//onclick点击事件,调用领养函数
return <button onClick={()=>this.adopt(2)}>领养第二个</button>//hello,{this.state.name}
}
}
export default App
All functions have been successfully executed, read and write functions
This code has some defects. If the transaction fails, an error will be reported, and the page will also report an error.
Click Reject or exit directly
The next step is to beautify the UI