Plian
Chinese
搜索
K

PWeb3 Javascript API

Getting Started

These docs are for PWeb3. To make your app work on Pchain, you can use the web3 object provided by the PWeb3 library. Under the hood, it communicates to a local node through RPC calls. PWeb3 works with any Pchain node which exposes an RPC layer.

Adding web3

First, you need to get web3.js into your project. This can be done using the following methods:
  • npm: npm install pweb3
  • bower: bower install pweb3
  • vanilla: link the dist./pweb3.min.js
Then you need to create a web3 instance, setting a provider. To make sure you don't overwrite the already set provider when in mist, check first if the web3 is available:
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545/pchain"));
}
After that, you can use the API of the web3 object.

Using callbacks

As this API is designed to work with a local RPC node, all its functions use synchronous HTTP requests by default. If you want to make an asynchronous request, you can pass an optional callback as the last parameter to most functions. All callbacks are using an error first callback style:
web3.pi.getBlock(48, function(error, result){
if(!error)
console.log(JSON.stringify(result));
else
console.error(error);
})

Batch requests

Batch requests allow queuing up requests and processing them at once. Note Batch requests are not faster! In fact making many requests at once will in some cases be faster, as requests are processed asynchronously. Batch requests are mainly useful to ensure the serial processing of requests.
var batch = web3.createBatch();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback));
batch.add(web3.pi.contract(abi).at(address).balance.request(address, callback2));
batch.execute();

A note on big numbers in web3.js

You will always get a BigNumber object for number values as JavaScript is not able to handle big numbers correctly. Look at the following examples:
"101010100324325345346456456456456456456"
// "101010100324325345346456456456456456456"
101010100324325345346456456456456456456
// 1.0101010032432535e+38
web3.js depends on the BigNumber Library and adds it automatically.
var balance = new BigNumber('131242344353464564564574574567456');
// or var balance = web3.pi.getBalance(someAddress);
balance.plus(21).toString(10); // toString(10) converts it to a number string
// "131242344353464564564574574567477"
The next example wouldn't work as we have more than 20 floating points, therefore it is recommended to always keep your balance in wei and only transform it to other units when presenting to the user:
var balance = new BigNumber('13124.234435346456466666457455567456');
balance.plus(21).toString(10); // toString(10) converts it to a number string, but can only show upto 20 digits
// "13145.23443534645646666646" // your number will be truncated after the 20th digit

PWeb3 API Reference

web3

version

net

pi

db

shh

chain

tdm

del

Library

web3

The web3 object provides all methods.
Example
var Web3 = require('web3');
// create an instance of web3 using the HTTP provider.
// NOTE in mist web3 is already available, so check first if it's available before instantiating
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
Example using HTTP Basic Authentication
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545", 0, BasicAuthUsername, BasicAuthPassword));
//Note: HttpProvider takes 4 arguments (host, timeout, user, password)

web3.version.api

web3.version.api
Returns
String - The pchain js api version.
Example
var version = web3.version.api;
console.log(version); // "0.2.0"

web3.version.node

web3.version.node
// or async
web3.version.getNode(callback(error, result){ ... })
Returns
String - The client/node version.
Example
var version = web3.version.node;
console.log(version); // "Mist/v0.9.3/darwin/go1.4.1"

web3.version.network

web3.version.network
// or async
web3.version.getNetwork(callback(error, result){ ... })
Returns
String - The network protocol version.
Example
var version = web3.version.network;
console.log(version); // 54

web3.version.pchain

web3.version.pchain
// or async
web3.version.pchain(callback(error, result){ ... })
Returns
String - The pchain protocol version.
Example
var version = web3.version.pchain;
console.log(version); // 60

web3.version.whisper

web3.version.whisper
// or async
web3.version.getWhisper(callback(error, result){ ... })
Returns
String - The whisper protocol version.
Example
var version = web3.version.whisper;
console.log(version); // 20

web3.isConnected

web3.isConnected()
Should be called to check if a connection to a node exists
Parameters
none
Returns
Boolean
Example
if(!web3.isConnected()) {
// show some dialog to ask the user to start a node
} else {
// start web3 filters, calls, etc
}

web3.setProvider

web3.setProvider(provider)
Should be called to set provider.
Parameters
none
Returns
undefined
Example
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545')); // 8080 for cpp/AZ, 8545 for go/mist

web3.currentProvider

web3.currentProvider
Will contain the current provider, if one is set. This can be used to check if mist etc. has set already a provider.
Returns
Object - The provider set or null;
Example
// Check if mist etc. already set a provider
if(!web3.currentProvider)
web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));

web3.reset

web3.reset(keepIsSyncing)
Should be called to reset state of web3. Resets everything except manager. Uninstalls all filters. Stops polling.
Parameters
  1. 1.
    Boolean - If true it will uninstall all filters, but will keep the web3.pi.isSyncing() polls
