PWeb3 Javascript API
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.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"));
}
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 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();
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
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