使用console.log(web3.version.api);來查看了web3的版本是0.20.1,html
參考文檔在:
https://github.com/ethereum/wiki/wiki/JavaScript-API
在學習的過程當中你會看見不少實例是不同的,就單單是合約的部署的地方的運行語句就十分地不一樣,這就是web3 0.2版本跟1.0版本的不一樣
以後打算使用1.0版本的了
1.首先,須要去聲明一個web3實例,,而後去設置providernode
if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); //當你以前若是使用過mist錢包等時,你的provider可能已經設置好了,web3.currentProvider就是你目前的provider } else { // set the provider you want from Web3.providers web3 = new Web3(new Web3.providers.HttpProvider(「http://localhost:8545」)); } //Note: HttpProvider takes 4 arguments (host, timeout, user, password)
或者:
if(!web3.currentProvider)//返回provider set or null
web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));
2.在節點中的函數都是默承認以使用回調函數的,舉例:
web3.eth.getBlock(48, function(error, result){
if(!error)
console.log(JSON.stringify(result));
else
console.error(error);
})
3.Batch requests(批處理請求):當你想要請求按必定的順序一次性調用時
var batch = web3.createBatch();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback));
batch.add(web3.eth.contract(abi).at(address).balance.request(address, callback2));
batch.execute();
4.web3中的的數字是基於BigNumber Library 的
調用方法:
var BigNumber = require('bignumber.js');
var balance = new BigNumber(‘131242344353464564564574574567456’);
//這樣輸出爲:
BigNumber { s: 1, e: 32, c: [ 13124, 23443534645645, 64574574567456 ] }
console.log(balance.toString(10));//10進制
//這樣輸出爲:131242344353464564564574574567456
balance.plus(21).toString(10); // toString(10) converts it to a number string
// 「131242344353464564564574574567477"
a = new BigNumber(1011, 2) // 「11" 二進制
b = new BigNumber('zz.9', 36) // 「1295.25" 36進制
以後從web3的API參考手冊開始看起:
1.web3.version.api
使用console.log(web3.version.api);
//來查看了web3的版本是0.20.1
2.web3.version.node
(1)console.log(web3.version.node);
(2)
web3.version.getNode(function(error,result){
if(!error){
console.log(result);
}else{
console.log(error);
}
});
//結果都是:Geth/v1.8.3-stable/darwin-amd64/go1.10.1
3.web3.version.network
(1)console.log(web3.version.network);
(2)web3.version.getNetwork(function(error,result){
if(!error){
console.log(result);
}else{
console.log(error);
}
});
//獲得的結果是geth是設置的networkID 314590 (--networkid 314590)
4.web3.version.ethereum查看以太坊協議的版本
(1)console.log(web3.version.ethereum);
(2)web3.version.getEthereum(function(error,result){
if(!error){
console.log(result);
}else{
console.log(error);
}
});
//結果是0x3f(63)
5.web3.version.whisper
whisper實際上就是以太坊p2p網絡上的一個應用,因此若是你之後要設計一個聊天室的話,就要使用這個協議了,要感覺whisper能夠經過啓動wnode來感覺
能夠構建一個完整的p2p聊天室,而且消息加密,沒法被追蹤;而且不須要服務器,永不停機。基於以太坊的whisper,它原本是爲以太坊上的DAPPS通訊構建的,有點複雜,之後再學
http://www.cnblogs.com/baizx/p/7505096.html
https://www.cnblogs.com/baizx/p/7898692.html
(1)console.log(web3.version.whisper);
(2)web3.version.getWhisper(function(error,result){
if(!error){
console.log(result);
}else{
console.log(error);
}
});
//結果是:Error: The method shh_version does not exist/is not available
6.console.log(web3.isConnected());//true
是否連接了節點
7.web3.setProvider(provider)
var web3 = new Web3();
web3.setProvider(new Web3.providers.HttpProvider(「http://localhost:8201"));//使用local3私有鏈
8.web3.sha3(string [, options])
var hash = web3.sha3("Some string to be hashed");
console.log(hash); // "0xed973b234cf2238052c9ac87072c71bcf33abc1bbd721018e0cca448ef79b379"
//使用使用keccak-256哈希算法計算字符串的hash值
var hashOfHash = web3.sha3(hash, {encoding: 'hex'});
console.log(hashOfHash); // 「0x85dd39c91a64167ba20732b228251e67caed1462d4bcf036af88dc6856d0fdcc"
//當string處的值hash是十六進制時(if the string to hash is encoded in hex),就設置{encoding: ‘hex'}
9.web3.toHex(mixed);
var str = web3.toHex({test: 'test'});
console.log(str); // ‘0x7b2274657374223a2274657374227d'
10.web3.toAscii(hexString);
Converts a HEX string into a ASCII string.
var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // 「ethereum"
11.web3.fromAscii(string [, padding]);
Converts any ASCII string to a HEX string.
var str = web3.fromAscii('ethereum');
console.log(str); // "0x657468657265756d"
var str2 = web3.fromAscii('ethereum', 32);//32bytes
console.log(str2); // 「0x657468657265756d000000000000000000000000000000000000000000000000"
//16進制的1位就是1bytes
12.web3.toDecimal(hexString)//把16進制的字符串轉爲10進制
13.web3.fromDecimal(number|String);//反過來
14.web3.fromWei(number|String|BigNumber, unit(String))
var value = web3.fromWei('21000000000000', 'finney');
console.log(value); // 「0.021"
21000000000000wei->0.021finney
15.web3.toWei(number, unit)
var value = web3.toWei('1', 'ether');
console.log(value); // 「1000000000000000000"
//1ether->1000000000000000000wei
16.web3.toBigNumber(numberOrHexString);
17.web3.isAddress(HexString);
18.web3.eth.defaultBlock//默認是最晚生成的那一個latest,或
web3.eth.defaultBlock(blockNumber)
web3.eth.defaultBlock(「earliest")//the genesis block
web3.eth.defaultBlock(「pending」)the currently mined block (including pending transactions)
19.
(1)web3.eth.syncing查詢同步的信息
(2)web3.eth.getSyncing(callback(error, result){ ... })
是否正在同步區塊,是就返回同步的對象信息:
{
startingBlock:Number - 同步開始區塊號
currentBlock: Number - 節點當前正在同步的區塊號
highestBlock: Number - 預估要同步到的區塊
}
不然返回false
20.web3.eth.isSyncing 檢查是否與網絡同步
同步有三種狀態,true(剛開始)、正在進行時和已經結束false
web3.eth.isSyncing(function(error, sync){
if(!error) {
// stop all app activity
if(sync === true) {
// we use `true`, so it stops all filters, but not the web3.eth.syncing polling
web3.reset(true);
// show sync info
} else if(sync) {
console.log(sync.currentBlock);
// re-gain app operation
} else {
// run your app init function...
}
}
});
21.web3.reset
用來重置web3的狀態。重置除了manager之外的其它全部東西。卸載filter,中止狀態輪詢。
參數:
Boolean - 若是設置爲true,將會卸載全部的filter,但會保留web3.eth.isSyncing()的狀態輪詢。
22.web3.eth.hashrate查詢每秒節點挖礦的哈希難度
23.web3.eth.gasPrice
返回當前的gas價格。這個值由最近幾個塊的gas價格的中值決定。
返回的是BigNumber,用toString(10)轉成10進制
24.web3.eth.blockNumber目前區塊數量
25.web3.eth.getStorageAt????
26.web3.eth.getBlockTransactionCount(hashStringOrBlockNumber |Number [, callback])獲得某區塊中的交易數量
輸入區塊的number、hash值或string("earliest", "latest" or 「pending」)
27.web3.eth.getTransactionReceipt(transactionHash)
pending的transaction是調用不出來值的,能夠查看出更多的信息,能夠看出交易是否成功
"status": 「0x1"爲成功;"status": 「0x0"爲不成功
若某個transactionHash是生成某個智能合約的,那麼用這個函數就能夠在contractAddress值處查看到合約的地址
28.web3.eth.sendTransaction(transactionObject [, callback])
transactionObject就是各類值{from:..,to:..,}
• from: String - 指定的發送者的地址。若是不指定,使用web3.eth.defaultAccount。
• to: String - (可選)交易消息的目標地址,若是是合約建立,則不填.
• value: Number|String|BigNumber - (可選)交易攜帶的貨幣量,以wei爲單位。若是合約建立交易,則爲初始的基金。
• gas: Number|String|BigNumber - (可選)默認是自動,交易可以使用的gas,未使用的gas會退回。
• gasPrice: Number|String|BigNumber - (可選)默認是自動肯定,交易的gas價格,默認是網絡gas價格的平均值 。
• data: String - (可選)或者包含相關數據的字節字符串,若是是合約建立,則是初始化要用到的代碼。
• nonce: Number - (可選)整數,使用此值,能夠容許你覆蓋你本身的相同nonce的,正在pending中的交易11。
29.web3.eth.sendRawTransaction(signedTransactionData [, callback])發送一個已經簽名的交易
signedTransactionData:16進制的簽名的交易數據
這就是一個簽名的步驟:
var Tx = require('ethereumjs-tx');
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')
var rawTx = {
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();//序列化???
//console.log(serializedTx.toString('hex'));
//f889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
console.log(hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385"
});
30.web3.eth.sign(address, dataToSign, [, callback])
使用指定帳戶address對要發送的數據dataToSign進行簽名,因此該帳戶是要解鎖的,dataToSign可使用進行哈希web3.sha3(「xyz")後的值
而後會返回使用ECDSA(橢圓曲線數字簽名算法)簽名後獲得的字符串,表示爲:
r = signature[0:64]
s = signature[64:128]
v = signature[128:130]
就是在eth.getTransaction看到的那幾個值
31.web3.eth.filter
輸入的值即爲輸入的過濾條件,對全部的日誌信息進行過濾來得到本身想要知道的信息
(1)// filterString can be 'latest' or 'pending'
var filter = web3.eth.filter(filterString);
(2)var filter = web3.eth.filter(options);
• fromBlock: Number|string - 起始區塊號(若是使用字符串latest,意思是最新的,正在打包的區塊),默認值是latest。
• toBlock: Number|string - 終止區塊號(若是使用字符串latest,意思是最新的,正在打包的區塊),默認值是latest。
• address: String - 單個或多個地址。獲取指定賬戶的日誌。
• topics: String[] - 在日誌對象中必須出現的字符串數組。順序很是重要,若是你想忽略主題,使用null。如,[null,'0x00...'],你還能夠爲每一個主題傳遞一個單獨的可選項數組,如[null,['option1','option1']]。
而後上面的過濾怎麼得到信息:
(1)filter.get(callback): 返回知足過濾條件的日誌。
(2)filter.watch(callback): 監聽知足條件的狀態變化,知足條件時調用回調7。
watch監聽回調返回值:
《1》String - 當使用latest參數時。返回最新的一個區塊哈希值。
《2》String - 當使用pending參數時。返回最新的pending中的交易哈希值。
《3》Object - 當使用手工過濾選項options時,將返回下述的日誌對象。
◦ logIndex: Number - 日誌在區塊中的序號。若是是pending的日誌,則爲null。
◦ transactionIndex: Number - 產生日誌的交易在區塊中的序號。若是是pending的日誌,則爲null。
◦ transactionHash: String,32字節 - 產生日誌的交易哈希值。
◦ blockHash: String,32字節 - 日誌所在塊的哈希。若是是pending的日誌,則爲null。
◦ blockNumber: Number - 日誌所在塊的塊號。若是是pending的日誌,則爲null。
◦ address: String,32字節 - 日誌產生的合約地址。
◦ data: string - 包含日誌一個或多個32字節的非索引的參數。
◦ topics: String[] - 一到四個32字節的索引的日誌參數數組。(在Solidity中,第一個主題是整個事件的簽名(如,Deposit(address,bytes32,uint256)),但若是使用匿名的方式定義事件的狀況除外)
filter.stopWatching(): 中止監聽,清除節點中的過濾。你應該老是在監聽完成後,執行這個操做。
與其有相同的功能的就是合約中的事件event了
當一個合同中有設置event時,若是想要查看event。舉例:
獲得的是符合條件a == 5的事件myEvent的值
// create filter
var event = myContractInstance.myEvent({a: 5}, function (error, result) {
if (!error)
console.log(result);
/*
{
address: '0x8718986382264244252fc4abd0339eb8d5708727',
topics: "0x12345678901234567890123456789012", "0x0000000000000000000000000000000000000000000000000000000000000005",
data: "0x0000000000000000000000000000000000000000000000000000000000000001",
...
}
*/
});
或者不回調,使用監聽watch或get:
var event = myContractInstance.myEvent({a: 5});
event.watch(function(error, result){
if (!error)
console.log(result);
});
event.stopWatching();
條件還能夠寫成:
var myEvent = myContractInstance.MyEvent({some: 'args'}, {fromBlock: 0, toBlock: 'latest'});
還有監聽全部事件的:
var events = myContractInstance.allEvents(條件,回調);
32.如何用語句去配置合約,之前都是說將sol代碼導入到remix-ide中去,而後再在它上面進行編譯compile-部署deploy,可是如今要學會怎麼使用代碼去將這些步驟完成了
git
// Deploy the contract asynchronous(異步) from Solidity file: const fs = require("fs"); const solc = require('solc') let source = fs.readFileSync('nameContract.sol', ‘utf8’); // Setting 1 as second paramater activates the optimiser(最優) let compiledContract = solc.compile(source, 1);//編譯 let abi = compiledContract.contracts[‘nameContract’].interface; //bytecode就是以前在remix-compile-details-web3deploy中的那串很長的數字 let bytecode = compiledContract.contracts[‘nameContract'].bytecode; //原來這個是這麼算的 let gasEstimate = web3.eth.estimateGas({data: bytecode}); let MyContract = web3.eth.contract(JSON.parse(abi)); //若構造函數沒有變量,那麼這裏的param1, param2是能夠去掉的 var myContractReturned = MyContract.new(param1, param2, { from:mySenderAddress,//通常就是eth.accounts[0] data:bytecode, gas:gasEstimate}, function(err, myContract){//這個回調回執行兩次 if(!err) { // NOTE: The callback will fire twice! // Once the contract has the transactionHash property set and once its deployed on an address. //一次是合約的交易哈希屬性完成 //另外一次是在某個地址上完成部署 // e.g. check tx hash on the first call (transaction send) if(!myContract.address) {//第一次 console.log(myContract.transactionHash) // The hash of the transaction, which deploys the contract // check address on the second call (contract deployed) } else {//第二次 console.log(myContract.address) // the contract address } // Note that the returned "myContractReturned" === "myContract", // so the returned "myContractReturned" object will also get the address set. } });
//這個是一個比較特別的input,能夠一會兒編譯兩個sol文件,並且還進行調用github
var solc = require('solc') var input = { 'lib.sol': 'library L { function f() returns (uint) { return 7; } }', 'cont.sol': 'import "lib.sol"; contract x { function g() { L.f(); } }' } var output = solc.compile({ sources: input }, 1) for (var contractName in output.contracts) console.log(contractName + ': ' + output.contracts[contractName].bytecode)
33.返回可用的編譯器
var number = web3.eth.getCompilers();
console.log(number); // ["lll", "solidity", 「serpent"]三種編譯器
34.web3.eth.compile.solidity(sol代碼)
編譯sol文件
web3數據庫部分
35.web3.db.putString(db, key, value)想存儲string到本地數據庫上的時候使用
Parameters
1 String - The database to store to.
2 String - The name of the store.就是至關於索引值的感受,經過key來找到value
3 String - The string value to store.
Returns
Boolean - true if successfull, otherwise false.
36.web3.db.getString(db, key)取出
37.web3.db.putHex(db, key, value)想存儲16進制時
38.web3.db.getHex(db, key)取出
shh部分——whisper
(這部分我仍是不是很明白,以後用獲得再看吧)
iban部分,也不知道這個是什麼
web