首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >本地开发环境以太坊合约交互实战

本地开发环境以太坊合约交互实战

作者头像
Tiny熊
发布2020-06-30 15:52:41
发布2020-06-30 15:52:41
1.2K0
举报

操作步骤

代码语言:javascript
复制
所有的操作都是在goland里面使用nodejs调web3库

•编写合约•编译合约(web3)-用solc编译(拿到bytecode、abi)•部署合约(web3)•找到合约实例•调用合约(set,get操作)

开发环境

代码语言:javascript
复制
//安装某宝的镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org


//安装指定版本solc
 cnpm install solc@0.4.24

//安装create-react-app
npm install create-react-app -g


//创建空的react项目
create-react-app project

//进入到project中
npm run start


//安装web3
npm i web3 --save

web3模块划分:

•web3-eth:与blockchain合约相关的模块•web3-shh:与p2p协议广播相关•web3-bzz:与swarm存储协议相关•web3-utils:开发者工具相关

a.部署合约时候,需要用到提供abi,即可执行后面的动作,进行部署 b.获取合约实例的时候需要用到这个函数,指定abi,指定address

代码语言:javascript
复制
Ganache用于搭建私有网络。在开发和测试环境下,Ganache提供了非常简便的以太坊私有网络搭建方法,
通过可视化界面可以直观地设置各种参数、浏览查看账户和交易等数据

代码加注解

01-compile

代码语言:javascript
复制
//导入solc编译器
var solc = require('solc')

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


let output = solc.compile(sourceCode, 1)
console.log('output:', output)

console.log('abi:______',output['contracts'][':SimpleStorage']['interface'])

//导出合约
module.exports = output['contracts'][':SimpleStorage']

02-deploy

代码语言:javascript
复制
let {bytecode, interface} = require('./01-compile')


// console.log('bytecode_____',bytecode)
// console.log('interface____',interface)


//1.引入web3

let Web3 = require('web3')

//2.new一个web3实例
let web3 = new Web3()

//3.设置网络
web3.setProvider('http://localhost:7545')

console.log('version:________', web3.version)
console.log('web3-eth.curretProvider_____________', web3.currentProvider)


//此地址需要使用Ganache地址
const account ='0xd4DB91aCBB5Be2a42276567c7473857e14888B53'

//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)
})

03-instance

代码语言:javascript
复制
//获取合约实例,导出去
//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 = '0x7a0402FDB3de50eBEBe77F0ff72A6b7526e92447' //此处是合约地址
//此处abi已经json对象,不需要进行parse动作
let contractInstance = new web3.eth.Contract(abi, address)
console.log('address__________', contractInstance.options.address)
module.exports = contractInstance

04-interaction

代码语言:javascript
复制
//1.导入合约实例
let instance = require('./03-instance')
const from = '0xd4DB91aCBB5Be2a42276567c7473857e14888B53'

//异步调用,返回值是一个promise
//2.读取数据

//整体封装成函数
//web3和区块链交互的返回值都是promise,可以直接使用async

let test = async () => {

    try {
        let y1 = await instance.methods.getValue().call()

        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()

调用结果

git地址 https://github.com/potaxie/web3


本文作者:potaxie

作者主页:

https://learnblockchain.cn/people/633

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-06-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 深入浅出区块链技术 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 操作步骤
  • 开发环境
  • web3模块划分:
  • 代码加注解
    • 01-compile
    • 02-deploy
    • 03-instance
    • 04-interaction
  • 调用结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档