win10环境下web3智能合约开发

1.使用 create-react-app 快速构建 React 开发环境

cnpm install -g create-react-app
create-react-app meetweb3
cd meetweb3
npm start

在浏览器中打开 http://localhost:3000/ 

2.新建文件和文件夹,整体目录结构

meetweb3
  |--contracts
    |--SimpleStorage.sol
  |--node_modules
  |--public
  |--src
  |--.gitignore
  |--01-compile.js
  |--02-deploy.js
  |--03-instance.js
  |--04-interaction.js
  |--package.json
  |--README.md
  |--yarn.lock

 

3.JetBrains GoLand运行solc(已经安装)

1.安装插件Intellij-Solidity-2.1.6
官方地址:https://plugins.jetbrains.com/plugin/9475-intellij-solidity
百度网盘:链接: https://pan.baidu.com/s/1QtkhDuL-7JsAYRE_kJx8UA  提取码: awfm 

 

2.JetBrains Goland 配置
a. File -> settings -> Plugins -> 设置 -> Install plugin from disk... -> Intellij-Solidity-2.1.6.zip -> OK
以上通过本地安装好插件
b. File -> settings -> Tools -> External Tools -> + -> Edit Tool:
        Name:Solidity
        Program:D:\python\nodejs\solcjs.cmd
        Arguments:--abi --bin $FileName$ -o $FileDir$\out\$FileNameWithoutExtension$
        Working directory:$FileDir$
   -> OK
以上完成了自定义External Tools的工具。
使用:
在合约中点击鼠标右键 -> External Tools -> Solidity

 

3.运行后的结果
在当前目录下自动创建out文件夹和与合约同名的文件夹,合约同名文件夹中产生了.abi和.bin文件。

 

4.JetBrains Goland 配置Nodejs环境

1.官方插件地址:https://plugins.jetbrains.com/plugin/6098-nodejs/versions
注意版本的选择,node和插件版本不同可能会报错
C:\Users\admin>node --version
v8.7.0
选用NodeJS-191.7479.1.zip
2.百度网盘:
链接: https://pan.baidu.com/s/1dQf42LQA7q9eQiWnKzTTHQ 提取码: dddh
2.插件安装
方法同上面的solidity插件安装一样
3.配置
a. File -> Settings -> Language&Frameworks -> JavaScript -> JavaScript Language version:ECMAScript6 -> OK
b. File -> Settings -> Language&Frameworks -> JavaScript -> Libraries -> New Library:
    Name:node
    Framework type:Nodejs Core Modules
    -> OK

  

5.编写solidity合约代码

pragma solidity >=0.4.25 <=0.6.0;

contract SimpleStorage {
    string str;

    constructor(string memory _str) public {
        str = _str;
    }

    function setValue(string memory _str) public {
        str = _str;
    }

    function getValue() public view returns (string memory) {
        return str;
    }
}

 

6.编写compile.js

let solc = require('solc')

let fs = require('fs')

let contractCode = fs.readFileSync('./contracts/SimpleStorage.sol', 'utf-8')

let output = solc.compile(contractCode, 1)

console.log('output:', output)

module.exports = output['contracts'][':SimpleStorage']

7.编写deploy.js

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

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

let Web3 = require('web3')
let web3 = new Web3()

web3.setProvider('http://127.0.0.1:8545')

const account = '0x3fe4cf9ac113b4a531024b046fab8b5c9e5f64a5'

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

let  contract = new web3.eth.Contract(JSON.parse(interface))
contract.deploy({
    data: bytecode,
    arguments: ['HelloWorld']
}).send({
    from: account,
    gas: '3000000',
}).then(instance => {
    console.log('address: ', instance.options.address)
})

8.安装web3js

1.Github下载地址:https://github.com/ethereum/web3.js/releases
2.选择版本https://github.com/ethereum/web3.js/releases/tag/v1.0.0-beta.35 使用1.0.0-beta35版本
3.百度网盘:链接: https://pan.baidu.com/s/18Cx_PuvRBW2lJRpYuk9RFA 提取码: yj9f 
4.如果是Github下载的源代码,找到packages/web3
  或者百度网盘下载的源代码,解压重命名web3
5.安装python2,配置好python2环境变量
6.将web3放在项目node_modules文件夹中,进入web3
7.使用Git Bash运行:cnpm install
8.安装web3后,进入node测试
    > let Web3 = require('web3')
    > let web3 = new Web3()
    > web3.version
    '1.0.0-beta.35'
9.启动ganache-cli
10.修改deploy.js中的account地址
11.运行deploy.js

 

 9.编写intance.js

let Web3 = require('web3')

let web3 = new Web3()

web3.setProvider('http://127.0.0.1:8545')

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 = '0x99b80C5DB381630AAA043b6F27ED65761358b1eb'

let contractInstance = new web3.eth.Contract(abi, address)

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

module.exports = contractInstance

10.编写interaction.js

let instance = require('./03-instance')

