【Ethereum Development 05】Web3.js

In the formal development environment, we generally do not use remix to compile and deploy contracts, but use goland to call web3 for development.
Web3 working mode :
insert image description here

1. Development environment

Create a react project using the footlock, initialize the NPM project, execute the following command, and create package.json, a file describing the properties of the current module.

npm init

All the way yes down.
The directory structure of the project is as follows:
insert image description here

2. web3 compile contract

2.1 Install the compiler

npm install --save solc

Will add dependencies in package.json
insert image description here

2.2 Write contract test.sol

pragma solidity ^0.4.0;
contract TestCon{
    
    
    string str;
    constructor(string _str) public{
    
    
        str=_str;
    }
    function setValue(string _str)public{
    
    
        str=_str;
    }
    function getValue() public view returns(string){
    
    
        return str;
    }
}

2.3 Compile file 01-compile.js

//导入solc编译器
let solc = require('solc') //0.4.25

let fs = require('fs')

//读取合约
let sourceCode = fs.readFileSync('./contracts/SimpleStorage.sol', 'utf-8')

// Setting 1 as second paramateractivates the optimiser
let output = solc.compile(sourceCode, 1)

 // console.log('output :', output)
//{age : 17, name : 'lily', address : 'sz'}
module.exports = output['contracts'][':SimpleStorage']

2.3 Compile the contract

Excuting an order

node 01-compile.js

3. web3 deployment contract

let {
    
    bytecode, interface} = require('./01-compile')

// console.log(bytecode)
// console.log(interface)

//1. 引入web3

let Web3 = require('web3')
//2. new 一个web3实例
let web3 = new Web3()
//3. 设置网络

web3.setProvider('http://localhost:7545')

const account = '0xd5957914c31E1d785cCC58237d065Dd25C61c4D0'

console.log('version :', web3.version)
// console.log(web3.currentProvider)

//1. 拼接合约数据 interface
let contract = new web3.eth.Contract(JSON.parse(interface))

//2. 拼接bytecode
contract.deploy({
    
    
    data: bytecode, //合约的bytecode
    arguments: ['HelloWorld'] //给构造函数传递参数,使用数组
}).send({
    
    
    from: account,
    gas: '3000000',
    //gasPrice: '1',
}).then(instance => {
    
    
    console.log('address :', instance.options.address)
})

4. Get the contract instance

//获取合约实例,导出去

//let {bytecode, interface} = require('./01-compile')

//1. 引入web3

let Web3 = require('web3')
//2. new 一个web3实例
let web3 = new Web3()
//3. 设置网络

web3.setProvider('http://localhost:7545')

let abi = [{
    
    "constant":true,"inputs":[],"name":"getValue","outputs":[{
    
    "name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{
    
    "constant":false,"inputs":[{
    
    "name":"_str","type":"string"}],"name":"setValue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{
    
    "inputs":[{
    
    "name":"_str","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]
let address = '0x0FE5006b70A0D58AD3c4d4BC9DAC02C970510Cf6'


//此处abi已经json对象,不需要进行parse动作
let contractInstance = new web3.eth.Contract(abi, address)

console.log('address :', contractInstance.options.address)

module.exports = contractInstance

5. Call the contract

//1. 导入合约实例

//2. 读取数据

//3. 写入数据

//4. 读取数据


let instance = require('./03-instance')
const from = '0xd5957914c31E1d785cCC58237d065Dd25C61c4D0'

//异步调用,返回值是一个promise
//2. 读取数据
instance.methods.getValue().call().then(data => {
    
    
    console.log('data:', data)

    //3. 写入数据
    instance.methods.setValue('Hello HangTou').send({
    
    
        from: from,
        value: 0,
    }).then(res => {
    
    
        console.log('res : ', res)

        //4. 读取数据
        instance.methods.getValue().call().then(data => {
    
    
            console.log('data2:', data)
        })
    })
})

6. Use promise to rewrite

//web3与区块链交互的返回值都是promise,可以直接使用async/await

let test = async () => {
    
    
    try {
    
    
        let v1 = await instance.methods.getValue().call()
        console.log('v1:', v1)

        let res = await  instance.methods.setValue('Hello HangTou').send({
    
    
            from: from,
            value: 0,
        })

        console.log('res:', res)

        let v2 = await instance.methods.getValue().call()

        console.log('v2:', v2)
    } catch (e) {
    
    
        console.log(e)
    }
}

test()

Guess you like

Origin blog.csdn.net/weixin_42918559/article/details/125129010