//导入solc 编译器 let solc = require(‘solc‘) let fs = require(‘fs‘) //读取合约 let sourceCode = fs.readFileSync(‘./contracts/SimpleStorage.sol‘,‘utf-8‘) //var input = ‘contract x { function g() {} }‘ // Setting 1 as second paramateractivates the optimiser //编译合约 let output = solc.compile(sourceCode, 1) module.exports = output[‘contracts‘][‘:SimpleStorage‘]
部署合约
let {bytecode, interface} = require(‘./01-complie‘) //console.log(bytecode) //console.log(interface) // 1.引入web3 let Web3 = require(‘web3‘) // 2.new 一个web3实例 let web3 = new Web3() // 3.设置网络 let isConnect = web3.setProvider(‘http://localhost:7545‘) const account = ‘0x975938478Fa7359567b84E9c9ccc20b2aac23066‘ //console.log(isConnect) //console.log("version:", web3.version) //console.log(web3.eth.currentProvider) // 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) }); // 3. 合约部署
获取合约实例
//获取 合约实例,导出合约实例 let {bytecode, interface} = require(‘./01-complie‘) // 1.引入web3 let Web3 = require(‘web3‘) // 2.new 一个web3实例 let web3 = new Web3() // 3.设置网络 let isConnect = web3.setProvider(‘http://localhost:7545‘) // 合约的abi let abi = [{"constant":false,"inputs":[{"name":"message","type":"string"}],"name":"setMessage","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getMessage","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"str","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}] //合约地址 let address = ‘0x7f61E1A3970777C3C25DA410fD6E2c3CfCFB953a‘; //此处abi 已经是json对象了不需要进行parse动作 let contractInstance = new web3.eth.Contract(abi,address); //console.log(‘address‘,contractInstance.options.address); module.exports = contractInstance;
调用合约
//1 .导入合约实例let instance = require(‘./03-instance‘);const from = ‘0x4E4c6a3655A5863089f9341ff61D3d8BeE00384a‘; //异步调用,返回值是一个promise//2。读取数据/*instance.methods.getMessage().call().then(data => { console.log(‘data: ‘, data); //3.写入数据 instance.methods.setMessage(‘Hello JackLuo‘).send({ from: from, value: 0 }).then(res => { //4.读取数据 console.log(‘res :‘, res) instance.methods.getMessage().call().then(data => { console.log(‘data2: ‘, data); }) })});*/ // web3与区块链交互的返回值都是promise,可以直接使用async/awaitlet test = async () => { try { let v1 = await instance.methods.getMessage().call() console.log(‘v1:‘, v1) let res = await instance.methods.setMessage(‘Hello Jackluo‘).send({ from: from, value: 0 }); console.log(‘res:‘, res) let v2 = await instance.methods.getMessage().call() console.log(‘v2:‘, v2) } catch (e) { console.log(e) }}; test();
原文地址:https://www.cnblogs.com/jackluo/p/12016536.html
时间: 2024-11-09 10:44:05