web3js learning

使用console.log(web3.version.api);来查看了web3的版本是0.20.1html

参考文档在:
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