Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

16.13. 實用例子

16.13.1. 數據寫入到區塊鏈中

做一筆交易,並寫入數據到區塊鏈中

			
let Web3 = require("web3");
let fs = require("fs");
let web3 = new Web3("http://localhost:8545");

let log = {
    time:(new Date).getTime(),
    type:"info",
    msg:"Web3 Test!!!"
};
let str = JSON.stringify(log);
console.log(str);
let data = Buffer.from(str).toString('hex');
data = '0x'+data;
console.log(data);

//將數據寫入到交易中
let coinbase = "0x5c18a33df2cc41a1beddc91133b8422e89f041b7"
console.log(coinbase)
let user1 = "0xc2b9e316f246d35052118e51b55c75bfe99d247e";
web3.eth.personal.unlockAccount(coinbase, "coinbase");
let address = web3.eth.sendTransaction({
    from:coinbase,
    to:user1,
    value:'0x00',
    data:data
},function(error, hash){
    console.log(hash);
});
			
			

運行上面程序,會產生一個交易,記下hash值,然後啟動挖礦。

			
> miner.start();
null
# 過一段時間後停止
> miner.stop();
true
			
			

然後查看這比交易

			
let Web3 = require("web3");
let fs = require("fs");
let web3 = new Web3("http://localhost:8545");
let address ="0xb15681eb4bdb6b9670d305fb341ebbc95d45c2ede0ea5034ef432b74f30b1b4f";
//從交易地址獲取數據
web3.eth.getTransaction(address).then(console.log);

web3.eth.getTransaction(address,function(error, result){
    //console.log(result);
    inputData = result.input;
    res_str = Buffer.from(inputData.replace('0x',''),'hex').toString();
    res_json = JSON.parse(res_str);
    console.log(res_json);
});			
			
			

結果輸出

			
{ blockHash: '0x78dacc2af60900d2e4cae90b71e27446e6e883df36c53f21cbc9e071f7a586f4',
  blockNumber: 1258,
  from: '0x5c18a33DF2cc41a1bedDC91133b8422e89f041B7',
  gas: 90000,
  gasPrice: '18000000000',
  hash: '0xb15681eb4bdb6b9670d305fb341ebbc95d45c2ede0ea5034ef432b74f30b1b4f',
  input: '0x7b2274696d65223a313531383933313435323537372c2274797065223a22696e666f222c226d7367223a22576562332054657374212121227d',
  nonce: 4,
  to: '0xc2b9e316F246d35052118E51B55C75BfE99d247e',
  transactionIndex: 0,
  value: '0',
  v: '0x41',
  r: '0x7fcd86c7fd975a0e98bd0e61a99da950b0155cd6c4581fefa4defbdcd404a930',
  s: '0x16f14ce1fbfadb9d59f343f8ac235cdd73dcedec5db1025ef91206b8bb17a827' }
{ time: 1518931452577, type: 'info', msg: 'Web3 Test!!!' }
			
			

{ time: 1518931452577, type: 'info', msg: 'Web3 Test!!!' } 就是保存在區塊鏈中的數據。

16.13.2. 編譯部署智能合約

			
console.log('Setting up...');
const fs = require ('fs');
const solc = require ('solc');
const Web3 = require ('web3');
const web3 = new Web3("http://localhost:8545");
console.log('Reading Contract...');
const input = fs.readFileSync('Netkiller.sol');
console.log('Compiling Contract...');
const output = solc.compile(input.toString(), 1);
//console.log(output);
const bytecode = output.contracts[':Netkiller'].bytecode;
//console.log(bytecode);
const abi = output.contracts[':Netkiller'].interface;
//console.log(abi);
//Contract Object
//const helloWorldContract = web3.eth.contract(JSON.parse(abi));

var myContract = new web3.eth.Contract(JSON.parse(abi), '0x5c18a33df2cc41a1beddc91133b8422e89f041b7', {
    from: '0x5c18a33df2cc41a1beddc91133b8422e89f041b7', // default from address
    gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
});

console.log('unlocking Coinbase account');
const password = "chen1980";
web3.eth.personal.unlockAccount("0x5c18a33df2cc41a1beddc91133b8422e89f041b7", password,100);

console.log("Deploying the contract");
			
			

16.13.3. 部署合約

			
var Web3 = require('web3');
var net = require('net');
var web3 = new Web3(new Web3.providers.IpcProvider("~/netkiller/ethereum/geth.ipc",net));

var abi = [...];
var bin = "";

var tokenContract = new web3.eth.Contract(abi, null, {
    from: '0xFB88dE099e13c3ED21F80a7a1E49f8CAEcF10df6' // 目前web3沒有api來解鎖賬戶,只能自己事先解鎖
});

tokenContract.deploy({
    data: bin,
    arguments: ['netkiller'] // 這裡是建構子傳值,如果建構子沒有參數,請刪除這行。
}).send({
    from: '0xFB88dE099e13c3ED21F80a7a1E49f8CAEcF10df6',
    gas: 1500000,
    gasPrice: '30000000000000'
}, function(error, transactionHash){
    console.log("deploy tx hash:"+transactionHash)
})
.on('error', function(error){ console.error(error) })
.on('transactionHash', function(transactionHash){ console.log("hash:",transactionHash)})
.on('receipt', function(receipt){
   console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation', function(confirmationNumber, receipt){console.log("receipt,",receipt)})
.then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
});			
			
			

16.13.4. ERC20 Example

通過Web3操作代幣轉賬

			
fs = require('fs');
const Web3 = require('web3');
const web3 = new Web3('http://localhost:8545');
web3.version
const abi = fs.readFileSync('output/TokenERC20.abi', 'utf-8');

const contractAddress = "0x05A97632C197a0496bc939C4e666c2E03Cb95DD4";
const toAddress = "0x2C687bfF93677D69bd20808a36E4BC2999B4767C";

var coinbase;

web3.eth.getCoinbase().then(function (address){
  coinbase = address;
  console.log(address);
});

const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { from: coinbase , gas: 100000});

contract.methods.balanceOf('0x5c18a33DF2cc41a1bedDC91133b8422e89f041B7').call().then(console.log).catch(console.error);
contract.methods.balanceOf('0x2C687bfF93677D69bd20808a36E4BC2999B4767C').call().then(console.log).catch(console.error);

web3.eth.personal.unlockAccount(coinbase, "netkiller").then(console.log);
contract.methods.transfer('0x2C687bfF93677D69bd20808a36E4BC2999B4767C', 100).send().then(console.log).catch(console.error);

contract.methods.balanceOf('0x2C687bfF93677D69bd20808a36E4BC2999B4767C').call().then(console.log).catch(console.error);