const from = '0x3fe4cf9ac113b4a531024b046fab8b5c9e5f64a5'

// instance.methods.getValue().call().then(data => {
//     console.log('data', data)
//     instance.methods.setValue('Hello Python').send({
//         from: from,
//         value:0,
//     }).then(res => {
//         console.log('res:', res)
//
//         instance.methods.getValue().call().then(data =>{
//             console.log('data',data)
//         })
//     })
// })

let test = async () => {
    try{
        let value1 = await instance.methods.getValue().call()
        console.log("value:", value1)
        let res = await instance.methods.setValue('Hello, Golang').send({
            from: from,
            value: 0,
        })
        console.log("res:", res)
        let value2 = await  instance.methods.getValue().call()
        console.log("value2:", value2)
    }catch (e) {
        console.log(e)
    }
}
test()

运行结果:

 

 

11.补充:solc安装

1.配置好python2的环境
2.在项目文件夹中和node安装目录中都用Git bash 执行npm install solc@0.4.25
solc不指定版本,可能安装别的版本(0.5.1),运行程序时会报错,一直没办法解决。后来指定安装0.4.25问题都解决了。

12.要测试网络中部署合约,先准备有以太币的账户  

1.测试水管网站:https://faucet.ropsten.be/
2.限制每隔24小时领取1ther

13.注册infura

1.网站:https://infura.io/
2.获取测试网络ENDPOINT,程序中使用:https://ropsten.infura.io/v3/c0521a4ac29145e5808040a85fe9d9f0

14.向测试网络中部署合约,重新编写deploy.js

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

let HDWalletProvider = require('truffle-hdwallet-provider')
let Web3 = require('web3')
let web3 = new Web3()

let terms = 'your Account wolds......'
let netIp = 'https://ropsten.infura.io/v3/c0521a4ac29145e58080......'

let provider = new HDWalletProvider(terms, netIp)

//web3.setProvider('http://127.0.0.1:8545')
web3.setProvider(provider)

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

console.log('0x'+bytecode) 

let  contract = new web3.eth.Contract(JSON.parse(interface))
//let contract = new web3.eth.Contract(bb)
// contract.deploy({
//     data: bytecode,
//     arguments: ['HelloWorld']
// }).send({
//     from: account,
//     gas: '3000000',
// }).then(instance => {
//     console.log('address: ', instance.options.address)
// })
//
let deploy = async () =>{
    let accounts = await web3.eth.getAccounts()
    console.log("accounts:", accounts)

    let instance = await  contract.deploy({
        data: '0x'+bytecode,
        arguments: ['HelloWorld']
    }).send({
        from: accounts[0],
        gas: '3000000',
    })
    console.log('instance address:', instance.options.address)
}

deploy()
1.上面的bytecode跟着示例直接用总是报错,上链的数据不一样,是经过了两次utf-8。使用'0x'进行拼接之后,上链的数据就正确了。

15.重新编写instance.js

let {interface} = require('./01-compile')
let Web3 = require('web3')
let HDWalletProvider = require('truffle-hdwallet-provider')

let web3 = new Web3()

let terms = 'your Account worlds......'
let netIp = 'https://ropsten.infura.io/v3/c0521a4ac29145e58080......'
let provider = new HDWalletProvider(terms, netIp)

//web3.setProvider('http://127.0.0.1:8545')
web3.setProvider(provider)

console.log('===============================================')
console.log(interface)

let abi = JSON.parse(interface)
let address = '0x5dFDB758ee9b87a72401789f43b7C9e5a2F2Be3D'

let contractInstance = new web3.eth.Contract(abi, address)

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

module.exports = contractInstance

16.重新编写interaction.js

let instance = require('./03-instance')

let Web3 = require('web3')
let HDWalletProvider = require('truffle-hdwallet-provider')

let terms = 'your account words......'
let netIp = 'https://ropsten.infura.io/v3/c0521a4ac29145e58080......'

let web3 = new Web3()
let provider = new HDWalletProvider(terms, netIp)

web3.setProvider(provider)

//const from = '0x3fe4cf9ac113b4a531024b046fab8b5c9e5f64a5'

// instance.methods.getValue().call().then(data => {
//     console.log('data', data)
//     instance.methods.setValue('Hello Python').send({
//         from: from,
//         value:0,
//     }).then(res => {
//         console.log('res:', res)
//
//         instance.methods.getValue().call().then(data =>{
//             console.log('data',data)
//         })
//     })
// })

let test = async () => {
    try{
        let accounts = await web3.eth.getAccounts()
        from = accounts[0]
        let value1 = await instance.methods.getValue().call()
        console.log("value:", value1)
        let res = await instance.methods.setValue('Hello, Golang').send({
            from: from,
            value: 0,
        })
        console.log("res:", res)
        let value2 = await  instance.methods.getValue().call()
        console.log("value2:", value2)
    }catch (e) {
        console.log(e)
    }
}
test()

转载于:https://www.cnblogs.com/zhangkaipc/p/11308951.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值