以太坊真实测试网络合约交互实战

  • potaxie
  • 更新于 2020-06-27 17:13
  • 阅读 4214

本文利用infura和metamask,实现与以太坊测试网络交互

操作步骤

  • 安装truffle-hdwallet-provider
  • 导入包
  • 创建一个provider

编辑注: truffle-hdwallet-provider已经更新为:@truffle/hdwallet-provider

//引入包
let Web3 =require('web3')
let HDWalletProvider = require('truffle-hdwallet-provider')

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

//3.设置metamask Ropsten-network的助记住词,表明花谁的钱
let terms = 'truly state fruit rug decide riot shy lake apple orphan october dinosaur'

//3.设置测试网络 infura
let netIp = 'https://ropsten.infura.io/v3/4c25a49808354c5480f97d4c82117ee4'
let provider = new HDWalletProvider(terms, netIp)
web3.setProvider(provider)

需要填写的数据

  • 助记词,表示花谁的钱--metamask 测试网络 scout same naive genius cannon maze differ acquire penalty habit surround ice
  • 指定一个服务商,让他帮助我们连接到真实网络 https://ropsten.infura.io/v3/4c25a49808354c5480f97d4c82117ee4
  • 需要使用个npm包(接受两个参数:1,2,这个包会帮我们连接到对应网络) npm install truffle-hdwallet-provider@0.0.3 --save

什么是Infura

image.png

  • 专业一点讲,Infura是一种IaaS(Infrastructure as a Service)产品,目的是为了降低访问以太坊数据的门槛。

  • 通俗一点讲,Infura就是一个可以让你的dApp快速接入以太坊的平台,不需要本地运行以太坊节点。

  • 从程序员的角度讲,Infura就是一个Web3 Provider,背后是负载均衡的API节点集群。使用它的好处就是,你永远不必担心连接的节点失效的问题,Infura会管理好这一切。

代码修改

02-deploy

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

//1.引入web3
let Web3 = require('web3')

//引入包
let HDWalletProvider = require('truffle-hdwallet-provider')

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

//3.设置metamask Ropsten-network的助记住词,表明花谁的钱
let terms = 'truly state fruit rug decide riot shy lake apple orphan october dinosaur'

//3.设置测试网络 infura
let netIp = 'https://ropsten.infura.io/v3/4c25a49808354c5480f97d4c82117ee4'
let provider = new HDWalletProvider(terms, netIp)
web3.setProvider(provider)
console.log('version:________', web3.version)
console.log('web3-eth.curretProvider_____________', web3.currentProvider)
//1.拼接合约数据
let contract = new web3.eth.Contract(JSON.parse(interface))
let deploy = async () => {
    //获取所有的账户

    let accounts = await web3.eth.getAccounts()
    console.log('accounts____', accounts)
    //执行部署

    let instance = await contract.deploy({
        data: bytecode,//合约的bytecode
        arguments: ['helloworld']//给构造函数传递参数,使用数组
    }).send({
        from: accounts[0],
        gas: '3000000',
        gasPrice: '1',
    })

    console.log('instance_address_____', instance.options.address)
}

deploy()

03-instance

//引入包
let Web3 =require('web3')
let HDWalletProvider = require('truffle-hdwallet-provider')

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

//3.设置metamask Ropsten-network的助记住词,表明花谁的钱
let terms = 'truly state fruit rug decide riot shy lake apple orphan october dinosaur'

//3.设置测试网络 infura
let netIp = 'https://ropsten.infura.io/v3/4c25a49808354c5480f97d4c82117ee4'
let provider = new HDWalletProvider(terms, netIp)
web3.setProvider(provider)

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 = '0x797Ff2e41b64eD1adfc84cA98afeD00813Dd051D' //此处是合约地址

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

04-interaction

//引入包
let Web3 =require('web3')
let HDWalletProvider = require('truffle-hdwallet-provider')

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

//3.设置metamask Ropsten-network的助记住词,表明花谁的钱
let terms = 'truly state fruit rug decide riot shy lake apple orphan october dinosaur'

//3.设置测试网络 infura
let netIp = 'https://ropsten.infura.io/v3/4c25a49808354c5480f97d4c82117ee4'
let provider = new HDWalletProvider(terms, netIp)
web3.setProvider(provider)

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

let test = async () => {
    try {
        //获取当前区块链的对应助记词的账户地址
        let accounts = await web3.eth.getAccounts()
        let from = accounts[0]
        let y1 = await instance.methods.getValue().call()

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

        console.log('res:', res)
        let v2 = await instance.methods.getValue().call()

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

test()

结果展示

image.png

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

点赞 2
收藏 1
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
potaxie
potaxie
坐标上海 四年大数据+两年区块链工作经验 git地址:https://github.com/potaxie 微信:potaxie