Returns
undefined
Example
web3.reset();

web3.sha3

web3.sha3(string [, options])
Parameters
  1. 1.
    String - The string to hash using the Keccak-256 SHA3 algorithm
  2. 2.
    Object - (optional) Set encoding to hex if the string to hash is encoded in hex. A leading 0x will be automatically ignored.
Returns
String - The Keccak-256 SHA3 of the given data.
Example
var hash = web3.sha3("Some string to be hashed");
console.log(hash); // "0xed973b234cf2238052c9ac87072c71bcf33abc1bbd721018e0cca448ef79b379"
var hashOfHash = web3.sha3(hash, {encoding: 'hex'});
console.log(hashOfHash); // "0x85dd39c91a64167ba20732b228251e67caed1462d4bcf036af88dc6856d0fdcc"

web3.getVoteHash

web3.getVoteHash(from, pubKey,amount,salt)
Parameters
  1. 1.
    from: address, 20 Bytes - the address who triggers the action
  2. 2.
    pubkey: hex string, 128 Bytes - the BLS Public Key who triggers the action,How To Get Your Pubkey
  3. 3.
    amount: hex string - the amount of vote
  4. 4.
    salt: string - salt string
Returns
String - The Keccak-256 SHA3 of the given data.
Example
var from = "4CACBCBF218679DCC9574A90A2061BCA4A8D8B6C";
var pubkey = "7315DF293B07C52EF6C1FC05018A1CA4FB630F6DBD4F1216804FEDDC2F04CD2932A5AB72B6910145ED97A5FFA0CDCB818F928A8921FDAE8033BF4259AC3400552065951D2440C25A6994367E1DC60EE34B34CB85CD95304B24F9A07473163F1F24C79AC5CBEC240B5EAA80907F6B3EDD44FD8341BF6EB8179334105FEDE6E790";
var amount = "0x1f4";
var salt = "ABCD";
var hash = web3.getVoteHash(from,pubkey,amount,salt);
// "0x78701448b4ee6fc4edc940266bcebc3e21b1b3c208957cb081cfba5a629beb72"

web3.toHex

web3.toHex(mixed);
Converts any value into HEX.
Parameters
  1. 1.
    String|Number|Object|Array|BigNumber - The value to parse to HEX. If its an object or array it will be JSON.stringify first. If its a BigNumber it will make it the HEX value of a number.
Returns
String - The hex string of mixed.
Example
var str = web3.toHex({test: 'test'});
console.log(str); // '0x7b2274657374223a2274657374227d'

web3.toAscii

web3.toAscii(hexString);
Converts a HEX string into a ASCII string.
Parameters
  1. 1.
    String - A HEX string to be converted to ascii.
Returns
String - An ASCII string made from the given hexString.
Example
var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "pchain"

web3.fromAscii

web3.fromAscii(string);
Converts any ASCII string to a HEX string.
Parameters
  1. 1.
    String - An ASCII string to be converted to HEX.
Returns
String - The converted HEX string.
Example
var str = web3.fromAscii('pchain');
console.log(str); // "0x657468657265756d"

web3.toDecimal

web3.toDecimal(hexString);
Converts a HEX string to its number representation.
Parameters
  1. 1.
    String - A HEX string to be converted to a number.
Returns
Number - The number representing the data hexString.
Example
var number = web3.toDecimal('0x15');
console.log(number); // 21

web3.fromDecimal

web3.fromDecimal(number);
Converts a number or number string to its HEX representation.
Parameters
  1. 1.
    Number|String - A number to be converted to a HEX string.
Returns
String - The HEX string representing of the given number.
Example
var value = web3.fromDecimal('21');
console.log(value); // "0x15"

web3.fromWei

web3.fromWei(number, unit)
Converts a number of wei into the following pchain units:
  • Gwei
  • Kwei
  • Mwei/babbage/pi/femtoether
  • pi
  • finney/gpi/grand/gwei
  • kpi/kwei/lovelace/mether/micro
  • microether/milli/milliether
  • mwei/nano/nanoether
  • noether
  • picoether/shannon
  • szabo
  • tpi
  • wei
Parameters
  1. 1.
    Number|String|BigNumber - A number or BigNumber instance.
  2. 2.
    String - One of the above pi units.
Returns
String|BigNumber - Either a number string, or a BigNumber instance, depending on the given number parameter.
Example
var value = web3.fromWei('21000000000000', 'finney');
console.log(value); // "0.021"

web3.toWei

web3.toWei(number, unit)
Converts an pchain unit into wei. Possible units are:
  • kwei/ada
  • mwei/babbage
  • gwei/shannon
  • szabo
  • finney
  • pi
  • kpi/grand/einstein
  • mpi
  • gpi
  • tpi
