-
1.环境安装:
- 安装node.js 和 npm安装包:
- 通过npm安装 web3. js:
-
通过npm安装 编译器 solc:
-
编译IDE 安装 solidity nodejs 插件
-
合约整体四步走流程
+### 2. 合约编译:
注:可以通过solidity 的在线编译工具 remix 实现 编译, 部署, 交互等操作。
- 导入solidity编译器 solc(版本:0.4.25)
2.通过fs 包读取智能合约代码
let sourceCode = fs.readFileSync('./contracts/Lottery.sol', 'utf-8')
- 合约编译
let output = solc.compile(sourceCode, 1)
- 导出bytecode 和ABI
module.exports = output['contracts'][':Lottery']
-
示例代码:
//导入solc编译器
let solc = require('solc') //0.4.25
// 导入文件处理包
let fs = require('fs')
//读取合约
let sourceCode = fs.readFileSync('./contracts/Lottery.sol', 'utf-8')
let output = solc.compile(sourceCode, 1)
// console.log('output :', output)
//{age : 17, name : 'lily', address : 'sz'}
// 导出 编译后的合约bytecode 和ABI
module.exports = output['contracts'][':Lottery']
-
3. 合约部署(这边使用的是测试网络 ropsten):
1. 创建一个provider:
通过 https://infura.io](https://infura.io/去创建对应的netIp
或者使用ganache 创建本地的私有网络(127.0.0.1: 端口号)如下图
// 导入 HDwalletProvider包
let HDWalletProvider = require('truffle-hdwallet-provider')
//2. new 一个web3实例
let web3 = new Web3()
//3. 导入助记词
let terms = 'spider owner element skate dress mad gaze ticket message practice opinion diet'
// rpc 网络
let netIp ='https://ropsten.infura.io/v3/30afba8bbf364776a7e46b25ae58e4f0'
// let netIp= 'http;127.0.0.1:7545'---- 使用ganache
let provider = new HDWalletProvider(terms, netIp)
2. 获取助记词对应的账户 然后部署发布合约:
2.1 通过 web3.eth.getAccounts()获取对应助记词的账号(地址)
2.2 拼接ABI 和 bytecode 获取合约示例
web3.eth.Contract , contract.deploy
2.3 支付手续费生成合约,并返回合约实例(instance),可以通过instance.options.address获取此时合约的实例
2.4 通过eth 浏览器 通过合约地址,查看当前部署的合约区块信息
https://ropsten.etherscan.io/(测试网络)
// 获取 编译导出的bytecode 和ABI
let {bytecode, interface} = require('./01.compile')
// 导入web3
let Web3 = require('web3')
// 导入 HDwalletProvider包
let HDWalletProvider = require('truffle-hdwallet-provider')
//2. new 一个web3实例
let web3 = new Web3()
//3. 导入助记词
let terms = 'spider owner element skate dress mad gaze ticket message practice opinion diet'
let netIp ='https://ropsten.infura.io/v3/30afba8bbf364776a7e46b25ae58e4f0'
// let netIp = 'https://ropsten.infura.io/v3/02cd1e3c295c425597fa105999493baa'
//let netIp = 'http://127.0.0.1:7545'
let provider = new HDWalletProvider(terms, netIp)
// web3.setProvider('HTTP://192.168.28.30:7545')
//web3.setProvider('HTTP://127.0.0.1:7545')
web3.setProvider(provider)
//1. 拼接合约数据 interface
let contract = new web3.eth.Contract(JSON.parse(interface))
let deploy = async () => {
//1. 现获取所有的账户
let accounts = await web3.eth.getAccounts()
console.log('accounts :', accounts)
//2. 执行部署
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()
-
4. 获取实例
-
1 通过setProvider 来获取web3 对象
let HDWalletProvider = require('truffle-hdwallet-provider')
//2. new 一个web3实例
let web3 = new Web3()
//3. 导入助记词
let terms = 'spider owner element skate dress mad gaze ticket message practice opinion diet'
// rpc 网络
let netIp ='https://ropsten.infura.io/v3/30afba8bbf364776a7e46b25ae58e4f0'
// let netIp= 'http;127.0.0.1:7545'---- 使用ganache
let provider = new HDWalletProvider(terms, netIp)
web3.setProvider(provider)
module.export=web3
-
2通过ABI和合约地址获取合约示例
先导入1中获取的web3对象
let web3 = require('../utils/initWeb3')
然后获取对应的合约实例
let contractInstance = new web3.eth.Contract(abi, address)
-
示例代码
let web3 = require('../utils/initWeb3')
let abi = [ { "constant": true, "inputs": [], "name": "getBalance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getPlayers", "outputs": [ { "name": "", "type": "address[]" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getPlayersCount", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "manager", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "uint256" } ], "name": "players", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "round", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "winner", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "tuiJiang", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "play", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [], "name": "kaiJiang", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } ]
let address = '0xa3f7418feA6b69A6464058419C66C8fFD5b602de'
//此处abi已经json对象,不需要进行parse动作
let contractInstance = new web3.eth.Contract(abi, address)
console.log('address :', contractInstance.options.address)
module.exports = contractInstance
-
5. 合约交互:
1.导入4中的合约示例:
- 通过contractInstance.methods.(合约中的函数名)来和合约交互
-
示例代码
let contractInstance=require('./eth/contractInstance')
let test=async () {
try {
let manager = await contractInstance.methods.manager().call()
let round = await contractInstance.methods.round().call()
let winner = await contractInstance.methods.winner().call()
let playerCounts = await contractInstance.methods.getPlayersCount().call()
//单位是wei,我们需要转换为ether单位
let balanceWei = await contractInstance.methods.getBalance().call()
//从wei单位转换为'ether'单位
let balance = web3.utils.fromWei(balanceWei, 'ether')
let players = await contractInstance.methods.getPlayers().call()
} catch (e) {
console.log(e)
}
}
网友评论