__

操作步骤

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

                   *
    // 引入包 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. 设置测试网络 infuralet 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[1] --save

什么是 Infura

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

•专业一点讲,Infura 是一种 IaaS (Infrastructure as a Service)产品,目的是为了降低访问以太坊数据的门槛。•通俗一点讲,Infura 就是一个可以让你的 dApp 快速接入以太坊的平台,不需要本地运行以太坊节点。•从程序员的角度讲,Infura 就是一个 Web3 Provider,背后是负载均衡的 API 节点集群。使用它的好处就是,你永远不必担心连接的节点失效的问题,Infura 会管理好这一切。

代码修改

02-deploy

    let {bytecode, interface} = require('./01-compile')  
    //1. 引入 web3let 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. 设置测试网络 infuralet 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. 设置测试网络 infuralet 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. 设置测试网络 infuralet 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()  

结果展示

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

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

References

[1] truffle-hdwallet-provider@0.0.3: mailto:truffle-hdwallet-provider@0.0.3


本文作者:potaxie

作者主页

https://learnblockchain.cn/people/633


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

来源链接:mp.weixin.qq.com