Parameters
  1. 1.
    Number|String|BigNumber - A number or BigNumber instance.
  2. 2.
    String - One of the above pi units.
Returns
String|BigNumber - Either a number string, or a BigNumber instance, depending on the given number parameter.
Example
var value = web3.toWei('1', 'pi');
console.log(value); // "1000000000000000000"

web3.toBigNumber

web3.toBigNumber(numberOrHexString);
Converts a given number into a BigNumber instance. See the note on BigNumber.
Parameters
  1. 1.
    Number|String - A number, number string or HEX string of a number.
Returns
BigNumber - A BigNumber instance representing the given value.
Example
var value = web3.toBigNumber('200000000000000000000001');
console.log(value); // instanceOf BigNumber
console.log(value.toNumber()); // 2.0000000000000002e+23
console.log(value.toString(10)); // '200000000000000000000001'

web3.isAddress

web3.isAddress(HexString);
Checks if the given string is an address.
Parameters
  1. 1.
    String - A HEX string.
Returns
Boolean - false if it's not on a valid address format. Returns true if it's an all lowercase or all uppercase valid address. If it's a mixed case address, it checks using web3.isChecksumAddress().
Example
var isAddress = web3.isAddress("0x8888f1f195afa192cfee860698584c030f4c9db1");
console.log(isAddress); // true

web3.net.listening

web3.net.listening
// or async
web3.net.getListening(callback(error, result){ ... })
This property is read only and says whether the node is actively listening for network connections or not.
Returns
Boolean - true if the client is actively listening for network connections, otherwise false.
Example
var listening = web3.net.listening;
console.log(listening); // true of false

web3.net.peerCount

web3.net.peerCount
// or async
web3.net.getPeerCount(callback(error, result){ ... })
This property is read only and returns the number of connected peers.
Returns
Number - The number of peers currently connected to the client.
Example
var peerCount = web3.net.peerCount;
console.log(peerCount); // 4

web3.pi

Contains the pchain blockchain related methods.
Example
var eth = web3.pi;

web3.pi.defaultAccount

web3.pi.defaultAccount
This default address is used for the following methods (optionally you can overwrite it by specifying the from property):
Values
String, 20 Bytes - Any address you own, or where you have the private key for. Default is undefined.
Returns
String, 20 Bytes - The currently set default address.
Example
var defaultAccount = web3.pi.defaultAccount;
console.log(defaultAccount); // ''
// set the default account
web3.pi.defaultAccount = '0x8888f1f195afa192cfee860698584c030f4c9db1';

web3.pi.defaultBlock

web3.pi.defaultBlock
This default block is used for the following methods (optionally you can override it by passing the defaultBlock parameter):
Values
Default block parameters can be one of the following:
  • Number - a block number
  • String - "earliest", the genesis block
  • String - "latest", the latest block (current head of the blockchain)
  • String - "pending", the currently mined block (including pending transactions) Default is latest
Returns
Number|String - The default block number to use when querying a state.
Example
var defaultBlock = web3.pi.defaultBlock;
console.log(defaultBlock); // 'latest'
// set the default block
web3.pi.defaultBlock = 231;

web3.pi.syncing

web3.pi.syncing
// or async
web3.pi.getSyncing(callback(error, result){ ... })
This property is read only and returns the either a sync object, when the node is syncing or false.
Returns
Object|Boolean - A sync object as follows, when the node is currently syncing or false:
  • startingBlock: Number - The block number where the sync started.
  • currentBlock: Number - The block number where at which block the node currently synced to already.
  • highestBlock: Number - The estimated block number to sync to.
Example
var sync = web3.pi.syncing;
console.log(sync);
/*
{
startingBlock: 300,
currentBlock: 312,
highestBlock: 512
}
*/

web3.pi.isSyncing

web3.pi.isSyncing(callback);
This convenience function calls the callback everytime a sync starts, updates and stops.
Returns
Object - a isSyncing object with the following methods:
  • syncing.addCallback(): Adds another callback, which will be called when the node starts or stops syncing.
  • syncing.stopWatching(): Stops the syncing callbacks.
Callback return value
  • Boolean - The callback will be fired with true when the syncing starts and with false when it stopped.
  • Object - While syncing it will return the syncing object:
    • startingBlock: Number - The block number where the sync started.
    • currentBlock: Number - The block number where at which block the node currently synced to already.
    • highestBlock: Number - The estimated block number to sync to.
Example
web3.pi.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.pi.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...
}
}
});

web3.pi.coinbase

web3.pi.coinbase
// or async
web3.pi.getCoinbase(callback(error, result){ ... })
This property is read only and returns the coinbase address where the mining rewards go to.
Returns
String - The coinbase address of the client.
Example
<