web3.setProvider('HTTP://127.0.0.1:7545');
pragma solidity ^0.4.26; contract hello{ string public name = "jack"; function getName() public view returns (string){ return name; } function steNamt(string myname) public { name = myname; } }
let solc = require('solc') let fs = require('fs') let sourcecode = fs.readFileSync('./contracts/helloname.sol','utf-8') //console.log(sourcecode.toString()) let output = solc.compile(sourcecode, 1) //console.log(output['contracts']) module.exports = output['contracts'][':hello']
let {bytecode, interface} = require("./compile") let Web3 = require("web3") // console.log('bytecode:',bytecode) // console.log('interface:',interface) const account = "0xD5fFa32A808970FAb637AeE4ca70e00888B3e4D8" let web3 = new Web3(); console.log("版本:",web3.version) //1.设置网络 web3.setProvider('HTTP://127.0.0.1:7545'); //console.log(web3.providers) //产看当前的currentProvider //console.log(web3.currentProvider) //2.拼接合约数据 let contract = new web3.eth.Contract(JSON.parse(interface)) //console.log("自己的contract:",contract) web3.eth.defaultAccount = account; //设置默认的账户 console.log(web3.eth.defaultAccount) console.log(contract.defaultBlock) // //3.拼接bytecode contract.deploy({ data:bytecode, arguments: ["success"] }) .send({ from: account, gas: 5721975, gasPrice: '300000000000' }) .then(function(newContractInstance){ //newContractInstance.options.address 得到的是新的合约的地址 console.log(newContractInstance.options.address) // instance with the new contract address });
//获取合约实例 let Web3 = require('web3') let web3 = new Web3() let {bytecode, interface} = require('./compile') let contractAddress = require('./deploy') console.log(interface) console.log(contractAddress) //根据api和address得到合约实例 let contracInstance = new web3.eth.Contract(JSON.parse(interface), contractAddress) console.log(contracInstance)
//1.获取合约实例 let contractInstance = require('./instance') const from = '0xC8147B0093339470dA5aaF4DFF643815c4adA893' contractInstance.methods.getName().call().then(result =>{ //1.读取到合约的结果 console.log("得到的结果:",result) //2.设置合约的变量值 contractInstance.methods.setName("currentJack").send({ from:from, value:0}).then(res =>{ console.log(res) //3.得到新的合约的值 contractInstance.methods.getName().call().then(res=>{ console.log("得到修改后的结果", res) }) }) })
ganache
进去后点quick start
//1.合约的地址 let Web3 = require('web3') let contractAddres = "合约的地址" let {bytecode,interface} = require('./compile') //console.log("得到的interface",interface) let web3 = new Web3() let THP = require('truffle-hdwallet-provider') let terms = '账户的助记词' //2.得到服务商网址 let netip = 'infura创建的项目的url' let provider = new THP(terms, netip) web3.setProvider(provider) //console.log(web3.currentProvider) //3.根据合约地址和api得到合约的实例 let contractInstance = new web3.eth.Contract(JSON.parse(interface),contractAddres) //console.log("合约的实例",contractInstance) module.exports = contractInstance