Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
pweb3.js - Pchain JavaScript API¶
pweb3.js is a collection of libraries which allow you to interact with a local or remote Pchain node, using an HTTP, WebSocket or IPC connection.
The following documentation will guide you through installing and running pweb3.js, as well as providing a API reference documentation with examples.
Contents:
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Getting Started¶
The pweb3.js library is a collection of modules which contain specific functionality for the Pchain ecosystem.
- The
web3-pi
is for the Pchain blockchain and smart contracts - The
web3-shh
is for the whisper protocol to communicate p2p and broadcast - The
web3-utils
contains useful helper functions for DApp developers.
Adding pweb3.js¶
First you need to get pweb3.js into your project. This can be done using the following methods:
- npm:
npm install pweb3
After that you need to create a web3 instance and set a provider.
A Pchain compatible browser will have a window.Pchain
or web3.currentProvider
available.
For pweb3.js, check Web3.givenProvider
. If this property is null
you should connect to your own local or remote node.
// in node.js use: const Web3 = require('pweb3');
// use the given Provider, e.g in the browser with PMetamask, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain', null, {});
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'), null, {});
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net, {}); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net, {})); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
That’s it! now you can use the web3
object.
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Callbacks Promises Events¶
To help web3 integrate into all kind of projects with different standards we provide multiple ways to act on asynchronous functions.
Most pweb3.js objects allow a callback as the last parameter, as well as returning promises to chain functions.
Pchain as a blockchain has different levels of finality and therefore needs to return multiple “stages” of an action. To cope with requirement we return a “PromiEvent” for functions like web3.pi.sendTransaction or contract methods. These stages are encapsulated into a “PromiEvent”, which combines a promise with an event emitter. The event emitter fires an event for each of the finality stages.
An example of a function that benefits from a PromiEvent is the web3.pi.sendTransaction method.
web3.pi.sendTransaction({from: '0x123...', data: '0x432...'})
.once('transactionHash', function(hash){ ... })
.once('receipt', function(receipt){ ... })
.on('confirmation', function(confNumber, receipt){ ... })
.on('error', function(error){ ... })
.then(function(receipt){
// will be fired once the receipt is mined
});
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Glossary¶
Specification¶
Functions:
type
:"function"
,"constructor"
(can be omitted, defaulting to"function"
;"fallback"
also possible but not relevant in pweb3.js);name
: the name of the function (only present for function types);constant
:true
if function is specified to not modify the blockchain state;payable
:true
if function accepts ether, defaults tofalse
;stateMutability
: a string with one of the following values:pure
(specified to not read blockchain state),view
(same asconstant
above),nonpayable
andpayable
(same aspayable
above);inputs
: an array of objects, each of which contains:name
: the name of the parameter;type
: the canonical type of the parameter.
outputs
: an array of objects same asinputs
, can be omitted if no outputs exist.
Events:
type
: always"event"
name
: the name of the event;inputs
: an array of objects, each of which contains:name
: the name of the parameter;type
: the canonical type of the parameter.indexed
:true
if the field is part of the log’s topics,false
if it one of the log’s data segment.
anonymous
:true
if the event was declared asanonymous
.
Example¶
contract Test {
uint a;
address d = 0x12345678901234567890123456789012;
function Test(uint testInt) { a = testInt;}
event Event(uint indexed b, bytes32 c);
event Event2(uint indexed b, bytes32 c);
function foo(uint b, bytes32 c) returns(address) {
Event(b, c);
return d;
}
}
// would result in the JSON:
[{
"type":"constructor",
"payable":false,
"stateMutability":"nonpayable"
"inputs":[{"name":"testInt","type":"uint256"}],
},{
"type":"function",
"name":"foo",
"constant":false,
"payable":false,
"stateMutability":"nonpayable",
"inputs":[{"name":"b","type":"uint256"}, {"name":"c","type":"bytes32"}],
"outputs":[{"name":"","type":"address"}]
},{
"type":"event",
"name":"Event",
"inputs":[{"indexed":true,"name":"b","type":"uint256"}, {"indexed":false,"name":"c","type":"bytes32"}],
"anonymous":false
},{
"type":"event",
"name":"Event2",
"inputs":[{"indexed":true,"name":"b","type":"uint256"},{"indexed":false,"name":"c","type":"bytes32"}],
"anonymous":false
}]
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Web3¶
The Web3 class is a wrapper to house all Pchain related modules.
Initiating of Web3¶
Parameters¶
provider
-string|object
: A URL or one of the Web3 provider classes.net
-net.Socket
(optional): The net NodeJS package.options
-object
(optional) The Web3 options
Example¶
import Web3 from 'pweb3';
// "Web3.givenProvider" will be set in a Pchain supported browser.
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', net, options);
> web3.pi
> web3.shh
> web3.utils
> web3.version
Web3.modules¶
This Static property will return an object with the classes of all major sub modules, to be able to instantiate them manually.
Returns¶
Object
: A list of modules:Pi
-Function
: the Pi module for interacting with the Pchain network see web3.pi for more.Net
-Function
: the Net module for interacting with network properties see web3.pi.net for more.Personal
-Function
: the Personal module for interacting with the Pchain accounts see web3.pi.personal for more.Shh
-Function
: the Shh module for interacting with the whisper protocol see web3.shh for more.
Example¶
Web3.modules
> {
Pi(provider, net?, options?),
Net(provider, net?, options?),
Personal(provider, net?, options?),
Shh(provider, net?, options?),
}
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
getVoteHash¶
Property of the Web3 class.
web3.getVoteHash
Parameters¶
from
- address, 20 Bytes - the address who triggers the actionpubkey
- hex string, 128 Bytes - the BLS Public Key who triggers the action,How To Get Your Pubkeyamount
- hex string - the amount of votesalt
- 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);
console.log(hash);
> "16d75d8c6bfb24de05c994db6756ba3cbafd0150cbc19737f49d3f3a073b43c2910ee9be73258427688ab864e2ab28a987b696b1975060d7e1557c64e3a2b0a89a"
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi¶
The web3-pi
package allows you to interact with an Pchain blockchain itself and the deployed smart contracts.
import Web3 from 'pweb3';
import {Pi} from 'pweb3-pi';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const pi = new Pi(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// or using the web3 umbrella package
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// -> web3.pi
Note on checksum addresses¶
All Pchain addresses returned by functions of this package are returned as checksum addresses. This means some letters are uppercase and some are lowercase. Based on that it will calculate a checksum for the address and prove its correctness. Incorrect checksum addresses will throw an error when passed into functions. If you want to circumvent the checksum check you can make an address all lower- or uppercase.
Example¶
web3.pi.getAccounts(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe" ,"0x85F43D8a49eeB85d32Cf465507DD71d507100C1d"]
subscribe¶
For web3.pi.subscribe
see the Subscribe reference documentation
Contract¶
For web3.pi.Contract
see the Contract reference documentation
Iban¶
For web3.pi.Iban
see the Iban reference documentation
personal¶
For web3.pi.personal
see the personal reference documentation
accounts¶
For web3.pi.accounts
see the accounts reference documentation
ens¶
For web3.pi.ens
see the Ens reference documentation
abi¶
For web3.pi.abi
see the ABI reference documentation
net¶
For web3.pi.net
see the net reference documentation
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
getProtocolVersion¶
web3.pi.getProtocolVersion([callback])
Returns the Pchain protocol version of the node.
Returns¶
Promise<string>
- The protocol version.
Example¶
web3.pi.getProtocolVersion().then(console.log);
> "63"
isSyncing¶
web3.pi.isSyncing([callback])
Checks if the node is currently syncing and returns either a syncing object, or false
.
Returns¶
Promise<object|boolean>
- A sync object 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.knownStates
-Number
: The estimated states to downloadpulledStates
-Number
: The already downloaded states
Example¶
web3.pi.isSyncing()
.then(console.log);
> {
startingBlock: 100,
currentBlock: 312,
highestBlock: 512,
knownStates: 234566,
pulledStates: 123455
}
getCoinbase¶
web3.pi.getCoinbase([callback])
Returns the coinbase address to which mining rewards will go.
Returns¶
Promise<string>
- The coinbase address set in the node for mining rewards.
Example¶
web3.pi.getCoinbase().then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"
isMining¶
web3.pi.isMining([callback])
Checks whether the node is mining or not.
Returns¶
Promise<boolean>
- Returns true
if the node is mining, otherwise false
.
Example¶
web3.pi.isMining().then(console.log);
> true
getHashrate¶
web3.pi.getHashrate([callback])
Returns the number of hashes per second that the node is mining with.
Returns¶
Promise<number>
- The Number of hashes per second.
getGasPrice¶
web3.pi.getGasPrice([callback])
Returns the current gas price oracle. The gas price is determined by the last few blocks median gas price. GasPrice is the wei per unit of gas,.
Returns¶
Promise<string>
- Number string of the current gas price in wei.
getAccounts¶
web3.pi.getAccounts([callback])
Will return a list of the unlocked accounts in the Web3 wallet or it will return the accounts from the currently connected node.
This means you can add accounts with web3.pi.accounts.create() and you will get them returned here.
Returns¶
Promise<Array>
- An array of addresses controlled by node.
Example¶
web3.pi.getAccounts().then(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"]
getBlockNumber¶
web3.pi.getBlockNumber([callback])
Returns the current block number.
Returns¶
Promise<number>
- The number of the most recent block.
getBalance¶
web3.pi.getBalance(address [, defaultBlock] [, callback])
Get the balance of an address at a given block.
Parameters¶
String
- The address to get the balance of.Number|String
- (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The current balance for the given address in wei.
See the A note on dealing with big numbers in JavaScript.
Example¶
web3.pi.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);
> "1000000000000"
getFullBalance¶
web3.pi.getFullBalance(from,blockNumber,fullProxied [, callback])
Get the balance of an address at a given block.
Parameters¶
String
- The address to get the balance of.Number|String
- QUANTITY|TAG - integer block number, or the string “latest”, “earliest” or “pending”.fullProxied
- Boolean - If true it returns the full detail proxied object under this address.
Returns¶
balance
- QUANTITY - integer of the current balance in p-wei.delegateBalance
- QUANTITY - total delegate balance in p-wei to other address.depositBalance
- QUANTITY - deposit balance in p-wei for Validator Stake.depositProxiedBalance
- QUANTITY - total deposit proxied balance in p-wei for Validator Stake.pendingRefundBalance
- QUANTITY - total pending refund balance in p-wei which will be return to delegate at the end of Current Epoch.proxiedBalance
- QUANTITY - total proxied balance in p-wei delegate from other address.proxied_detail
- Object - detail record of each address’s proxied data, including proxied balance, deposit proxied balance and pending refund balance.
Example¶
var fullBalance = web3.pi.getFullBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1","latest",true);
console.log(fullBalance);
> {
"balance": "0x1000eadf9",
"delegateBalance": "0x152d02c7e14af6800000",
"depositBalance": "0x0",
"depositProxiedBalance": "0x0",
"pendingRefundBalance": "0x0",
"proxiedBalance": "0x152d02c7e14af680b000",
"proxied_detail": {
"0x1529fa43d9f7fe958662f7200739cdc3ec2666c7": {
"ProxiedBalance": "0xb000",
"DepositProxiedBalance": "0x0",
"PendingRefundBalance": "0x0"
},
"0xd833b6738285f4a50cf42cf1a40c4000256589d4": {
"ProxiedBalance": "0x152d02c7e14af6800000",
"DepositProxiedBalance": "0x0",
"PendingRefundBalance": "0x0"
}
}
}
getStorageAt¶
web3.pi.getStorageAt(address, position [, defaultBlock] [, callback])
Get the storage at a specific position of an address.
Parameters¶
String
- The address to get the storage from.Number
- The index position of the storage.Number|String
- (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The value in storage at the given position.
Example¶
web3.pi.getStorageAt("0x407d73d8a49eeb85d32cf465507dd71d507100c1", 0).then(console.log);
> "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"
getCode¶
web3.pi.getCode(address [, defaultBlock] [, callback])
Get the code at a specific address.
Parameters¶
String
- The address to get the code from.Number|String
- (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The data at given address address
.
Example¶
web3.pi.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8").then(console.log);
> "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056"
getBlock¶
web3.pi.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])
Returns a block matching the block number or block hash.
Parameters¶
String|Number
- The block number or block hash. Or the string"genesis"
,"latest"
or"pending"
as in the default block parameter.Boolean
- (optional, defaultfalse
) Iftrue
, the returned block will contain all transactions as objects, iffalse
it will only contains the transaction hashes.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object>
- The block object:
number
-Number
: The block number.null
when its pending block.hash
32 Bytes -String
: Hash of the block.null
when its pending block.parentHash
32 Bytes -String
: Hash of the parent block.nonce
8 Bytes -String
: Hash of the generated proof-of-work.null
when its pending block.sha3Uncles
32 Bytes -String
: SHA3 of the uncles data in the block.logsBloom
256 Bytes -String
: The bloom filter for the logs of the block.null
when its pending block.transactionsRoot
32 Bytes -String
: The root of the transaction trie of the blockstateRoot
32 Bytes -String
: The root of the final state trie of the block.receiptsRoot
32 Bytes -String
: Transaction receipts are used to store the state after a transaction has been executed and are kept in an index-keyed trie. The hash of its root is placed in the block header as the receipts root.miner
-String
: The address of the beneficiary to whom the mining rewards were given.difficulty
-String
: Integer of the difficulty for this block.totalDifficulty
-String
: Integer of the total difficulty of the chain until this block.extraData
-String
: The “extra data” field of this block.size
-Number
: Integer the size of this block in bytes.gasLimit
-Number
: The maximum gas allowed in this block.gasUsed
-Number
: The total used gas by all transactions in this block.timestamp
-Number | String
: The unix timestamp for when the block was collated (returns a string if a overflow got detected).transactions
-Array
: Array of transaction objects, or 32 Bytes transaction hashes depending on thereturnTransactionObjects
parameter.uncles
-Array
: Array of uncle hashes.
Example¶
web3.pi.getBlock(3150).then(console.log);
> {
"number": 3,
"hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88",
"nonce": "0xfb6e1a62d119228b",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"transactionsRoot": "0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee",
"stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb",
"receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
"miner": "0x8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty": '21345678965432',
"totalDifficulty": '324567845321',
"size": 616,
"extraData": "0x",
"gasLimit": 3141592,
"gasUsed": 21662,
"timestamp": 1429287689,
"transactions": [
"0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
],
"uncles": []
}
getBlockTransactionCount¶
web3.pi.getBlockTransactionCount(blockHashOrBlockNumber [, callback])
Returns the number of transaction in a given block.
Parameters¶
String|Number
- The block number or hash. Or the string"genesis"
,"latest"
or"pending"
as in the default block parameter.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<number>
- The number of transactions in the given block.
Example¶
web3.pi.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log);
> 1
getUncle¶
web3.pi.getUncle(blockHashOrBlockNumber, uncleIndex [, callback])
Returns a blocks uncle by a given uncle index position.
Parameters¶
String|Number
- The block number or hash. Or the string"genesis"
,"latest"
or"pending"
as in the default block parameter.Number
- The index position of the uncle.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object>
- The returned uncle. For a return value see web3.pi.getBlock().
Note
An uncle doesn’t contain individual transactions.
Example¶
web3.pi.getUncle(500, 0).then(console.log);
> // see web3.pi.getBlock
getTransaction¶
web3.pi.getTransaction(transactionHash [, callback])
Returns a transaction matching the given transaction hash.
Parameters¶
String
- The transaction hash.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object>
- A transaction object its hash transactionHash
:
hash
32 Bytes -String
: Hash of the transaction.nonce
-Number
: The number of transactions made by the sender prior to this one.blockHash
32 Bytes -String
: Hash of the block where this transaction was in.null
when its pending.blockNumber
-Number
: Block number where this transaction was in.null
when its pending.transactionIndex
-Number
: Integer of the transactions index position in the block.null
when its pending.from
-String
: Address of the sender.to
-String
: Address of the receiver.null
when its a contract creation transaction.value
-String
: Value transferred in wei.gasPrice
-String
: The wei per unit of gas provided by the sender in wei.gas
-Number
: Gas provided by the sender.input
-String
: The data sent along with the transaction.
Example¶
web3.pi.getTransaction('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b§234').then(console.log);
> {
"hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"nonce": 2,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"transactionIndex": 0,
"from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
"value": '123450000000000000',
"gas": 314159,
"gasPrice": '2000000000000',
"input": "0x57cb2fc4"
}
getPendingTransactions¶
web3.pi.getPendingTransactions([, callback])
Returns a list of pending transactions.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object[]>
- Array of pending transactions:
hash
32 Bytes -String
: Hash of the transaction.nonce
-Number
: The number of transactions made by the sender prior to this one.blockHash
32 Bytes -String
: Hash of the block where this transaction was in.null
when its pending.blockNumber
-Number
: Block number where this transaction was in.null
when its pending.transactionIndex
-Number
: Integer of the transactions index position in the block.null
when its pending.from
-String
: Address of the sender.to
-String
: Address of the receiver.null
when its a contract creation transaction.value
-String
: Value transferred in wei.gasPrice
-String
: The wei per unit of gas provided by the sender in wei.gas
-Number
: Gas provided by the sender.input
-String
: The data sent along with the transaction.
Example¶
web3.pi.getPendingTransactions().then(console.log);
> [
{
hash: '0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b',
nonce: 2,
blockHash: '0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46',
blockNumber: 3,
transactionIndex: 0,
from: '0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b',
to: '0x6295ee1b4f6dd65047762f924ecd367c17eabf8f',
value: '123450000000000000',
gas: 314159,
gasPrice: '2000000000000',
input: '0x57cb2fc4'
v: '0x3d',
r: '0xaabc9ddafffb2ae0bac4107697547d22d9383667d9e97f5409dd6881ce08f13f',
s: '0x69e43116be8f842dcd4a0b2f760043737a59534430b762317db21d9ac8c5034'
},....,{
hash: '0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b',
nonce: 3,
blockHash: '0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46',
blockNumber: 4,
transactionIndex: 0,
from: '0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b',
to: '0x6295ee1b4f6dd65047762f924ecd367c17eabf8f',
value: '123450000000000000',
gas: 314159,
gasPrice: '2000000000000',
input: '0x57cb2fc4'
v: '0x3d',
r: '0xaabc9ddafffb2ae0bac4107697547d22d9383667d9e97f5409dd6881ce08f13f',
s: '0x69e43116be8f842dcd4a0b2f760043737a59534430b762317db21d9ac8c5034'
}
]
getTransactionFromBlock¶
getTransactionFromBlock(hashStringOrNumber, indexNumber [, callback])
Returns a transaction based on a block hash or number and the transactions index position.
Parameters¶
String
- A block number or hash. Or the string"genesis"
,"latest"
or"pending"
as in the default block parameter.Number
- The transactions index position.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object>
- A transaction object, see web3.pi.getTransaction:
Example¶
const transaction = web3.pi.getTransactionFromBlock('0x4534534534', 2).then(console.log);
> // see web3.pi.getTransaction
getTransactionReceipt¶
web3.pi.getTransactionReceipt(hash [, callback])
Returns the receipt of a transaction by transaction hash.
Note
The receipt is not available for pending transactions and returns null
.
Parameters¶
String
- The transaction hash.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise
returns Object
- A transaction receipt object, or null
when no receipt was found:
status
-Boolean
:TRUE
if the transaction was successful,FALSE
, if the EVM reverted the transaction.blockHash
32 Bytes -String
: Hash of the block where this transaction was in.blockNumber
-Number
: Block number where this transaction was in.transactionHash
32 Bytes -String
: Hash of the transaction.transactionIndex
-Number
: Integer of the transactions index position in the block.from
-String
: Address of the sender.to
-String
: Address of the receiver.null
when its a contract creation transaction.contractAddress
-String
: The contract address created, if the transaction was a contract creation, otherwisenull
.cumulativeGasUsed
-Number
: The total amount of gas used when this transaction was executed in the block.gasUsed
-Number
: The amount of gas used by this specific transaction alone.logs
-Array
: Array of log objects, which this transaction generated.
Example¶
const receipt = web3.pi.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b')
.then(console.log);
> {
"status": true,
"transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": 0,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
"cumulativeGasUsed": 314159,
"gasUsed": 30234,
"logs": [{
// logs as returned by getPastLogs, etc.
}, ...]
}
getTransactionCount¶
web3.pi.getTransactionCount(address [, defaultBlock] [, callback])
Get the numbers of transactions sent from this address.
Parameters¶
String
- The address to get the numbers of transactions from.Number|String
- (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<number>
- The number of transactions sent from the given address.
Example¶
web3.pi.getTransactionCount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe").then(console.log);
> 1
sendTransaction¶
web3.pi.sendTransaction(transactionObject [, callback])
Sends a transaction to the network.
Parameters¶
Object
- The transaction object to send:
from
-String|Number
: The address for the sending account. Uses the web3.pi.defaultAccount property, if not specified. Or an address or index of a local wallet in web3.pi.accounts.wallet.to
-String
: (optional) The destination address of the message, left undefined for a contract-creation transaction.value
-Number|String|BN|BigNumber
: (optional) The value transferred for the transaction in wei, also the endowment if it’s a contract-creation transaction.gas
-Number
: (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).gasPrice
-Number|String|BN|BigNumber
: (optional) The price of gas for this transaction in wei, defaults to web3.pi.gasPrice.data
-String
: (optional) Either a ABI byte string containing the data of the function call on a contract, or in the case of a contract-creation transaction the initialisation code.nonce
-Number
: (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.
callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Note
The from
property can also be an address or index from the web3.pi.accounts.wallet. It will then sign locally using the private key of that account, and send the transaction via web3.pi.sendSignedTransaction().
Returns¶
The callback will return the 32 bytes transaction hash.
PromiEvent
: A promise combined event emitter. Will be resolved when the transaction receipt is available. Additionally the following events are available:
"transactionHash"
returnsString
: Is fired right after the transaction is sent and a transaction hash is available."receipt"
returnsObject
: Is fired when the transaction receipt is available."confirmation"
returnsNumber
,Object
: Is fired for every confirmation up to the 12th confirmation. Receives the confirmation number as the first and the receipt as the second argument. Fired from confirmation 0 on, which is the block where its minded."error"
returnsError
: Is fired if an error occurs during sending. If a out of gas error, the second parameter is the receipt.
Example¶
// compiled solidity source code using https://remix.ethereum.org
const code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";
// using the callback
web3.pi.sendTransaction({
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
data: code // deploying a contract
}, function(error, hash){
...
});
// using the promise
web3.pi.sendTransaction({
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
value: '1000000000000000'
})
.then(function(receipt){
...
});
// using the event emitter
web3.pi.sendTransaction({
from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
value: '1000000000000000'
})
.on('transactionHash', function(hash){
...
})
.on('receipt', function(receipt){
...
})
.on('confirmation', function(confirmationNumber, receipt){ ... })
.on('error', console.error); // If a out of gas error, the second parameter is the receipt.
sendSignedTransaction¶
web3.pi.sendSignedTransaction(signedTransactionData [, callback])
Sends an already signed transaction, generated for example using web3.pi.accounts.signTransaction.
Parameters¶
String
- Signed transaction data in HEX formatFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
PromiEvent
: A promise combined event emitter. Will be resolved when the transaction receipt is available.
Please see the return values for web3.pi.sendTransaction for details.
Example¶
const Tx = require('pchainjs-tx');
const privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')
const rawTx = {
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
// mainChain: 'pchain',childChain 1: 'child_0'
chainId: 'pchain'
}
const tx = new Tx(rawTx);
tx.sign(privateKey);
const serializedTx = tx.serialize();
// console.log(serializedTx.toString('hex'));
// 0xf889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f
web3.pi.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
> // see pi.getTransactionReceipt() for details
sign¶
web3.pi.sign(dataToSign, address [, callback])
Signs data using a specific account. This account needs to be unlocked.
Parameters¶
String
- Data to sign. If String it will be converted using web3.utils.utf8ToHex.String|Number
- Address to sign data with. Or an address or index of a local wallet in web3.pi.accounts.wallet.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Note
The 2. address
parameter can also be an address or index from the web3.pi.accounts.wallet. It will then sign locally using the private key of this account.
Returns¶
Promise<string>
- The signature.
Example¶
web3.pi.sign("Hello world", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
// the below is the same
web3.pi.sign(web3.utils.utf8ToHex("Hello world"), "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
signTransaction¶
web3.pi.signTransaction(transactionObject [, address,] [, callback])
Signs a transaction with the private key of the given address. If the given address is a local unlocked account, the transaction will be signed locally.
Parameters¶
1. Object
- The transaction data to sign web3.pi.sendTransaction() for more.
1. string
- The address of the account.
3. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object>
- The RLP encoded transaction. The raw
property can be used to send the transaction using web3.pi.sendSignedTransaction.
Example¶
web3.pi.signTransaction({
from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
gasPrice: "20000000000",
gas: "21000",
to: '0x3535353535353535353535353535353535353535',
value: "1000000000000000000",
data: ""
}).then(console.log);
> {
raw: '0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88da07e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
tx: {
nonce: '0x0',
gasPrice: '0x4a817c800',
gas: '0x5208',
to: '0x3535353535353535353535353535353535353535',
value: '0xde0b6b3a7640000',
input: '0x',
v: '0x25',
r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
}
}
call¶
web3.pi.call(callObject [, defaultBlock] [, callback])
Executes a message call transaction, which is directly executed in the VM of the node, but never mined into the blockchain.
Parameters¶
Object
- A transaction object see web3.pi.sendTransaction, with the difference that for calls thefrom
property is optional as well.Number|String
- (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The returned data of the call, e.g. a smart contract functions return value.
Example¶
web3.pi.call({
to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", // contract address
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
}).then(console.log);
> "0x000000000000000000000000000000000000000000000000000000000000000a"
estimateGas¶
web3.pi.estimateGas(callObject [, callback])
Executes a message call or transaction and returns the amount of the gas used.
Parameters¶
Object
- A transaction object see web3.pi.sendTransaction, with the difference that for calls thefrom
property is optional as well.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<number>
- The used gas for the simulated call/transaction.
Example¶
web3.pi.estimateGas({
to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
}).then(console.log);
> "0x0000000000000000000000000000000000000000000000000000000000000015"
getPastLogs¶
web3.pi.getPastLogs(options [, callback])
Gets past logs, matching the given options.
Parameters¶
Object
- The filter options as follows:
fromBlock
-Number|String
: The number of the earliest block ("latest"
may be given to mean the most recent and"pending"
currently mining, block). By default"latest"
.toBlock
-Number|String
: The number of the latest block ("latest"
may be given to mean the most recent and"pending"
currently mining, block). By default"latest"
.address
-String|Array
: An address or a list of addresses to only get logs from particular account(s).topics
-Array
: An array of values which must each appear in the log entries. The order is important, if you want to leave topics out usenull
, e.g.[null, '0x12...']
. You can also pass an array for each topic with options for that topic e.g.[null, ['option1', 'option2']]
Returns¶
Promise<Array>
- Array of log objects.
The structure of the returned event Object
in the Array
looks as follows:
address
-String
: From which this event originated from.data
-String
: The data containing non-indexed log parameter.topics
-Array
: An array with max 4 32 Byte topics, topic 1-3 contains indexed parameters of the log.logIndex
-Number
: Integer of the event index position in the block.transactionIndex
-Number
: Integer of the transaction’s index position, the event was created in.transactionHash
32 Bytes -String
: Hash of the transaction this event was created in.blockHash
32 Bytes -String
: Hash of the block where this event was created in.null
when its still pending.blockNumber
-Number
: The block number where this log was created in.null
when still pending.
Example¶
web3.pi.getPastLogs({
address: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"]
}).then(console.log);
> [{
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},{...}]
getWork¶
web3.pi.getWork([callback])
Gets work for miners to mine on. Returns the hash of the current block, the seedHash, and the boundary condition to be met (“target”).
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Array>
- The mining work with the following structure:
String
32 Bytes - at index 0: current block header pow-hashString
32 Bytes - at index 1: the seed hash used for the DAG.String
32 Bytes - at index 2: the boundary condition (“target”), 2^256 / difficulty.
Example¶
web3.pi.getWork().then(console.log);
> [
"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"0x5EED00000000000000000000000000005EED0000000000000000000000000000",
"0xd1ff1c01710000000000000000000000d1ff1c01710000000000000000000000"
]
submitWork¶
web3.pi.submitWork(nonce, powHash, digest, [callback])
Used for submitting a proof-of-work solution.
Parameters¶
String
8 Bytes: The nonce found (64 bits)String
32 Bytes: The header’s pow-hash (256 bits)String
32 Bytes: The mix digest (256 bits)Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
if the provided solution is valid, otherwise false.
Example¶
web3.pi.submitWork([
"0x0000000000000001",
"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000"
])
.then(console.log);
> true
requestAccounts¶
web3.pi.requestAccounts([callback])
This method will request/enable the accounts from the current environment it is running (PMetamask, Status or Mist). It doesn’t work if you’re connected to a node with a default PWeb3.js provider. (WebsocketProvider, HttpProvidder and IpcProvider) This method will only work if you’re using the injected provider from a application like Status, Mist or PMetamask.
For further information about the behavior of this method please read the EIP of it: EIP-1102
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Array>
- Returns an array of enabled accounts.
Example¶
web3.pi.requestAccounts().then(console.log);
> ['0aae0B295369a9FD31d5F28D9Ec85E40f4cb692BAf', 0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe]
getChainId¶
web3.pi.getChainId([callback])
Returns the chain ID of the current connected node as described in the EIP-695.
Returns¶
Promise<Number>
- Returns chain ID.
getProof¶
web3.pi.getProof(address, storageKey, blockNumber, [callback])
Returns the account and storage-values of the specified account including the Merkle-proof as described in EIP-1186.
Parameters¶
String
20 Bytes: The Address of the account or contract.Array
32 Bytes: Array of storage-keys which should be proofed and included. See web3.pi.getStorageAt.Number | String | "latest" | "earliest"
: Integer block number, or the string “latest” or “earliest”.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- A account object.
balance
- The balance of the account. See web3.pi.getBalance.codeHash
- hash of the code of the account. For a simple Account without code it will return “0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470”nonce
- Nonce of the account.storageHash
- SHA3 of the StorageRoot. All storage will deliver a MerkleProof starting with this rootHash.accountProof
- Array of rlp-serialized MerkleTree-Nodes, starting with the stateRoot-Node, following the path of the SHA3 (address) as key.storageProof
- Array of storage-entries as requested.key
- The requested storage key.value
- The storage value.
Example¶
web3.pi.getProof(
"0x1234567890123456789012345678901234567890",
["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"],
"latest"
).then(console.log);
> {
"address": "0x1234567890123456789012345678901234567890",
"accountProof": [
"0xf90211a090dcaf88c40c7bbc95a912cbdde67c175767b31173df9ee4b0d733bfdd511c43a0babe369f6b12092f49181ae04ca173fb68d1a5456f18d20fa32cba73954052bda0473ecf8a7e36a829e75039a3b055e51b8332cbf03324ab4af2066bbd6fbf0021a0bbda34753d7aa6c38e603f360244e8f59611921d9e1f128372fec0d586d4f9e0a04e44caecff45c9891f74f6a2156735886eedf6f1a733628ebc802ec79d844648a0a5f3f2f7542148c973977c8a1e154c4300fec92f755f7846f1b734d3ab1d90e7a0e823850f50bf72baae9d1733a36a444ab65d0a6faaba404f0583ce0ca4dad92da0f7a00cbe7d4b30b11faea3ae61b7f1f2b315b61d9f6bd68bfe587ad0eeceb721a07117ef9fc932f1a88e908eaead8565c19b5645dc9e5b1b6e841c5edbdfd71681a069eb2de283f32c11f859d7bcf93da23990d3e662935ed4d6b39ce3673ec84472a0203d26456312bbc4da5cd293b75b840fc5045e493d6f904d180823ec22bfed8ea09287b5c21f2254af4e64fca76acc5cd87399c7f1ede818db4326c98ce2dc2208a06fc2d754e304c48ce6a517753c62b1a9c1d5925b89707486d7fc08919e0a94eca07b1c54f15e299bd58bdfef9741538c7828b5d7d11a489f9c20d052b3471df475a051f9dd3739a927c89e357580a4c97b40234aa01ed3d5e0390dc982a7975880a0a089d613f26159af43616fd9455bb461f4869bfede26f2130835ed067a8b967bfb80",
"0xf90211a0395d87a95873cd98c21cf1df9421af03f7247880a2554e20738eec2c7507a494a0bcf6546339a1e7e14eb8fb572a968d217d2a0d1f3bc4257b22ef5333e9e4433ca012ae12498af8b2752c99efce07f3feef8ec910493be749acd63822c3558e6671a0dbf51303afdc36fc0c2d68a9bb05dab4f4917e7531e4a37ab0a153472d1b86e2a0ae90b50f067d9a2244e3d975233c0a0558c39ee152969f6678790abf773a9621a01d65cd682cc1be7c5e38d8da5c942e0a73eeaef10f387340a40a106699d494c3a06163b53d956c55544390c13634ea9aa75309f4fd866f312586942daf0f60fb37a058a52c1e858b1382a8893eb9c1f111f266eb9e21e6137aff0dddea243a567000a037b4b100761e02de63ea5f1fcfcf43e81a372dafb4419d126342136d329b7a7ba032472415864b08f808ba4374092003c8d7c40a9f7f9fe9cc8291f62538e1cc14a074e238ff5ec96b810364515551344100138916594d6af966170ff326a092fab0a0d31ac4eef14a79845200a496662e92186ca8b55e29ed0f9f59dbc6b521b116fea090607784fe738458b63c1942bba7c0321ae77e18df4961b2bc66727ea996464ea078f757653c1b63f72aff3dcc3f2a2e4c8cb4a9d36d1117c742833c84e20de994a0f78407de07f4b4cb4f899dfb95eedeb4049aeb5fc1635d65cf2f2f4dfd25d1d7a0862037513ba9d45354dd3e36264aceb2b862ac79d2050f14c95657e43a51b85c80",
"0xf90171a04ad705ea7bf04339fa36b124fa221379bd5a38ffe9a6112cb2d94be3a437b879a08e45b5f72e8149c01efcb71429841d6a8879d4bbe27335604a5bff8dfdf85dcea00313d9b2f7c03733d6549ea3b810e5262ed844ea12f70993d87d3e0f04e3979ea0b59e3cdd6750fa8b15164612a5cb6567cdfb386d4e0137fccee5f35ab55d0efda0fe6db56e42f2057a071c980a778d9a0b61038f269dd74a0e90155b3f40f14364a08538587f2378a0849f9608942cf481da4120c360f8391bbcc225d811823c6432a026eac94e755534e16f9552e73025d6d9c30d1d7682a4cb5bd7741ddabfd48c50a041557da9a74ca68da793e743e81e2029b2835e1cc16e9e25bd0c1e89d4ccad6980a041dda0a40a21ade3a20fcd1a4abb2a42b74e9a32b02424ff8db4ea708a5e0fb9a09aaf8326a51f613607a8685f57458329b41e938bb761131a5747e066b81a0a16808080a022e6cef138e16d2272ef58434ddf49260dc1de1f8ad6dfca3da5d2a92aaaadc58080",
"0xf851808080a009833150c367df138f1538689984b8a84fc55692d3d41fe4d1e5720ff5483a6980808080808080808080a0a319c1c415b271afc0adcb664e67738d103ac168e0bc0b7bd2da7966165cb9518080"
],
"balance": 0,
"codeHash": "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
"nonce": 0,
"storageHash": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"storageProof": [
{
"key": "0x0000000000000000000000000000000000000000000000000000000000000000",
"value": '0',
"proof": []
},
{
"key": "0x0000000000000000000000000000000000000000000000000000000000000001",
"value": '0',
"proof": []
}
]
}
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.subscribe¶
The web3.pi.subscribe
function lets you subscribe to specific events in the blockchain.
subscribe¶
web3.pi.subscribe(type [, options] [, callback]);
Parameters¶
String
- The subscription, you want to subscribe to.Mixed
- (optional) Optional additional parameters, depending on the subscription type.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription, and the subscription itself as 3 parameter.
Returns¶
EventEmitter
- A Subscription instance
subscription.id
: The subscription id, used to identify and unsubscribing the subscription.subscription.subscribe([callback])
: Can be used to re-subscribe with the same parameters.subscription.unsubscribe([callback])
: Unsubscribes the subscription and returns TRUE in the callback if successfull.subscription.options
: The subscription options, used when re-subscribing.subscription.type
: The subscription type.subscription.method
: The subscription method e.g.:logs
.on("data")
returnsObject
: Fires on each incoming log with the log object as argument.on("changed")
returnsObject
: Fires on each log which was removed from the blockchain. The log will have the additional property"removed: true"
.on("error")
returnsObject
: Fires when an error in the subscription occurs.
Notification returns¶
any
- depends on the subscription, see the different subscriptions for more.
Example¶
const subscription = web3.pi.subscribe('logs', {
address: '0x123456..',
topics: ['0x12345...']
}, function(error, result){
if (!error)
console.log(result);
});
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if(success)
console.log('Successfully unsubscribed!');
});
clearSubscriptions¶
web3.pi.clearSubscriptions()
Resets subscriptions.
Note
This will not reset subscriptions from other packages like web3-shh
.
Returns¶
Promise<boolean>
Example¶
web3.pi.subscribe('logs', {} ,function(){ ... });
...
web3.pi.clearSubscriptions();
subscribe(“pendingTransactions”)¶
web3.pi.subscribe('pendingTransactions' [, callback]);
Subscribes to incoming pending transactions.
Parameters¶
String
-"pendingTransactions"
, the type of the subscription.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription.
Returns¶
EventEmitter
: An subscription instance as an event emitter with the following events:
"data"
returnsString
: Fires on each incoming pending transaction and returns the transaction hash."error"
returnsObject
: Fires when an error in the subscription occurs.
Notification returns¶
Object|Null
- First parameter is an error object if the subscription failed.String
- Second parameter is the transaction hash.
Example¶
const subscription = web3.pi.subscribe('pendingTransactions', function(error, result){
if (!error)
console.log(result);
})
.on("data", function(transaction){
console.log(transaction);
});
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if(success)
console.log('Successfully unsubscribed!');
});
subscribe(“newBlockHeaders”)¶
web3.pi.subscribe('newBlockHeaders' [, callback]);
Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain.
Parameters¶
String
-"newBlockHeaders"
, the type of the subscription.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription.
Returns¶
EventEmitter
: An subscription instance as an event emitter with the following events:
"data"
returnsObject
: Fires on each incoming block header."error"
returnsObject
: Fires when an error in the subscription occurs.
The structure of a returned block header is as follows:
number
-Number
: The block number.null
when its pending block.hash
32 Bytes -String
: Hash of the block.null
when its pending block.parentHash
32 Bytes -String
: Hash of the parent block.nonce
8 Bytes -String
: Hash of the generated proof-of-work.null
when its pending block.sha3Uncles
32 Bytes -String
: SHA3 of the uncles data in the block.logsBloom
256 Bytes -String
: The bloom filter for the logs of the block.null
when its pending block.transactionsRoot
32 Bytes -String
: The root of the transaction trie of the blockstateRoot
32 Bytes -String
: The root of the final state trie of the block.receiptsRoot
32 Bytes -String
: Transaction receipts are used to store the state after a transaction has been executed and are kept in an index-keyed trie. The hash of its root is placed in the block header as the receipts root.miner
-String
: The address of the beneficiary to whom the mining rewards were given.extraData
-String
: The “extra data” field of this block.gasLimit
-Number
: The maximum gas allowed in this block.gasUsed
-Number
: The total used gas by all transactions in this block. It can be multiplied to gasPrice to obtain total amount in wei.timestamp
-Number
: The unix timestamp for when the block was collated.
Notification returns¶
Object|Null
- First parameter is an error object if the subscription failed.Object
- The block header object like above.
Example¶
const subscription = web3.pi.subscribe('newBlockHeaders', function(error, result){
if (!error) {
console.log(result);
return;
}
console.error(error);
})
.on("data", function(blockHeader){
console.log(blockHeader);
})
.on("error", console.error);
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if (success) {
console.log('Successfully unsubscribed!');
}
});
subscribe(“syncing”)¶
web3.pi.subscribe('syncing' [, callback]);
Subscribe to syncing events. This will return an object when the node is syncing and when its finished syncing will return FALSE
.
Parameters¶
String
-"syncing"
, the type of the subscription.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription.
Returns¶
EventEmitter
: An subscription instance as an event emitter with the following events:
"data"
returnsObject
: Fires on each incoming sync object as argument."changed"
returnsObject
: Fires when the synchronisation is started withtrue
and when finished withfalse
."error"
returnsObject
: Fires when an error in the subscription occurs.
For the structure of a returned event Object
see web3.pi.isSyncing return values.
Notification returns¶
Object|Null
- First parameter is an error object if the subscription failed.Object|Boolean
- The syncing object, when started it will returntrue
once or when finished it will return false once.
Example¶
const subscription = web3.pi.subscribe('syncing', function(error, sync){
if (!error)
console.log(sync);
})
.on("data", function(sync){
// show some syncing stats
})
.on("changed", function(isSyncing){
if(isSyncing) {
// stop app operation
} else {
// regain app operation
}
});
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if(success)
console.log('Successfully unsubscribed!');
});
subscribe(“logs”)¶
web3.pi.subscribe('logs', options [, callback]);
Subscribes to incoming logs, filtered by the given options.
Parameters¶
"logs"
-String
, the type of the subscription.Object
- The subscription options
fromBlock
-Number
: The number of the earliest block. By defaultnull
.address
-String|Array
: An address or a list of addresses to only get logs from particular account(s).topics
-Array
: An array of values which must each appear in the log entries. The order is important, if you want to leave topics out usenull
, e.g.[null, '0x00...']
. You can also pass another array for each topic with options for that topic e.g.[null, ['option1', 'option2']]
callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription.
Returns¶
EventEmitter
: An subscription instance as an event emitter with the following events:
"data"
returnsObject
: Fires on each incoming log with the log object as argument."changed"
returnsObject
: Fires on each log which was removed from the blockchain. The log will have the additional property"removed: true"
."error"
returnsObject
: Fires when an error in the subscription occurs.
For the structure of a returned event Object
see web3.pi.getPastEvents return values.
Notification returns¶
Object|Null
- First parameter is an error object if the subscription failed.Object
- The log object like in web3.pi.getPastEvents return values.
Example¶
const subscription = web3.pi.subscribe('logs', {
address: '0x123456..',
topics: ['0x12345...']
}, (error, result) => {
if (!error) {
console.log(result);
}
console.error(error);
})
.on("data", (log) => {
console.log(log);
})
.on("changed", (log) => {
console.log(log);
});
// unsubscribes the subscription
subscription.unsubscribe((error, success) => {
if (success) {
console.log('Successfully unsubscribed!');
}
});
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.Contract¶
The web3.pi.Contract
object makes it easy to interact with smart contracts on the Pchain blockchain.
When you create a new contract object you give it the json interface of the respective smart contract
and web3 will auto convert all calls into low level ABI calls over RPC for you.
This allows you to interact with smart contracts as if they were JavaScript objects.
To use it standalone:
web3.pi.Contract¶
new web3.pi.Contract(jsonInterface, address, options)
Creates a new contract instance with all its methods and events defined in its json interface object.
Parameters¶
jsonInterface
-Array
: The json interface for the contract to instantiateaddress
-String
(optional): This address is necessary for transactions and call requests and can also be added later usingmyContract.options.address = '0x1234..'.
options
-Object
(optional): The options of the contract. Some are used as fallbacks for calls and transactions:data
-String
: The byte code of the contract. Used when the contract gets deployed.address
-String
: The address where the contract is deployed. See address.- defaultAccount
- defaultBlock
- defaultGas
- defaultGasPrice
- transactionBlockTimeout
- transactionConfirmationBlocks
- transactionPollingTimeout
- transactionSigner
Returns¶
Object
: The contract instance with all its methods and events.
Example¶
const myContract = new web3.pi.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', {
defaultAccount: '0x1234567890123456789012345678901234567891', // default from address
defaultGasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
});
= Properties =¶
options¶
The contract options object has the following properties:
data
-String
: The contract bytecode.address
-String
(deprecated usecontract.address
): The address of the contract.
address¶
myContract.address
The address used for this contract instance. All transactions generated by pweb3.js from this contract will contain this address as the “to”.
The address will be stored in lowercase.
Property¶
address
- String|null
: The address for this contract, or null
if it’s not yet set.
Example¶
myContract.address;
> '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'
// set a new address
myContract.address = '0x1234FFDD...';
jsonInterface¶
myContract.jsonInterface
The json interface object derived from the ABI of this contract.
Property¶
jsonInterface
- AbiModel
: The json interface for this contract. Re-setting this will regenerate the methods and events of the contract instance.
AbiModel¶
interface AbiModel {
getMethod(name: string): AbiItemModel | false;
getMethods(): AbiItemModel[];
hasMethod(name: string): boolean;
getEvent(name: string): AbiItemModel | false;
getEvents(): AbiItemModel[];
getEventBySignature(signature: string): AbiItemModel;
hasEvent(name: string): boolean;
}
interface AbiItemModel {
name: string;
signature: string;
payable: boolean;
anonymous: boolean;
getInputLength(): Number;
getInputs(): AbiInput[];
getIndexedInputs(): AbiInput[];
getOutputs(): AbiOutput[];
isOfType(): boolean;
}
interface AbiInput {
name: string;
type: string;
indexed?: boolean;
components?: AbiInput[];
}
interface AbiOutput {
name: string;
type: string;
components?: AbiOutput[];
}
= Methods =¶
clone¶
myContract.clone()
Clones the current contract instance.
Parameters¶
none
Returns¶
Object
: The new contract instance.
Example¶
const contract1 = new pi.Contract(abi, address, {gasPrice: '12345678', defaultAccount: fromAddress});
const contract2 = contract1.clone();
contract2.address = address2;
(contract1.address !== contract2.address);
> true
deploy¶
myContract.deploy(options)
Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance.
Parameters¶
options
-Object
: The options used for deployment.data
-String
: The byte code of the contract.arguments
-Array
(optional): The arguments which get passed to the constructor on deployment.
Returns¶
Object
: The transaction object:
Array
- arguments: The arguments passed to the method before. They can be changed.Function
- send: Will deploy the contract. The promise will resolve with the new contract instance, instead of the receipt!Function
- estimateGas: Will estimate the gas used for deploying.Function
- encodeABI: Encodes the ABI of the deployment, which is contract data + constructor parameters
For details to the methods see the documentation below.
Example¶
myContract.deploy({
data: '0x12345...',
arguments: [123, 'My String']
})
.send({
from: '0x1234567890123456789012345678901234567891',
gas: 1500000,
gasPrice: '30000000000000'
}, (error, transactionHash) => { ... })
.on('error', (error) => { ... })
.on('transactionHash', (transactionHash) => { ... })
.on('receipt', (receipt) => {
console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation', (confirmationNumber, receipt) => { ... })
.then((newContractInstance) => {
console.log(newContractInstance.options.address) // instance with the new contract address
});
// When the data is already set as an option to the contract itself
myContract.options.data = '0x12345...';
myContract.deploy({
arguments: [123, 'My String']
})
.send({
from: '0x1234567890123456789012345678901234567891',
gas: 1500000,
gasPrice: '30000000000000'
})
.then((newContractInstance) => {
console.log(newContractInstance.options.address) // instance with the new contract address
});
// Simply encoding
myContract.deploy({
data: '0x12345...',
arguments: [123, 'My String']
})
.encodeABI();
> '0x12345...0000012345678765432'
// Gas estimation
myContract.deploy({
data: '0x12345...',
arguments: [123, 'My String']
})
.estimateGas((err, gas) => {
console.log(gas);
});
methods¶
myContract.methods.myMethod([param1[, param2[, ...]]])
Creates a transaction object for that method, which then can be called, send, estimated.
The methods of this smart contract are available through:
- The name:
myContract.methods.myMethod(123)
- The name with parameters:
myContract.methods['myMethod(uint256)'](123)
- The signature:
myContract.methods['0x58cf5f10'](123)
This allows calling functions with same name but different parameters from the JavaScript contract object.
Parameters¶
Parameters of any method depend on the smart contracts methods, defined in the JSON interface.
Returns¶
Object
: The Transaction Object:
Array
- arguments: The arguments passed to the method before. They can be changed.Function
- call: Will call the “constant” method and execute its smart contract method in the EVM without sending a transaction (Can’t alter the smart contract state).Function
- send: Will send a transaction to the smart contract and execute its method (Can alter the smart contract state).Function
- estimateGas: Will estimate the gas used when the method would be executed on chain.Function
- encodeABI: Encodes the ABI for this method. This can be send using a transaction, call the method or passing into another smart contracts method as argument.
For details to the methods see the documentation below.
Example¶
// calling a method
myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, (error, result) => {
...
});
// or sending and using a promise
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then((receipt) => {
// receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
});
// or sending and using the events
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.on('transactionHash', (hash) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('error', console.error);
methods.myMethod.call¶
myContract.methods.myMethod([param1[, param2[, ...]]]).call(transactionObject, blockNumber, callback])
Will call a “constant” method and execute its smart contract method in the EVM without sending any transaction. Note calling can not alter the smart contract state.
Parameters¶
options
- Object
(optional): The options used for calling.
1.* transactionObject
from
-String
(optional): The address the call “transaction” should be made from.gasPrice
-String
(optional): The gas price in wei to use for this call “transaction”.It is the wei per unit of gas.gas
-Number
(optional): The maximum gas provided for this call “transaction” (gas limit).
2.*``blockNumber`` - Number
: The block number this log was created in. null
when still pending.
3.*``callback`` - Function
(optional): This callback will be fired with the result of the smart contract method execution as the second argument, or with an error object as the first argument.
Returns¶
Promise<any>
- The return value(s) of the smart contract method.
If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices:
Example¶
// using the callback
myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, (error, result) => {
...
});
// using the promise
myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then((result) => {
...
});
// MULTI-ARGUMENT RETURN:
// Solidity
contract MyContract {
function myFunction() returns(uint256 myNumber, string myString) {
return (23456, "Hello!%");
}
}
// pweb3.js
const MyContract = new web3.pi.Contract(abi, address);
MyContract.methods.myFunction().call()
.then(console.log);
> Result {
myNumber: '23456',
myString: 'Hello!%',
0: '23456', // these are here as fallbacks if the name is not know or given
1: 'Hello!%'
}
// SINGLE-ARGUMENT RETURN:
// Solidity
contract MyContract {
function myFunction() returns(string myString) {
return "Hello!%";
}
}
// pweb3.js
const MyContract = new web3.pi.Contract(abi, address);
MyContract.methods.myFunction().call()
.then(console.log);
> "Hello!%"
methods.myMethod.send¶
myContract.methods.myMethod([param1[, param2[, ...]]]).send(options[, callback])
Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state.
Parameters¶
options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.It is the wei per unit of gas.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).value
- ``Number|String|BN|BigNumber``(optional): The value transferred for the transaction in wei.
callback
-Function
(optional): This callback will be fired first with the “transactionHash”, or with an error object as the first argument.
Returns¶
The callback will return the 32 bytes transaction hash.
PromiEvent
: A promise combined event emitter. Will be resolved when the transaction receipt is available, OR if this send()
is called from a someContract.deploy()
, then the promise will resolve with the new contract instance. Additionally the following events are available:
"transactionHash"
returnsString
: is fired right after the transaction is sent and a transaction hash is available."receipt"
returnsObject
: is fired when the transaction receipt is available. Receipts from contracts will have nologs
property, but instead anevents
property with event names as keys and events as properties. See getPastEvents return values for details about the returned event object."confirmation"
returnsNumber
,Object
: is fired for every confirmation up to the 24th confirmation. Receives the confirmation number as the first and the receipt as the second argument. Fired from confirmation 1 on, which is the block where it’s mined."error"
returnsError
: is fired if an error occurs during sending. If an out of gas error, the second parameter is the receipt.
Example¶
// using the callback
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, (error, transactionHash) => {
...
});
// using the promise
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then((receipt) => {
// receipt can also be a new contract instance, when coming from a "contract.deploy({...}).send()"
});
// using the event emitter
myContract.methods.myMethod(123).send({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
// receipt example
console.log(receipt);
> {
"transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": 0,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"contractAddress": "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
"cumulativeGasUsed": 314159,
"gasUsed": 30234,
"events": {
"MyEvent": {
returnValues: {
myIndexedParam: 20,
myOtherIndexedParam: '0x123456789...',
myNonIndexParam: 'My String'
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},
"MyOtherEvent": {
...
},
"MyMultipleEvent":[{...}, {...}] // If there are multiple of the same event, they will be in an array
}
}
})
.on('error', console.error); // If there's an out of gas error the second parameter is the receipt.
methods.myMethod.estimateGas¶
myContract.methods.myMethod([param1[, param2[, ...]]]).estimateGas(options[, callback])
Will call estimate the gas a method execution will take when executed in the EVM without. The estimation can differ from the actual gas used when later sending a transaction, as the state of the smart contract can be different at that time.
Parameters¶
options
-Object
(optional): The options used for calling.from
-String
(optional): The address the call “transaction” should be made from.gas
-Number
(optional): The maximum gas provided for this call “transaction” (gas limit). Setting a specific value helps to detect out of gas errors. If all gas is used it will return the same number.value
- ``Number|String|BN|BigNumber``(optional): The value transferred for the call “transaction” in wei.
callback
-Function
(optional): This callback will be fired with the result of the gas estimation as the second argument, or with an error object as the first argument.
Returns¶
Promise<number>
- The gas amount estimated.
Example¶
// using the callback
myContract.methods.myMethod(123).estimateGas({gas: 5000000}, function(error, gasAmount){
if(gasAmount == 5000000)
console.log('Method ran out of gas');
});
// using the promise
myContract.methods.myMethod(123).estimateGas({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'})
.then(function(gasAmount){
...
})
.catch(function(error){
...
});
methods.myMethod.encodeABI¶
myContract.methods.myMethod([param1[, param2[, ...]]]).encodeABI()
Encodes the ABI for this method. This can be used to send a transaction, call a method, or pass it into another smart contracts method as arguments.
Parameters¶
none
Returns¶
String
: The encoded ABI byte code to send via a transaction or call.
Example¶
myContract.methods.myMethod(123).encodeABI();
> '0x58cf5f1000000000000000000000000000000000000000000000000000000000000007B'
= Events =¶
once¶
myContract.once(event[, options], callback)
Subscribes to an event and unsubscribes immediately after the first event or error. Will only fire for a single event.
Parameters¶
event
-String
: The name of the event in the contract, or"allEvents"
to get all events.options
-Object
(optional): The options used for deployment.filter
-Object
(optional): Lets you filter events by indexed parameters, e.g.{filter: {myNumber: [12,13]}}
means all events where “myNumber” is 12 or 13.topics
-Array
(optional): This allows you to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically.
callback
-Function
: This callback will be fired for the first event as the second argument, or an error as the first argument. See getPastEvents return values for details about the event structure.
Returns¶
undefined
Example¶
myContract.once('MyEvent', {
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
fromBlock: 0
}, (error, event) => { console.log(event); });
// event output example
> {
returnValues: {
myIndexedParam: 20,
myOtherIndexedParam: '0x123456789...',
myNonIndexParam: 'My String'
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
events¶
myContract.events.MyEvent([options][, callback])
Subscribe to an event
Parameters¶
options
-Object
(optional): The options used for deployment.filter
-Object
(optional): Let you filter events by indexed parameters, e.g.{filter: {myNumber: [12,13]}}
means all events where “myNumber” is 12 or 13.fromBlock
-Number
(optional): The block number from which to get events on.topics
-Array
(optional): This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically.
callback
-Function
(optional): This callback will be fired for each event as the second argument, or an error as the first argument.
Returns¶
EventEmitter
: The event emitter has the following events:
"data"
returnsObject
: Fires on each incoming event with the event object as argument."changed"
returnsObject
: Fires on each event which was removed from the blockchain. The event will have the additional property"removed: true"
."error"
returnsObject
: Fires when an error in the subscription occurs.
The structure of the returned event Object
looks as follows:
event
-String
: The event name.signature
-String|Null
: The event signature,null
if it’s an anonymous event.address
-String
: Address this event originated from.returnValues
-Object
: The return values coming from the event, e.g.{myVar: 1, myVar2: '0x234...'}
.logIndex
-Number
: Integer of the event index position in the block.transactionIndex
-Number
: Integer of the transaction’s index position the event was created in.transactionHash
32 Bytes -String
: Hash of the transaction this event was created in.blockHash
32 Bytes -String
: Hash of the block this event was created in.null
when it’s still pending.blockNumber
-Number
: The block number this log was created in.null
when still pending.raw.data
-String
: The data containing non-indexed log parameter.raw.topics
-Array
: An array with max 4 32 Byte topics, topic 1-3 contains indexed parameters of the event.
Example¶
myContract.events.MyEvent({
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
fromBlock: 0
}, (error, event) => { console.log(event); })
.on('data', (event) => {
console.log(event); // same results as the optional callback above
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
// event output example
> {
returnValues: {
myIndexedParam: 20,
myOtherIndexedParam: '0x123456789...',
myNonIndexParam: 'My String'
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
events.allEvents¶
myContract.events.allEvents([options][, callback])
Same as events but receives all events from this smart contract. Optionally the filter property can filter those events.
getPastEvents¶
myContract.getPastEvents(event[, options][, callback])
Gets past events for this contract.
Parameters¶
event
-String
: The name of the event in the contract, or"allEvents"
to get all events.options
-Object
(optional): The options used for deployment.filter
-Object
(optional): Lets you filter events by indexed parameters, e.g.{filter: {myNumber: [12,13]}}
means all events where “myNumber” is 12 or 13.fromBlock
-Number
(optional): The block number from which to get events on.toBlock
-Number
(optional): The block number to get events up to (Defaults to"latest"
).topics
-Array
(optional): This allows manually setting the topics for the event filter. If given the filter property and event signature, (topic[0]) will not be set automatically.
callback
-Function
(optional): This callback will be fired with an array of event logs as the second argument, or an error as the first argument.
Returns¶
Promise
returns Array
: An array with the past event Objects
, matching the given event name and filter.
For the structure of a returned event Object
see getPastEvents return values.
Example¶
myContract.getPastEvents('MyEvent', {
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
fromBlock: 0,
toBlock: 'latest'
}, (error, events) => { console.log(events); })
.then((events) => {
console.log(events) // same results as the optional callback above
});
> [{
returnValues: {
myIndexedParam: 20,
myOtherIndexedParam: '0x123456789...',
myNonIndexParam: 'My String'
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
},
event: 'MyEvent',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
},{
...
}]
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.accounts¶
The web3.pi.accounts
contains functions to generate Pchain accounts and sign transactions and data.
Note
This package got NOT audited until now. Take precautions to clear memory properly, store the private keys safely, and test transaction receiving and sending functionality properly before using in production!
import {Accounts} from 'web3-pi-accounts';
// Passing in the pi or web3 package is necessary to allow retrieving chainId, gasPrice and nonce automatically
// for accounts.signTransaction().
const accounts = new Accounts('ws://localhost:6970/pchain', null, options);
create¶
web3.pi.accounts.create([entropy]);
Generates an account object with private key and public key. It’s different from web3.pi.personal.newAccount() which creates an account over the network on the node via an RPC call.
Parameters¶
entropy
-String
(optional): A random string to increase entropy. If given it should be at least 32 characters. If none is given a random string will be generated using randomhex.
Returns¶
Object
- The account object with the following structure:
address
-string
: The account address.privateKey
-string
: The accounts private key. This should never be shared or stored unencrypted in localstorage! Also make sure tonull
the memory after usage.signTransaction(tx [, callback])
-Function
: The function to sign transactions. See web3.pi.accounts.signTransaction() for more.sign(data)
-Function
: The function to sign transactions. See web3.pi.accounts.sign() for more.
Example¶
web3.pi.accounts.create();
> {
address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
web3.pi.accounts.create('2435@#@#@±±±±!!!!678543213456764321§34567543213456785432134567');
> {
address: "0xF2CD2AA0c7926743B1D4310b2BC984a0a453c3d4",
privateKey: "0xd7325de5c2c1cf0009fac77d3d04a9c004b038883446b065871bc3e831dcd098",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
web3.pi.accounts.create(web3.utils.randomHex(32));
> {
address: "0xe78150FaCD36E8EB00291e251424a0515AA1FF05",
privateKey: "0xcc505ee6067fba3f6fc2050643379e190e087aeffe5d958ab9f2f3ed3800fa4e",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
privateKeyToAccount¶
web3.pi.accounts.privateKeyToAccount(privateKey);
Creates an account object from a private key.
Parameters¶
privateKey
-String
: The private key hex string beginning with0x
.
Returns¶
Object
- The account object with the structure seen here.
Example¶
web3.pi.accounts.privateKeyToAccount('0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709');
> {
address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
signTransaction¶
web3.pi.accounts.signTransaction(tx, privateKey [, callback]);
Signs an Pchain transaction with a given private key.
Parameters¶
tx
-Object
: The transaction’s properties object as follows:nonce
-String
: (optional) The nonce to use when signing this transaction. Default will use web3.pi.getTransactionCount().chainId
-String
: (optional) The chain id to use when signing this transaction. Default will use web3.pi.net.getId().to
-String
: (optional) The receiver of the transaction, can be empty when deploying a contract.data
-String
: (optional) The call data of the transaction, can be empty for simple value transfers.value
-String
: (optional) The value of the transaction in wei.gasPrice
-String
: (optional) The gas price set by this transaction, if empty, it will use web3.pi.gasPrice()gas
-String
: The gas provided by the transaction.
privateKey
-String
: The private key to sign with.callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise
returningObject
: The signed data RLP encoded transaction, or ifreturnSignature
istrue
the signature values as follows:messageHash
-String
: The hash of the given message.r
-String
: First 32 bytes of the signatures
-String
: Next 32 bytes of the signaturev
-String
: Recovery value + 27rawTransaction
-String
: The RLP encoded transaction, ready to be send using web3.pi.sendSignedTransaction.transactionHash
-String
: The transaction hash for the RLP encoded transaction.
Example¶
web3.pi.accounts.signTransaction({
to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
value: '1000000000',
gas: 2000000
}, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')
.then(console.log);
> {
messageHash: '0x88cfbd7e51c7a40540b233cf68b62ad1df3e92462f1c6018d6d67eae0f3b08f5',
v: '0x25',
r: '0xc9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895',
s: '0x727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68',
rawTransaction: '0xf869808504e3b29200831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a0c9cf86333bcb065d140032ecaab5d9281bde80f21b9687b3e94161de42d51895a0727a108a0b8d101465414033c3f705a9c7b826e596766046ee1183dbc8aeaa68',
transactionHash: '0xde8db924885b0803d2edc335f745b2b8750c8848744905684c20b987443a9593'
}
web3.pi.accounts.signTransaction({
to: '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',
value: '1000000000',
gas: 2000000,
gasPrice: '234567897654321',
nonce: 0,
chainId: 1
}, '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318')
.then(console.log);
> {
messageHash: '0x6893a6ee8df79b0f5d64a180cd1ef35d030f3e296a5361cf04d02ce720d32ec5',
r: '0x9ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9c',
s: '0x440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428',
v: '0x25',
rawTransaction: '0xf86a8086d55698372431831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca008025a009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428',
transactionHash: '0xd8f64a42b57be0d565f385378db2f6bf324ce14a594afc05de90436e9ce01f60'
}
recoverTransaction¶
web3.pi.accounts.recoverTransaction(rawTransaction);
Recovers the Pchain address which was used to sign the given RLP encoded transaction.
Parameters¶
signature
-String
: The RLP encoded transaction.
Returns¶
String
: The Pchain address used to sign this transaction.
Example¶
web3.pi.accounts.recoverTransaction('0xf86180808401ef364594f0109fc8df283027b6285cc889f5aa624eac1f5580801ca031573280d608f75137e33fc14655f097867d691d5c4c44ebe5ae186070ac3d5ea0524410802cdc025034daefcdfa08e7d2ee3f0b9d9ae184b2001fe0aff07603d9');
> "0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"
hashMessage¶
web3.pi.accounts.hashMessage(message);
Hashes the given message to be passed web3.pi.accounts.recover() function. The data will be UTF-8 HEX decoded and enveloped as follows: "\x19Pchain Signed Message:\n" + message.length + message
and hashed using keccak256.
Parameters¶
message
-String
: A message to hash, if its HEX it will be UTF8 decoded before.
Returns¶
String
: The hashed message
Example¶
web3.pi.accounts.hashMessage("Hello World")
> "0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2"
// the below results in the same hash
web3.pi.accounts.hashMessage(web3.utils.utf8ToHex("Hello World"))
> "0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2"
sign¶
web3.pi.accounts.sign(data, privateKey);
Signs arbitrary data. This data is before UTF-8 HEX decoded and enveloped as follows: "\x19Pchain Signed Message:\n" + message.length + message
.
Parameters¶
data
-String
: The data to sign. If its a string it will beprivateKey
-String
: The private key to sign with.
Returns¶
Object
: The signed data RLP encoded signature, or ifreturnSignature
istrue
the signature values as follows:message
-String
: The the given message.messageHash
-String
: The hash of the given message.r
-String
: First 32 bytes of the signatures
-String
: Next 32 bytes of the signaturev
-String
: Recovery value + 27
Example¶
web3.pi.accounts.sign('Some data', '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
> {
message: 'Some data',
messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
v: '0x1c',
r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029',
signature: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c'
}
recover¶
web3.pi.accounts.recover(signatureObject);
web3.pi.accounts.recover(message, signature [, preFixed]);
web3.pi.accounts.recover(message, v, r, s [, preFixed]);
Recovers the Pchain address which was used to sign the given data.
Parameters¶
message|signatureObject
-String|Object
: Either signed message or hash, or the signature object as following values:messageHash
-String
: The hash of the given message already prefixed with"\x19Pchain Signed Message:\n" + message.length + message
.r
-String
: First 32 bytes of the signatures
-String
: Next 32 bytes of the signaturev
-String
: Recovery value + 27
signature
-String
: The raw RLP encoded signature, OR parameter 2-4 as v, r, s values.preFixed
-Boolean
(optional, default:false
): If the last parameter istrue
, the given message will NOT automatically be prefixed with"\x19Pchain Signed Message:\n" + message.length + message
, and assumed to be already prefixed.
Returns¶
String
: The Pchain address used to sign this data.
Example¶
web3.pi.accounts.recover({
messageHash: '0x1da44b586eb0729ff70a73c326926f6ed5a25f5b056e7f47fbc6e58d86871655',
v: '0x1c',
r: '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd',
s: '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029'
})
> "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
// message, signature
web3.pi.accounts.recover('Some data', '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c');
> "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
// message, v, r, s
web3.pi.accounts.recover('Some data', '0x1c', '0xb91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd', '0x6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a029');
> "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23"
encrypt¶
web3.pi.accounts.encrypt(privateKey, password);
Encrypts a private key to the web3 keystore v3 standard.
Parameters¶
privateKey
-String
: The private key to encrypt.password
-String
: The password used for encryption.
Returns¶
Object
: The encrypted keystore v3 JSON.
Example¶
web3.pi.accounts.encrypt('0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318', 'test!')
> {
version: 3,
id: '04e9bcbb-96fa-497b-94d1-14df4cd20af6',
address: '2c7536e3605d9c16a7a3d7b1898e529396a65c23',
crypto: {
ciphertext: 'a1c25da3ecde4e6a24f3697251dd15d6208520efc84ad97397e906e6df24d251',
cipherparams: { iv: '2885df2b63f7ef247d753c82fa20038a' },
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams: {
dklen: 32,
salt: '4531b3c174cc3ff32a6a7a85d6761b410db674807b2d216d022318ceee50be10',
n: 262144,
r: 8,
p: 1
},
mac: 'b8b010fff37f9ae5559a352a185e86f9b9c1d7f7a9f1bd4e82a5dd35468fc7f6'
}
}
decrypt¶
web3.pi.accounts.decrypt(keystoreJsonV3, password);
Decrypts a keystore v3 JSON, and creates the account.
Parameters¶
keystoreJsonV3
-String
: The encrypted keystore v3 JSON.password
-String
: The password used for encryption.
Returns¶
Object
: The decrypted account.
Example¶
web3.pi.accounts.decrypt({
version: 3,
id: '04e9bcbb-96fa-497b-94d1-14df4cd20af6',
address: '2c7536e3605d9c16a7a3d7b1898e529396a65c23',
crypto: {
ciphertext: 'a1c25da3ecde4e6a24f3697251dd15d6208520efc84ad97397e906e6df24d251',
cipherparams: { iv: '2885df2b63f7ef247d753c82fa20038a' },
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams: {
dklen: 32,
salt: '4531b3c174cc3ff32a6a7a85d6761b410db674807b2d216d022318ceee50be10',
n: 262144,
r: 8,
p: 1
},
mac: 'b8b010fff37f9ae5559a352a185e86f9b9c1d7f7a9f1bd4e82a5dd35468fc7f6'
}
}, 'test!');
> {
address: "0x2c7536E3605D9C16a7a3D7b1898e529396a65c23",
privateKey: "0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
wallet¶
web3.pi.accounts.wallet;
Contains an in memory wallet with multiple accounts. These accounts can be used when using web3.pi.sendTransaction().
Example¶
web3.pi.accounts.wallet;
> Wallet {
0: {...}, // account by index
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...}, // same account by address
"0xf0109fc8df283027b6285cc889f5aa624eac1f55": {...}, // same account by address lowercase
1: {...},
"0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...},
"0xd0122fc8df283027b6285cc889f5aa624eac1d23": {...},
add: function(){},
remove: function(){},
save: function(){},
load: function(){},
clear: function(){},
length: 2,
}
wallet.create¶
web3.pi.accounts.wallet.create(numberOfAccounts [, entropy]);
Generates one or more accounts in the wallet. If wallets already exist they will not be overridden.
Parameters¶
numberOfAccounts
-Number
: Number of accounts to create. Leave empty to create an empty wallet.entropy
-String
(optional): A string with random characters as additional entropy when generating accounts. If given it should be at least 32 characters.
Returns¶
Object
: The wallet object.
Example¶
web3.pi.accounts.wallet.create(2, '54674321§3456764321§345674321§3453647544±±±§±±±!!!43534534534534');
> Wallet {
0: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
"0xf0109fc8df283027b6285cc889f5aa624eac1f55": {...},
...
}
wallet.add¶
web3.pi.accounts.wallet.add(account);
Adds an account using a private key or account object to the wallet.
Parameters¶
account
-String|Object
: A private key or account object created with web3.pi.accounts.create().
Returns¶
Object
: The added account.
Example¶
web3.pi.accounts.wallet.add('0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318');
> {
index: 0,
address: '0x2c7536E3605D9C16a7a3D7b1898e529396a65c23',
privateKey: '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318',
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
web3.pi.accounts.wallet.add({
privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01'
});
> {
index: 0,
address: '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01',
privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709',
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
wallet.remove¶
web3.pi.accounts.wallet.remove(account);
Removes an account from the wallet.
Parameters¶
account
-String|Number
: The account address, or index in the wallet.
Returns¶
Boolean
: true
if the wallet was removed. false
if it couldn’t be found.
Example¶
web3.pi.accounts.wallet;
> Wallet {
0: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...}
1: {...},
"0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01": {...}
...
}
web3.pi.accounts.wallet.remove('0xF0109fC8DF283027b6285cc889F5aA624EaC1F55');
> true
web3.pi.accounts.wallet.remove(3);
> false
wallet.clear¶
web3.pi.accounts.wallet.clear();
Securely empties the wallet and removes all its accounts.
Parameters¶
none
Returns¶
Object
: The wallet object.
Example¶
web3.pi.accounts.wallet.clear();
> Wallet {
add: function(){},
remove: function(){},
save: function(){},
load: function(){},
clear: function(){},
length: 0
}
wallet.encrypt¶
web3.pi.accounts.wallet.encrypt(password);
Encrypts all wallet accounts to an array of encrypted keystore v3 objects.
Parameters¶
password
-String
: The password which will be used for encryption.
Returns¶
Array
: The encrypted keystore v3.
Example¶
web3.pi.accounts.wallet.encrypt('test');
> [ { version: 3,
id: 'dcf8ab05-a314-4e37-b972-bf9b86f91372',
address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
crypto:
{ ciphertext: '0de804dc63940820f6b3334e5a4bfc8214e27fb30bb7e9b7b74b25cd7eb5c604',
cipherparams: [Object],
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams: [Object],
mac: 'b2aac1485bd6ee1928665642bf8eae9ddfbc039c3a673658933d320bac6952e3' } },
{ version: 3,
id: '9e1c7d24-b919-4428-b10e-0f3ef79f7cf0',
address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
crypto:
{ ciphertext: 'd705ebed2a136d9e4db7e5ae70ed1f69d6a57370d5fbe06281eb07615f404410',
cipherparams: [Object],
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams: [Object],
mac: 'af9eca5eb01b0f70e909f824f0e7cdb90c350a802f04a9f6afe056602b92272b' } }
]
wallet.decrypt¶
web3.pi.accounts.wallet.decrypt(keystoreArray, password);
Decrypts keystore v3 objects.
Parameters¶
keystoreArray
-Array
: The encrypted keystore v3 objects to decrypt.password
-String
: The password which will be used for encryption.
Returns¶
Object
: The wallet object.
Example¶
web3.pi.accounts.wallet.decrypt([
{ version: 3,
id: '83191a81-aaca-451f-b63d-0c5f3b849289',
address: '06f702337909c06c82b09b7a22f0a2f0855d1f68',
crypto:
{ ciphertext: '7d34deae112841fba86e3e6cf08f5398dda323a8e4d29332621534e2c4069e8d',
cipherparams: { iv: '497f4d26997a84d570778eae874b2333' },
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams:
{ dklen: 32,
salt: '208dd732a27aa4803bb760228dff18515d5313fd085bbce60594a3919ae2d88d',
n: 262144,
r: 8,
p: 1 },
mac: '0062a853de302513c57bfe3108ab493733034bf3cb313326f42cf26ea2619cf9' } },
{ version: 3,
id: '7d6b91fa-3611-407b-b16b-396efb28f97e',
address: 'b5d89661b59a9af0b34f58d19138baa2de48baaf',
crypto:
{ ciphertext: 'cb9712d1982ff89f571fa5dbef447f14b7e5f142232bd2a913aac833730eeb43',
cipherparams: { iv: '8cccb91cb84e435437f7282ec2ffd2db' },
cipher: 'aes-128-ctr',
kdf: 'scrypt',
kdfparams:
{ dklen: 32,
salt: '08ba6736363c5586434cd5b895e6fe41ea7db4785bd9b901dedce77a1514e8b8',
n: 262144,
r: 8,
p: 1 },
mac: 'd2eb068b37e2df55f56fa97a2bf4f55e072bef0dd703bfd917717d9dc54510f0' } }
], 'test');
> Wallet {
0: {...},
1: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
"0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...}
...
}
wallet.save¶
web3.pi.accounts.wallet.save(password [, keyName]);
Stores the wallet encrypted and as string in local storage.
Note
Browser only.
Parameters¶
password
-String
: The password to encrypt the wallet.keyName
-String
: (optional) The key used for the local storage position, defaults to"web3js_wallet"
.
Returns¶
Boolean
Example¶
web3.pi.accounts.wallet.save('test#!$');
> true
wallet.load¶
web3.pi.accounts.wallet.load(password [, keyName]);
Loads a wallet from local storage and decrypts it.
Note
Browser only.
Parameters¶
password
-String
: The password to decrypt the wallet.keyName
-String
: (optional) The key used for the localstorage position, defaults to"web3js_wallet"
.
Returns¶
Object
: The wallet object.
Example¶
web3.pi.accounts.wallet.load('test#!$', 'myWalletKey');
> Wallet {
0: {...},
1: {...},
"0xF0109fC8DF283027b6285cc889F5aA624EaC1F55": {...},
"0xD0122fC8DF283027b6285cc889F5aA624EaC1d23": {...}
...
}
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.personal¶
The web3-pi-personal
package allows you to interact with the Pchain node’s accounts.
Note
Many of these functions send sensitive information, like password. Never call these functions over a unsecured Websocket or HTTP provider, as your password will be sent in plain text!
import Web3 from 'pweb3';
import {Personal} from 'web3-pi-personal';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const personal = new Personal(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// or using the web3 umbrella package
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// -> web3.pi.personal
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
newAccount¶
web3.pi.personal.newAccount(password, [callback])
Create a new account on the node that Web3 is connected to with its provider.
The RPC method used is personal_newAccount
. It differs from
web3.pi.accounts.create() where the key pair is
created only on client and it’s up to the developer to manage it.
Note
Never call this function over a unsecured Websocket or HTTP provider, as your password will be send in plain text!
Parameters¶
password
-String
: The password to encrypt this account with.
Returns¶
Promise<string>
- The address of the newly created account.
Example¶
web3.pi.personal.newAccount('!@superpassword')
.then(console.log);
> '0x1234567891011121314151617181920212223456'
sign¶
web3.pi.personal.sign(dataToSign, address, password [, callback])
Signs data using a specific account. This data is before UTF-8 HEX decoded and enveloped as follows: "\x19Pchain Signed Message:\n" + message.length + message
.
Note
Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
Parameters¶
String
- Data to sign. If String it will be converted using web3.utils.utf8ToHex.String
- Address to sign data with.String
- The password of the account to sign data with.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The signature.
Example¶
web3.pi.personal.sign("Hello world", "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
// the below is the same
web3.pi.personal.sign(web3.utils.utf8ToHex("Hello world"), "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
ecRecover¶
web3.pi.personal.ecRecover(dataThatWasSigned, signature [, callback])
Recovers the account that signed the data.
Parameters¶
String
- Data that was signed. If String it will be converted using web3.utils.utf8ToHex.String
- The signature.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The account.
Example¶
web3.pi.personal.ecRecover("Hello world", "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400").then(console.log);
> "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe"
signTransaction¶
web3.pi.personal.signTransaction(transaction, password [, callback])
Signs a transaction. This account needs to be unlocked.
Note
Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
Parameters¶
Object
- The transaction data to sign web3.pi.sendTransaction() for more.String
- The password of thefrom
account, to sign the transaction with.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- The RLP encoded transaction. The raw
property can be used to send the transaction using web3.pi.sendSignedTransaction.
Example¶
web3.pi.signTransaction({
from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
gasPrice: "20000000000",
gas: "21000",
to: '0x3535353535353535353535353535353535353535',
value: "1000000000000000000",
data: ""
}, 'MyPassword!').then(console.log);
> {
raw: '0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88da07e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
tx: {
nonce: '0x0',
gasPrice: '0x4a817c800',
gas: '0x5208',
to: '0x3535353535353535353535353535353535353535',
value: '0xde0b6b3a7640000',
input: '0x',
v: '0x25',
r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
}
}
sendTransaction¶
web3.pi.personal.sendTransaction(transactionOptions, password [, callback])
This method sends a transaction over the management API.
Note
Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
Parameters¶
Object
- The transaction optionsString
- The passphrase for the current accountFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The transaction hash.
Example¶
web3.pi.sendTransaction({
from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
gasPrice: "20000000000",
gas: "21000",
to: '0x3535353535353535353535353535353535353535',
value: "1000000000000000000",
data: ""
}, 'MyPassword!').then(console.log);
> '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
unlockAccount¶
web3.pi.personal.unlockAccount(address, password, unlockDuraction [, callback])
Unlocks the given account.
Note
Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
Parameters¶
address
-String
: The account address.password
-String
- The password of the account.unlockDuration
-Number
- The duration for the account to remain unlocked.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if the account got unlocked successful otherwise false.
Example¶
web3.pi.personal.unlockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "test password!", 600)
.then(console.log('Account unlocked!'));
> "Account unlocked!"
lockAccount¶
web3.pi.personal.lockAccount(address [, callback])
Locks the given account.
Note
Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
Parameters¶
1. address
- String
: The account address.
4. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
Example¶
web3.pi.personal.lockAccount("0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe")
.then(console.log('Account locked!'));
> "Account locked!"
getAccounts¶
web3.pi.personal.getAccounts([callback])
Returns a list of accounts the node controls by using the provider and calling
the RPC method personal_listAccounts
. Using web3.pi.accounts.create()
will not add accounts into this list. For that use
web3.pi.personal.newAccount().
The results are the same as web3.pi.getAccounts() except that calls
the RPC method pi_accounts
.
Returns¶
Promise<Array>
- An array of addresses controlled by node.
Example¶
web3.pi.personal.getAccounts()
.then(console.log);
> ["0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe", "0xDCc6960376d6C6dEa93647383FfB245CfCed97Cf"]
importRawKey¶
web3.pi.personal.importRawKey(privateKey, password)
Imports the given private key into the key store, encrypting it with the passphrase.
Returns the address of the new account.
Note
Sending your account password over an unsecured HTTP RPC connection is highly unsecure.
Parameters¶
privateKey
-String
- An unencrypted private key (hex string).password
-String
- The password of the account.
Returns¶
Promise<string>
- The address of the account.
Example¶
web3.pi.personal.importRawKey("cd3376bb711cb332ee3fb2ca04c6a8b9f70c316fcdf7a1f44ef4c7999483295e", "password1234")
.then(console.log);
> "0x8f337bf484b2fc75e4b0436645dcc226ee2ac531"
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.ens¶
The web3.pi.ens
functions let you interacting with the Ens smart contracts.
import Web3 from 'pweb3';
import {Ens} from 'web3-pi-ens';
import {Accounts} from 'web3-pi-accounts';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const pi = new Ens(
Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain',
null,
options
new Accounts(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options)
);
// or using the web3 umbrella package
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// -> web3.pi.ens
registry¶
web3.pi.ens.registry;
Returns the network specific Ens registry.
Returns¶
Registry
- The current Ens registry.
Example¶
web3.pi.ens.registry;
> {
ens: Ens,
resolverContract: Contract | null,
setProvider(provider: provider, net?: net.Socket): boolean,
owner(name: string, callback?: (error: Error, address: string) => void): Promise<string>,
resolver(name: string): Promise<Contract>,
checkNetwork(): Promise<string>,
}
resolver¶
web3.pi.ens.resolver(name);
Returns the resolver contract to an Pchain address.
Returns¶
Resolver
- The Ens resolver for this name.
Example¶
web3.pi.ens.resolver('pchain.pi').then((contract) => {
console.log(contract);
});
> Contract<Resolver>
supportsInterface¶
web3.pi.ens.supportsInterface(ENSName, interfaceId, [callback]);
Checks if the current resolver does support the desired interface.
Parameters¶
ENSName
-String
: The Ens name to resolve.interfaceId
-String
: A defined ENS interfaceId.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true if the given interfaceId is supported by the resolver.
Example¶
web3.pi.ens.supportsInterface('pchain.pi', '0xbc1c58d1').then((supportsInterface) => {
console.log(supportsInterface);
})
> true
getAddress¶
web3.pi.ens.getAddress(ENSName, [callback]);
Resolves an Ens name to an Pchain address.
Parameters¶
ENSName
-String
: The Ens name to resolve.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The Pchain address of the given name.
Example¶
web3.pi.ens.getAddress('pchain.pi').then((address) => {
console.log(address);
})
> 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359
setAddress¶
web3.pi.ens.setAddress(ENSName, address, options, [callback]);
Sets the address of an Ens name in his resolver.
Parameters¶
ENSName
-String
: The Ens name.address
-String
: The address to set.options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Emits an AddrChanged
event.
Example¶
web3.pi.ens.setAddress(
'pchain.pi',
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then((result) => {
console.log(result.events);
});
> AddrChanged(...)
// Or using the event emitter
web3.pi.ens.setAddress(
'pchain.pi',
'0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('error', console.error);
// Or listen to the AddrChanged event on the resolver
web3.pi.ens.resolver('pchain.pi').then((resolver) => {
resolver.events.AddrChanged({fromBlock: 0}, (error, event) => {
console.log(event);
})
.on('data', (event) => {
console.log(event);
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here contract-events_.
getPubkey¶
web3.pi.ens.getPubkey(ENSName, [callback]);
Returns the X and Y coordinates of the curve point for the public key.
Parameters¶
ENSName
-String
: The Ens name.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Object<String, String>
- The X and Y coordinates.
Example¶
web3.pi.ens.getPubkey('pchain.pi').then((result) => {
console.log(result)
});
> {
"0": "0x0000000000000000000000000000000000000000000000000000000000000000",
"1": "0x0000000000000000000000000000000000000000000000000000000000000000",
"x": "0x0000000000000000000000000000000000000000000000000000000000000000",
"y": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
setPubkey¶
web3.pi.ens.setPubkey(ENSName, x, y, options, [callback]);
Sets the SECP256k1 public key associated with an Ens node
Parameters¶
ENSName
-String
: The Ens name.x
-String
: The X coordinate of the public key.y
-String
: The Y coordinate of the public key.options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Emits an PubkeyChanged
event.
Example¶
web3.pi.ens.setPubkey(
'pchain.pi',
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then((result) => {
console.log(result.events);
});
> PubkeyChanged(...)
// Or using the event emitter
web3.pi.ens.setPubkey(
'pchain.pi',
'0x0000000000000000000000000000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('error', console.error);
// Or listen to the PubkeyChanged event on the resolver
web3.pi.ens.resolver('pchain.pi').then((resolver) => {
resolver.events.PubkeyChanged({fromBlock: 0}, function(error, event) {
console.log(event);
})
.on('data', (event) => {
console.log(event);
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here contract-events_.
getText¶
web3.pi.ens.getText(ENSName, key, [callback]);
Returns the text by the given key.
Parameters¶
ENSName
-String
: The Ens name.key
-String
: The key of the array.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
Example¶
web3.pi.ens.getText('pchain.pi', 'key').then((result) => {
console.log(result);
});
> "0000000000000000000000000000000000000000000000000000000000000000"
setText¶
web3.pi.ens.setText(ENSName, key, value, options, [callback]);
Sets the content hash associated with an Ens node.
Parameters¶
ENSName
-String
: The Ens name.
2. key
- String
: The key.
2. value
- String
: The value.
3. options
- Object
: The options used for sending.
from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Emits an TextChanged
event.
Example¶
web3.pi.ens.setText(
'pchain.pi',
'key',
'value',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then((result) => {
console.log(result.events);
});
> ContentChanged(...)
// Or using the event emitter
web3.pi.ens.setText(
'pchain.pi',
'key',
'value',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('error', console.error);
// And listen to the TextChanged event on the resolver
web3.pi.ens.resolver('pchain.pi').then((resolver) => {
resolver.events.TextChanged({fromBlock: 0}, (error, event) => {
console.log(event);
})
.on('data', (event) => {
console.log(event);
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here contract-events_.
getContent¶
web3.pi.ens.getContent(ENSName, [callback]);
Returns the content hash associated with an Ens node.
Parameters¶
ENSName
-String
: The Ens name.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The content hash associated with an Ens node.
Example¶
web3.pi.ens.getContent('pchain.pi').then((result) => {
console.log(result);
});
> "0x0000000000000000000000000000000000000000000000000000000000000000"
setContent¶
web3.pi.ens.setContent(ENSName, hash, options, [callback]);
Sets the content hash associated with an Ens node.
Parameters¶
ENSName
-String
: The Ens name.hash
-String
: The content hash to set.options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Emits an ContentChanged
event.
Example¶
web3.pi.ens.setContent(
'pchain.pi',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then((result) => {
console.log(result.events);
});
> ContentChanged(...)
// Or using the event emitter
web3.pi.ens.setContent(
'pchain.pi',
'0x0000000000000000000000000000000000000000000000000000000000000000',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('error', console.error);
// Or listen to the ContentChanged event on the resolver
web3.pi.ens.resolver('pchain.pi').then((resolver) => {
resolver.events.ContentChanged({fromBlock: 0}, (error, event) => {
console.log(event);
})
.on('data', (event) => {
console.log(event);
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
});
For further information on the handling of contract events please see here contract-events_.
getMultihash¶
web3.pi.ens.getMultihash(ENSName, [callback]);
Returns the multihash associated with an Ens node.
Parameters¶
ENSName
-String
: The Ens name.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The associated multihash.
Example¶
web3.pi.ens.getMultihash('pchain.pi').then((result) => {
console.log(result);
});
> 'QmXpSwxdmgWaYrgMUzuDWCnjsZo5RxphE3oW7VhTMSCoKK'
setMultihash¶
web3.pi.ens.setMultihash(ENSName, hash, options, [callback]);
Sets the multihash associated with an Ens node.
Parameters¶
ENSName
-String
: The Ens name.hash
-String
: The multihash to set.options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Emits an ``MultihashChanged``event.
Example¶
web3.pi.ens.setMultihash(
'pchain',
'QmXpSwxdmgWaYrgMUzuDWCnjsZo5RxphE3oW7VhTMSCoKK',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then((result) => {
console.log(result.events);
});
> MultihashChanged(...)
// Or using the event emitter
web3.pi.ens.setMultihash(
'pchain.pi',
'QmXpSwxdmgWaYrgMUzuDWCnjsZo5RxphE3oW7VhTMSCoKK',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('error', console.error);
For further information on the handling of contract events please see here contract-events_.
getContenthash¶
web3.pi.ens.getContenthash(ENSName, [callback]);
Returns the contenthash associated with an Ens node. contenthash encoding is defined in [EIP1577](http://eips.ethereum.org/EIPS/eip-1577)
Parameters¶
ENSName
-String
: The Ens name.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The associated contenthash.
Example¶
web3.pi.ens.getContenthash('pac-txt.pi').then((result) => {
console.log(result);
});
> '0xe30101701220e08ea2458249e8f26aee72b95b39c33849a992a3eff40bd06d26c12197adef16'
setContenthash¶
web3.pi.ens.setContenthash(ENSName, hash, options, [callback]);
Sets the contenthash associated with an Ens node.
Parameters¶
ENSName
-String
: The Ens name.hash
-String
: The contenthash to set.options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
(optional): The gas price in wei to use for this transaction.gas
-Number
(optional): The maximum gas provided for this transaction (gas limit).
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Emits an ContenthashChanged
event.
Example¶
web3.pi.ens.setContenthash(
'pchain',
'0xe301017012208cd82588c4e08268fa0b824caa93847ac843410076eeedc41d65fb52eccbb9e6',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
).then((result) => {
console.log(result.events);
});
> ContenthashChanged(...)
// Or using the event emitter
web3.pi.ens.setContenthash(
'pchain.pi',
'0xe301017012208cd82588c4e08268fa0b824caa93847ac843410076eeedc41d65fb52eccbb9e6',
{
from: '0x9CC9a2c777605Af16872E0997b3Aeb91d96D5D8c'
}
)
.on('transactionHash', (hash) => {
...
})
.on('confirmation', (confirmationNumber, receipt) => {
...
})
.on('receipt', (receipt) => {
...
})
.on('error', console.error);
For further information on the handling of contract events please see here contract-events_.
Ens events¶
The Ens API provides the possibility for listening to all Ens related events.
Known resolver events¶
AddrChanged
- AddrChanged(node bytes32, a address)ContentChanged
- ContentChanged(node bytes32, hash bytes32)NameChanged
- NameChanged(node bytes32, name string)ABIChanged
- ABIChanged(node bytes32, contentType uint256)PubkeyChanged
- PubkeyChanged(node bytes32, x bytes32, y bytes32)TextChanged
- TextChanged(bytes32 indexed node, string indexedKey, string key)ContenthashChanged
- ContenthashChanged(bytes32 indexed node, bytes hash)
Example¶
web3.pi.ens.resolver('pchain.pi').then((resolver) => {
resolver.events.AddrChanged({fromBlock: 0}, (error, event) => {
console.log(event);
})
.on('data', (event) => {
console.log(event);
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
});
> {
returnValues: {
node: '0x123456789...',
a: '0x123456789...',
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: [
'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'
]
},
event: 'AddrChanged',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
Known registry events¶
Transfer
- Transfer(node bytes32, owner address)
2. NewOwner
- NewOwner(node bytes32, label bytes32, owner address)
4. NewResolver
- NewResolver(node bytes32, resolver address)
5. NewTTL
- NewTTL(node bytes32, ttl uint64)
Example¶
web3.pi.ens.resistry.then((registry) => {
registry.events.Transfer({fromBlock: 0}, (error, event) => {
console.log(event);
})
.on('data', (event) => {
console.log(event);
})
.on('changed', (event) => {
// remove event from local database
})
.on('error', console.error);
});
> {
returnValues: {
node: '0x123456789...',
owner: '0x123456789...',
},
raw: {
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: [
'0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
'0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385'
]
},
event: 'Transfer',
signature: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'
}
For further information on the handling of contract events please see here contract-events_.
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.Iban¶
The web3.pi.Iban
function lets convert Pchain addresses from and to IBAN and BBAN.
import {Iban} from 'web3-pi-iban';
const iban = new Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS');
// or using the web3 umbrella package
import Web3 from 'pweb3';
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// -> new web3.pi.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS')
toAddress¶
static function
web3.pi.Iban.toAddress(ibanAddress)
Singleton: Converts a direct IBAN address into an Pchain address.
Note
This method also exists on the IBAN instance.
Parameters¶
String
: the IBAN address to convert.
Returns¶
String
- The Pchain address.
Example¶
web3.pi.Iban.toAddress("XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS");
> "0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8"
toIban¶
static function
web3.pi.Iban.toIban(address)
Singleton: Converts an Pchain address to a direct IBAN address.
Parameters¶
String
: the Pchain address to convert.
Returns¶
String
- The IBAN address.
Example¶
web3.pi.Iban.toIban("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8");
> "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"
static function, return IBAN instance
fromAddress¶
web3.pi.Iban.fromAddress(address)
Singleton: Converts an Pchain address to a direct IBAN instance.
Parameters¶
String
: the Pchain address to convert.
Returns¶
Object
- The IBAN instance.
Example¶
web3.pi.Iban.fromAddress("0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8");
> Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"}
static function, return IBAN instance
fromBban¶
web3.pi.Iban.fromBban(bbanAddress)
Singleton: Converts an BBAN address to a direct IBAN instance.
Parameters¶
String
: the BBAN address to convert.
Returns¶
Object
- The IBAN instance.
Example¶
web3.pi.Iban.fromBban('ETHXREGGAVOFYORK');
> Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"}
static function, return IBAN instance
createIndirect¶
web3.pi.Iban.createIndirect(options)
Singleton: Creates an indirect IBAN address from a institution and identifier.
Parameters¶
Object
: the options object as follows:institution
-String
: the institution to be assignedidentifier
-String
: the identifier to be assigned
Returns¶
Object
- The IBAN instance.
Example¶
web3.pi.Iban.createIndirect({
institution: "XREG",
identifier: "GAVOFYORK"
});
> Iban {_iban: "XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS"}
static function, return boolean
isValid¶
web3.pi.Iban.isValid(ibanAddress)
Singleton: Checks if an IBAN address is valid.
Note
This method also exists on the IBAN instance.
Parameters¶
String
: the IBAN address to check.
Returns¶
Boolean
Example¶
web3.pi.Iban.isValid("XE81ETHXREGGAVOFYORK");
> true
web3.pi.Iban.isValid("XE82ETHXREGGAVOFYORK");
> false // because the checksum is incorrect
prototype.isValid¶
method of Iban instance
web3.pi.Iban.prototype.isValid()
Singleton: Checks if an IBAN address is valid.
Note
This method also exists on the IBAN instance.
Parameters¶
String
: the IBAN address to check.
Returns¶
Boolean
Example¶
const iban = new web3.pi.Iban("XE81ETHXREGGAVOFYORK");
iban.isValid();
> true
prototype.isDirect¶
method of Iban instance
web3.pi.Iban.prototype.isDirect()
Checks if the IBAN instance is direct.
Returns¶
Boolean
Example¶
const iban = new web3.pi.Iban("XE81ETHXREGGAVOFYORK");
iban.isDirect();
> false
prototype.isIndirect¶
method of Iban instance
web3.pi.Iban.prototype.isIndirect()
Checks if the IBAN instance is indirect.
Returns¶
Boolean
Example¶
const iban = new web3.pi.Iban("XE81ETHXREGGAVOFYORK");
iban.isIndirect();
> true
prototype.checksum¶
method of Iban instance
web3.pi.Iban.prototype.checksum()
Returns the checksum of the IBAN instance.
Returns¶
String
: The checksum of the IBAN
Example¶
const iban = new web3.pi.Iban("XE81ETHXREGGAVOFYORK");
iban.checksum();
> "81"
prototype.institution¶
method of Iban instance
web3.pi.Iban.prototype.institution()
Returns the institution of the IBAN instance.
Returns¶
String
: The institution of the IBAN
Example¶
const iban = new web3.pi.Iban("XE81ETHXREGGAVOFYORK");
iban.institution();
> 'XREG'
prototype.client¶
method of Iban instance
web3.pi.Iban.prototype.client()
Returns the client of the IBAN instance.
Returns¶
String
: The client of the IBAN
Example¶
const iban = new web3.pi.Iban("XE81ETHXREGGAVOFYORK");
iban.client();
> 'GAVOFYORK'
prototype.toAddress¶
method of Iban instance
web3.pi.Iban.prototype.toString()
Returns the Pchain address of the IBAN instance.
Returns¶
String
: The Pchain address of the IBAN
Example¶
const iban = new web3.pi.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS');
iban.toAddress();
> '0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8'
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.net¶
Functions to receive details about the current connected network.
getId¶
web3.pi.net.getId([callback])
web3.shh.net.getId([callback])
Gets the current network ID.
Parameters¶
none
Returns¶
Promise
returns Number
: The network ID.
Example¶
web3.pi.net.getId().then(console.log);
> 1
isListening¶
web3.pi.net.isListening([callback])
web3.shh.net.isListening([callback])
Checks if the node is listening for peers.
Parameters¶
none
Returns¶
Promise
returns Boolean
Example¶
web3.pi.isListening().then(console.log);
> true
getPeerCount¶
web3.pi.net.getPeerCount([callback])
web3.shh.net.getPeerCount([callback])
Get the number of peers connected to.
Parameters¶
none
Returns¶
Promise
returns Number
Example¶
web3.pi.getPeerCount().then(console.log);
> 25
getNetworkType¶
web3.pi.net.getNetworkType([callback])
Guesses the chain the node is connected by comparing the genesis hashes.
Note
It’s recommended to use the web3.pi.getChainId method to detect the currently connected chain.
Returns¶
Promise
returnsString
:"main"
for main network"morden"
for the morden test network"rinkeby"
for the rinkeby test network"ropsten"
for the ropsten test network"kovan"
for the kovan test network"private"
for undetectable networks.
Example¶
web3.pi.net.getNetworkType().then(console.log);
> "main"
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.pi.abi¶
The web3-pi-abi
package allows you to de- and encode parameters from a ABI (Application Binary Interface).
This will be used for calling functions of a deployed smart-contract.
import {AbiCoder} from 'web3-pi-abi';
const abiCoder = new AbiCoder();
// or using the web3 umbrella package
import Web3 from 'pweb3';
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// -> web3.pi.abi
encodeFunctionSignature¶
web3.pi.abi.encodeFunctionSignature(functionName);
Encodes the function name to its ABI signature, which are the first 4 bytes of the sha3 hash of the function name including types.
Parameters¶
1. functionName
- String|Object
: The function name to encode.
or the JSON interface object of the function. If string it has to be in the form function(type,type,...)
, e.g: myFunction(uint256,uint32[],bytes10,bytes)
Returns¶
String
- The ABI signature of the function.
Example¶
// From a JSON interface object
web3.pi.abi.encodeFunctionSignature({
name: 'myMethod',
type: 'function',
inputs: [{
type: 'uint256',
name: 'myNumber'
},{
type: 'string',
name: 'myString'
}]
})
> 0x24ee0097
// Or string
web3.pi.abi.encodeFunctionSignature('myMethod(uint256,string)')
> '0x24ee0097'
encodeEventSignature¶
web3.pi.abi.encodeEventSignature(eventName);
Encodes the event name to its ABI signature, which are the sha3 hash of the event name including input types.
Parameters¶
1. eventName
- String|Object
: The event name to encode.
or the JSON interface object of the event. If string it has to be in the form event(type,type,...)
, e.g: myEvent(uint256,uint32[],bytes10,bytes)
Returns¶
String
- The ABI signature of the event.
Example¶
web3.pi.abi.encodeEventSignature('myEvent(uint256,bytes32)')
> 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97
// or from a json interface object
web3.pi.abi.encodeEventSignature({
name: 'myEvent',
type: 'event',
inputs: [{
type: 'uint256',
name: 'myNumber'
},{
type: 'bytes32',
name: 'myBytes'
}]
})
> 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97
encodeParameter¶
web3.pi.abi.encodeParameter(type, parameter);
Encodes a parameter based on its type to its ABI representation.
Parameters¶
type
-String|Object
: The type of the parameter, see the solidity documentation for a list of types.parameter
-Mixed
: The actual parameter to encode.
Returns¶
String
- The ABI encoded parameter.
Example¶
web3.pi.abi.encodeParameter('uint256', '2345675643');
> "0x000000000000000000000000000000000000000000000000000000008bd02b7b"
web3.pi.abi.encodeParameter('uint256', '2345675643');
> "0x000000000000000000000000000000000000000000000000000000008bd02b7b"
web3.pi.abi.encodeParameter('bytes32', '0xdf3234');
> "0xdf32340000000000000000000000000000000000000000000000000000000000"
web3.pi.abi.encodeParameter('bytes', '0xdf3234');
> "0x00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003df32340000000000000000000000000000000000000000000000000000000000"
web3.pi.abi.encodeParameter('bytes32[]', ['0xdf3234', '0xfdfd']);
> "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002df32340000000000000000000000000000000000000000000000000000000000fdfd000000000000000000000000000000000000000000000000000000000000"
encodeParameters¶
web3.pi.abi.encodeParameters(typesArray, parameters);
Encodes a function parameters based on its JSON interface object.
Parameters¶
typesArray
-Array<String|Object>|Object
: An array with types or a JSON interface of a function. See the solidity documentation for a list of types.parameters
-Array
: The parameters to encode.
Returns¶
String
- The ABI encoded parameters.
Example¶
web3.pi.abi.encodeParameters(['uint256','string'], ['2345675643', 'Hello!%']);
> "0x000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000"
web3.pi.abi.encodeParameters(['uint8[]','bytes32'], [['34','434'], '0x324567fff']);
> "0x0"
encodeFunctionCall¶
web3.pi.abi.encodeFunctionCall(jsonInterface, parameters);
Encodes a function call using its JSON interface object and given parameters.
Parameters¶
jsonInterface
-Object
: The JSON interface object of a function.parameters
-Array
: The parameters to encode.
Returns¶
String
- The ABI encoded function call. Means function signature + parameters.
Example¶
web3.pi.abi.encodeFunctionCall({
name: 'myMethod',
type: 'function',
inputs: [{
type: 'uint256',
name: 'myNumber'
},{
type: 'string',
name: 'myString'
}]
}, ['2345675643', 'Hello!%']);
> "0x24ee0097000000000000000000000000000000000000000000000000000000008bd02b7b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000748656c6c6f212500000000000000000000000000000000000000000000000000"
decodeParameter¶
web3.pi.abi.decodeParameter(type, hexString);
Decodes an ABI encoded parameter to its JavaScript type.
Parameters¶
type
-String|Object
: The type of the parameter, see the solidity documentation for a list of types.hexString
-String
: The ABI byte code to decode.
Returns¶
Mixed
- The decoded parameter.
Example¶
web3.pi.abi.decodeParameter('uint256', '0x0000000000000000000000000000000000000000000000000000000000000010');
> "16"
web3.pi.abi.decodeParameter('string', '0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000');
> "Hello!%!"
web3.pi.abi.decodeParameter('string', '0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000');
> "Hello!%!"
decodeParameters¶
web3.pi.abi.decodeParameters(typesArray, hexString);
Decodes ABI encoded parameters to its JavaScript types.
Parameters¶
typesArray
-Array<String|Object>|Object
: An array with types or a JSON interface outputs array. See the solidity documentation for a list of types.hexString
-String
: The ABI byte code to decode.
Returns¶
Object
- The result object containing the decoded parameters.
Example¶
web3.pi.abi.decodeParameters(['string', 'uint256'], '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000');
> Result { '0': 'Hello!%!', '1': '234' }
web3.pi.abi.decodeParameters([{
type: 'string',
name: 'myString'
},{
type: 'uint256',
name: 'myNumber'
}], '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000ea000000000000000000000000000000000000000000000000000000000000000848656c6c6f212521000000000000000000000000000000000000000000000000');
> Result {
'0': 'Hello!%!',
'1': '234',
myString: 'Hello!%!',
myNumber: '234'
}
decodeLog¶
web3.pi.abi.decodeLog(inputs, hexString, topics);
Decodes ABI encoded log data and indexed topic data.
Parameters¶
inputs
-Array
: A JSON interface inputs array. See the solidity documentation for a list of types.hexString
-String
: The ABI byte code in thedata
field of a log.topics
-Array
: An array with the index parameter topics of the log, without the topic[0] if its a non-anonymous event, otherwise with topic[0].
Returns¶
Object
- The result object containing the decoded parameters.
Example¶
web3.pi.abi.decodeLog([{
type: 'string',
name: 'myString'
},{
type: 'uint256',
name: 'myNumber',
indexed: true
},{
type: 'uint8',
name: 'mySmallNumber',
indexed: true
}],
'0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000',
['0x000000000000000000000000000000000000000000000000000000000000f310', '0x0000000000000000000000000000000000000000000000000000000000000010']);
> Result {
'0': 'Hello%!',
'1': '62224',
'2': '16',
myString: 'Hello%!',
myNumber: '62224',
mySmallNumber: '16'
}
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.chain¶
The web3-chain
package allows you to interact with the Pchain nodes chain properties.
createChildChain¶
web3.chain.createChildChain(from,chainId,minValidators,minDepositAmount,startBlock,endBlock,gasPrice [, callback])
Send an application of Child Chain Creation, save the application into the ChainInfo DB.
Parameters¶
from
- address - the address who triggers the actionchainId
- string - child chain idminValidators
- hex string - Minimum Validators of the new Child ChainminDepositAmount
- hex string - Minimum Deposit PAI of the new Child ChainstartBlock
- hex string - Start Block height for launch child chainendBlock
- hex string - End Block height for launch child chaingasPrice
- hex string - ( if set to null,system will give default value(1 gwei) ) gas price from the request
Returns¶
String - The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0xa349d8a4e35f0c922377168daae653b5c9f1d370";
var chainId = "pchain-child-1";
var minValidators = "0x1";
var minDepositAmount = "0x152D02C7E14AF6800000";
var gas = "0x32":
var gasPrice = "0x7D0";
web3.chain.createChildChain(from,chainId,minValidators,minDepositAmount,startBlock,endBlock,gas,gasPrice, function(err, hash) {
if (!err)
console.log(hash);
});
joinChildChain¶
web3.chain.joinChildChain(from,pubkey,chainId,depositAmount,signature,gasPrice [, callback])
Send a request to Join the child chain, save the Join Application into the ChainInfo DB, after the blockchain match the criteria of the child chain, chainMgr will load the Child Chain Data from ChainInfo DB then start it.
Parameters¶
from
- address, 20 Bytes - the address who triggers the actionpubkey
- hex string, 128 Bytes - the BLS Public Key who triggers the actionchainId
- string - child chain iddepositAmount
- hex string - Amount of the Deposit PAI to join the Child Chainsignature
- hex string, 64 Bytes - the signature of From Address, signed by BLS Private Key. (How to sign, see web3.chain.signAddress)gasPrice
- hex string - ( if set to null,system will give default value(1 gwei) ) gas price from the request
Returns¶
String - The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0x5CE010Bf008Ba976Dd80Ed968a2f916190Cf9b4f";
var pubkey = "5CCB45F727A7075C9336DF357A3610DD884FD97E64FFB51EED30890B8B3519E36D1C211A7BC1335C09CE654779328F1D01D997C1B2C5F9D196AD67FA5AF7A00273CED363C50D8F12B4EA096AFB859D6311C63C910752D41C0532C2D2654DCA863F7D56B2B9C33E0E7A5A0349F6B4FC20AE15526C5463F11D76FA92AB183ECEBE";
var chainId = "pchain-child-1";
var depositAmount = "0x152D02C7E14AF6800000";
var signature = "0x6e5ea219800849592e67f76d45742a29c42a20b0b9d853facf32ac788591869e3db50a10770d88b93f24d2f6efed8acd220bce6442db7a2fbadfdada2d2cde73";
var gasPrice = "0x7D0";
web3.chain.joinChildChain(from,pubkey,chainId,depositAmount,signature,gasPrice, function(err, hash) {
if (!err)
console.log(hash);
});
depositInMainChain¶
web3.chain.depositInMainChain(from,chainId,amount,gasPrice [, callback])
Parameters¶
from
- address, 20 Bytes - the address who triggers the actionchainId
- string - child chain idamount
- hex string - amount of PAI to depositgasPrice
- hex string - ( if set to null,system will give default value(1 gwei) ) gas price from the request
Returns¶
String - The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var chainId = "pchain-child-1";
var amount = "0x152D02C7E14AF6800000";
var gasPrice = "0x2540be400";
web3.chain.depositInMainChain(from,chainId,amount,gasPrice, function(err, hash) {
if (!err)
console.log(hash);
});
depositInChildChain¶
web3.chain.depositInChildChain(from,txHash [, callback])
Deposit from the main chain to child chain (step 2). Should be used with chain_depositInMainChain
Parameters¶
from
- address, 20 Bytes - the address who triggers the actiontxHash
- string - Tx Hash of the chain_depositInMainChain rpc
Returns¶
String - The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var txHash = "0x31d6fe38869272a821ac7a2b3b00aba9cb486f02cc570895f8f5d2dea8f7b5dc";
web3.chain.depositInChildChain(from,txHash, function(err, hash) {
if (!err)
console.log(hash);
});
withdrawFromChildChain¶
web3.chain.withdrawFromChildChain(from,amount,gasPrice [, callback])
Withdraw from child chain to the main chain (step 1). Should be used with chain_withdrawFromMainChain
Parameters¶
from
- address, 20 Bytes - the address who triggers the actiontxHash
- string - Tx Hash of the chain_depositInMainChain rpcgasPrice
- hex string - ( if set to null,system will give default value(1 gwei) ) gas price from the request
Returns¶
String - The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var amount = "0x152D02C7E14AF6800000";
var gasPrice = "0x2540be400";
web3.chain.withdrawFromChildChain(from,amount,gasPrice, function(err, hash) {
if (!err)
console.log(hash);
});
withdrawFromMainChain¶
web3.chain.withdrawFromMainChain(from,amount,chainId,txHash [, callback])
Withdraw from child chain to the main chain (step 2). Should be used with chain_withdrawFromChildChain
Parameters¶
from
- address, 20 Bytes - the address who triggers the actionamount
- hex string - amount of PAI to withdrawchainId
- string - child chain idtxHash
- string - Tx Hash of the chain_withdrawFromChildChain rpc
Returns¶
String - The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var amount = "0x152D02C7E14AF6800000";
var chainId = "pchain-child-1":
var txHash = "0x6ff2ac4bb53ef7907bef3219eb3f2684b66df8a22048a80270960f9671ed0007";
web3.chain.withdrawFromMainChain(from,amount,chainId,txHash, function(err, hash) {
if (!err)
console.log(hash);
});
signAddress¶
web3.chain.signAddress(from,privateKey [, callback])
Sign the Address with BLS Private Key, return the BLS Signature to proof you are the owner of the BLS Public Key
Parameters¶
from
- address, 20 Bytes - the address who triggers the actionprivateKey
- hex string, 32 Bytes - BLS Private Key,How To Get Your Privatekey
Returns¶
DATA, 64 Bytes - the BLS Signature for the Address
Example¶
var from = "0xFD6AA07FF92907886B10B8E8863DDF8BA1902109";
var privateKey = "0xA1BCB0033FC989D34026EED71AE6C57004CF1FBDC520ABF112B13FF7C03B62C6";
web3.chain.signAddress(from,privateKey, function(err, Signature) {
if (!err)
console.log(Signature);
});
setBlockReward¶
web3.chain.setBlockReward(from,reward [, callback])
Set the Reward of each block for the CHILD CHAIN, only Child Chain Owner is allowed to send this tx. The Block Reward change will effect on the next block after this tx be mined.
The Block Reward will be charged from Child Chain Address 0x0000000000000000000000000000000000000064 balance, which accept anyone to transfer their contribution
Parameters¶
from
- address, 20 Bytes - the address who triggers the actionreward
- hex string - The reward of each block
Returns¶
hash, string - the transaction hash
Example¶
var from = "0xFD6AA07FF92907886B10B8E8863DDF8BA1902109";
var award = "0x1";
web3.chain.setBlockReward(from,award, function(err, hash) {
if (!err)
console.log(hash);
});
getBlockReward¶
web3.chain.getBlockReward(blockNumber [, callback])
Get the Reward of each block for the CHILD CHAIN
Parameters¶
QUANTITY|TAG
- integer block number, or the string “latest”, “earliest” or “pending”
Returns¶
QUANTITY - integer of the block reward in wei
Example¶
var blockNumber = "0x670";
web3.chain.getBlockReward(blockNumber, function(err, result) {
if (!err)
console.log(result);
});
getAllChains¶
web3.chain.getAllChains( [, callback])
Get all the Chain Info from the node (A synced Full node should have all the chains’ info)
Parameters¶
none
Returns¶
Object
- The chain info object
chain_id
- String - The chain id of the chain.owner
- Address, 20 Bytes - The owner address of the chain.current_epoch
- Number - The current epoch number of the chain.epoch_start_time
- Time - The start time of the current epochvalidators
- Array - Array of validator objectaddress
- Address - Address of the Validatorvoting_power
- QUANTITY - Voting Power (Stack) of the Validator
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.tdm¶
The web3-tdm
package allows you to interact with the Pchain nodes tdm properties.
voteNextEpoch¶
web3.tdm.voteNextEpoch(from,voteHash,gasPrice [, callback])
Send hash of Vote for the next epoch.
Parameters¶
from
-address, 20 Bytes
- the address who triggers the actionvoteHash
-hex string, 32 Bytes
- hash of the vote. (How to get the vote hash, use Keccak-256 (not the standardized SHA3-256) example: keccak256(from + pubkey + amount + salt) ),you can get pubkey from ‘priv_validator.json’ in the datadir directory(Default ~/.pchain on linux).You can get vote hash By Javascript API getVoteHashgasPrice
-hex string
- (optional, default: 1 gwei) gas price from the request
Returns¶
String
- The 32 Bytes transaction hash as HEX string.
Example¶
var from = "4CACBCBF218679DCC9574A90A2061BCA4A8D8B6C";
var pubkey = "7315DF293B07C52EF6C1FC05018A1CA4FB630F6DBD4F1216804FEDDC2F04CD2932A5AB72B6910145ED97A5FFA0CDCB818F928A8921FDAE8033BF4259AC3400552065951D2440C25A6994367E1DC60EE34B34CB85CD95304B24F9A07473163F1F24C79AC5CBEC240B5EAA80907F6B3EDD44FD8341BF6EB8179334105FEDE6E790";
var amount = "0x1f4";
var salt = "ABCD";
var voteHash = web3.getVoteHash(from,pubkey,amount,salt);
// "0x78701448b4ee6fc4edc940266bcebc3e21b1b3c208957cb081cfba5a629beb72"
var gasPrice = null:
web3.tdm.voteNextEpoch(from,voteHash,gasPrice, function(err, hash) {
if (!err)
console.log(hash);
});
revealVote¶
web3.tdm.revealVote(from,pubkey,amount,salt,signature,gasPrice [, callback])
Reveal the vote, the content of vote should matched with the hash which provided in tdm_voteNextEpoch.
Parameters¶
from
-address
, 20 Bytes - the address who triggers the actionpubkey
-hex string
, 128 Bytes - the BLS Public Key who triggers the actionmount
-hex string
- the amount of votesalt
-string
- salt stringsignature
-hex string, 64 Bytes
- the signature of From Address, signed by BLS Private Key. (How to sign, see signAddress)gasPrice
-hex string
- (optional, default: 1 gwei) gas price from the request
Returns¶
String
- The 32 Bytes transaction hash as HEX string.
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var pubkey = "04A77BB50F7D3993CC6485CAABF8FE1980EDAAE88635A1FCB6EFE577D4C10166F0BA4D9C1AC53461FE3332292DDC8594C92E0E4D2C0CEEE0F74D8D67ACD8E391B1";
var amount = "0x152D02C7E14AF6800000";
var salt = "salt":
var signature = "0x6e5ea219800849592e67f76d45742a29c42a20b0b9d853facf32ac788591869e3db50a10770d88b93f24d2f6efed8acd220bce6442db7a2fbadfdada2d2cde73";
var gasPrice = null:
web3.tdm.revealVote(from,pubkey,amount,salt,signature, gasPrice,function(err, hash) {
if (!err)
console.log(hash);
});
getCurrentEpochNumber¶
web3.tdm.getCurrentEpochNumber( [, callback])
Returns the current epoch number.
Parameters¶
none
Returns¶
epochNumber
- int
- current epoch number
Example¶
web3.tdm.getCurrentEpochNumber(function(err, result) {
if (!err)
console.log(result);
});
getEpoch¶
web3.tdm.getEpoch(number [, callback])
Returns the epoch details.
Parameters¶
number
- int
- epoch number
Returns¶
the epoch details
Example¶
var number = 1;
web3.tdm.getEpoch(number,function(err, result) {
if (!err)
console.log(result);
});
getNextEpochVote¶
web3.tdm.getNextEpochVote([, callback])
Returns the current epoch number.
Parameters¶
none
Returns¶
result
- string
- votes detail of the next epoch, such as epoch number, start block, end block, votes
Example¶
web3.tdm.getNextEpochVote(function(err, result) {
if (!err)
console.log(result);
});
getNextEpochValidators¶
web3.tdm.getNextEpochValidators([, callback])
Returns the validators of the next epoch based on the votes.
Parameters¶
none
Returns¶
result
- DATA
- validators of the next epoch, such as address, public key, voting power
Example¶
web3.tdm.getNextEpochValidators(function(err, result) {
if (!err)
console.log(result);
});
generatePrivateValidator¶
web3.tdm.generatePrivateValidator(from,[, callback])
Returns the generated BLS Public/Private Key associate with provided address.
Parameters¶
from
- address
- 20 Bytes
Returns¶
address
-`` address, 20 Bytes`` - address from the requestconsensus_pub_key
-hex string, 128 Bytes
- the generated BLS Public Keyconsensus_priv_key
-hex string, 32 Bytes
- the generated BLS Private Key
Example¶
var from = "0x1234567890123456789012345678901234567890";
web3.tdm.generatePrivateValidator(from,function(err, result) {
if (!err)
console.log(result);
});
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.del¶
The web3-del
package allows you to interact with the Pchain nodes delegate properties.
delegate¶
web3.del.delegate(from,candidate,amount,gasPrice [, callback])
Create a new transaction to Delegate your balance to Candidate.
Parameters¶
from
-address, 20 Bytes
- the address who triggers the actioncandidate
-address, 20 Bytes
- the address of candidateamount
-hex string
- Amount of the Delegate PAI (minimum 1,000 PAI)gasPrice
-hex string
- (optional, default: 1 gwei) gas price from the request
Returns¶
hash
- string
- the transaction hash
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var candidate = "0xB3544059698177F14968D29A25AFD0D6D65F4537";
var amount = "0x21e19e0c9bab2400000";
var gasPrice = null:
web3.del.delegate(from,candidate,amount,gasPrice,function(err, result) {
if (!err)
console.log(result);
});
cancelDelegate¶
web3.del.cancelDelegate(from,candidate,amount,gasPrice [, callback])
Create a new transaction to Cancel your Delegation from Candidate.
Parameters¶
from
-address, 20 Bytes
- the address who triggers the actioncandidate
-address, 20 Bytes
- the address of candidateamount
-hex string
- Amount of the Delegate PAIgasPrice: hex string
- (optional, default: 1 gwei) gas price from the request
Returns¶
hash
- string
- the transaction hash
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var candidate = "0xB3544059698177F14968D29A25AFD0D6D65F4537";
var amount = "0x152D02C7E14AF6800000";
var gasPrice = null:
web3.del.cancelDelegate(from,candidate,amount,gasPrice,function(err, result) {
if (!err)
console.log(result);
});
applyCandidate¶
web3.del.applyCandidate(from,securityDeposit,commission,gasPrice [, callback])
Create a new transaction to become a Candidate (with specific security deposit and commission fee rate).
Parameters¶
from
-address, 20 Bytes
- the address who triggers the actionsecurityDeposit
-hex string
- Amount of the security deposit PAI (minimum 10,000 PAI)commission
-integer
- the commission fee percentage of each Block Reward be charged from delegator, when Candidate become a Validator (between 0 - 100)gasPrice
-hex string
- (optional, default: 1 gwei) gas price from the request
Returns¶
hash
- string
- the transaction hash
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var securityDeposit = "0x21e19e0c9bab2400000";
var commission = 10;
var gasPrice = null:
web3.del.applyCandidate(from,securityDeposit,commission,gasPrice,function(err, result) {
if (!err)
console.log(result);
});
cancelCandidate¶
web3.del.cancelCandidate(from,gasPrice [, callback])
Create a new transaction to become a Candidate (with specific security deposit and commission fee rate).
Parameters¶
from
-address, 20 Bytes
- the address who triggers the actiongasPrice
-hex string
- (optional, default: 1 gwei) gas price from the request
Returns¶
hash
- hex string
- the transaction hash
Example¶
var from = "0xB3544059698177F14968D29A25AFD0D6D65F4534";
var gasPrice = null:
web3.del.cancelCandidate(from,gasPrice,function(err, result) {
if (!err)
console.log(result);
});
checkCandidate¶
web3.del.checkCandidate(from,blockNumber [, callback])
Returns the candidate status of the account of given address.
Parameters¶
from
-address, 20 Bytes
- address to check for balance.blockNumber
-QUANTITY|TAG
- integer block number, or the string “latest”, “earliest” or “pending”
Returns¶
candidate
-Boolean
- Candidate Flag of the given addresscommission
-QUANTITY
- commission percentage of Candidate Address
Example¶
var from = "0xd833b6738285f4a50cf42cf1a40c4000256589d4";
web3.del.checkCandidate(from,"latest",function(err, result) {
if (!err)
console.log(result);
});
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.*.net¶
The web3-net
package allows you to interact with the Pchain nodes network properties.
import Web3 from 'web3';
import {Net} from 'web3-net';
// "Personal.providers.givenProvider" will be set if in an Pchain supported browser.
const net = new Net(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// or using the web3 umbrella package
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// -> web3.pi.net
// -> web3.shh.net
getId¶
web3.pi.net.getId([callback])
web3.shh.net.getId([callback])
Gets the current network ID.
Parameters¶
none
Returns¶
Promise
returns Number
: The network ID.
Example¶
web3.pi.net.getId().then(console.log);
> 1
isListening¶
web3.pi.net.isListening([callback])
web3.shh.net.isListening([callback])
Checks if the node is listening for peers.
Parameters¶
none
Returns¶
Promise
returns Boolean
Example¶
web3.pi.isListening().then(console.log);
> true
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.bzz¶
The web3-bzz
does no longer exists in the pweb3.js project. Check out the Swarm Docs
for seeing possible alternatives to interact with the Swarm API.
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.shh¶
The web3-shh
package allows you to interact with the whisper protocol for broadcasting.
For more see Whisper Overview.
import Web3 from 'pweb3';
import {Shh} import 'web3-shh';
// "Web3.givenProvider" will be set if in an Ethereum supported browser.
const shh = new Shh(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
// or using the web3 umbrella package
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options;
// -> web3.shh
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
getId¶
web3.pi.net.getId([callback])
web3.shh.net.getId([callback])
Gets the current network ID.
Parameters¶
none
Returns¶
Promise
returns Number
: The network ID.
Example¶
web3.pi.net.getId().then(console.log);
> 1
isListening¶
web3.pi.net.isListening([callback])
web3.shh.net.isListening([callback])
Checks if the node is listening for peers.
Parameters¶
none
Returns¶
Promise
returns Boolean
Example¶
web3.pi.isListening().then(console.log);
> true
getPeerCount¶
web3.pi.net.getPeerCount([callback])
web3.shh.net.getPeerCount([callback])
Get the number of peers connected to.
Parameters¶
none
Returns¶
Promise
returns Number
Example¶
web3.pi.getPeerCount().then(console.log);
> 25
getVersion¶
web3.shh.getVersion([callback])
Returns the version of the running whisper.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The version of the current whisper running.
getInfo¶
web3.shh.getInfo([callback])
Gets information about the current whisper node.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- The information of the node with the following properties:
messages
-Number
: Number of currently floating messages.maxMessageSize
-Number
: The current message size limit in bytes.memory
-Number
: The memory size of the floating messages in bytes.minPow
-Number
: The current minimum PoW requirement.
Example¶
web3.shh.getInfo().then(console.log);
> {
"minPow": 0.8,
"maxMessageSize": 12345,
"memory": 1234335,
"messages": 20
}
setMaxMessageSize¶
web3.shh.setMaxMessageSize(size, [callback])
Sets the maximal message size allowed by this node. Incoming and outgoing messages with a larger size will be rejected. Whisper message size can never exceed the limit imposed by the underlying P2P protocol (10 Mb).
Parameters¶
Number
- Message size in bytes.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on success, error on failure.
Example¶
web3.shh.setMaxMessageSize(1234565)
.then(console.log);
> true
setMinPoW¶
web3.shh.setMinPoW(pow, [callback])
Sets the minimal PoW required by this node.
This experimental function was introduced for the future dynamic adjustment of PoW requirement. If the node is overwhelmed with messages, it should raise the PoW requirement and notify the peers. The new value should be set relative to the old value (e.g. double). The old value can be obtained via web3.shh.getInfo().
Parameters¶
Number
- The new PoW requirement.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on success, error on failure.
Example¶
web3.shh.setMinPoW(0.9)
.then(console.log);
> true
markTrustedPeer¶
web3.shh.markTrustedPeer(enode, [callback])
Marks specific peer trusted, which will allow it to send historic (expired) messages.
Note
This function is not adding new nodes, the node needs to be an existing peer.
Parameters¶
String
- Enode of the trusted peer.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on success, error on failure.
Example¶
web3.shh.markTrustedPeer()
.then(console.log);
> true
newKeyPair¶
web3.shh.newKeyPair([callback])
Generates a new public and private key pair for message decryption and encryption.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- Returns the Key ID on success and an error on failure.
Example¶
web3.shh.newKeyPair()
.then(console.log);
> "5e57b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f"
addPrivateKey¶
web3.shh.addPrivateKey(privateKey, [callback])
Stores a key pair derived from a private key, and returns its ID.
Parameters¶
String
- The private key as HEX bytes to import.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The Key ID on success and an error on failure.
Example¶
web3.shh.addPrivateKey('0x8bda3abeb454847b515fa9b404cede50b1cc63cfdeddd4999d074284b4c21e15')
.then(console.log);
> "3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f"
deleteKeyPair¶
web3.shh.deleteKeyPair(id, [callback])
Deletes the specifies key if it exists.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newKeyPair
andshh.addPrivateKey
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on success, error on failure.
Example¶
web3.shh.deleteKeyPair('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> true
hasKeyPair¶
web3.shh.hasKeyPair(id, [callback])
Checks if the whisper node has a private key of a key pair matching the given ID.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newKeyPair
andshh.addPrivateKey
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on if the key pair exist in the node, false
if not. Error on failure.
Example¶
web3.shh.hasKeyPair('fe22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> true
getPublicKey¶
web3.shh.getPublicKey(id, [callback])
Returns the public key for a key pair ID.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newKeyPair
andshh.addPrivateKey
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- Returns the Public key on success and an error on failure.
Example¶
web3.shh.getPublicKey('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0x04d1574d4eab8f3dde4d2dc7ed2c4d699d77cbbdd09167b8fffa099652ce4df00c4c6e0263eafe05007a46fdf0c8d32b11aeabcd3abbc7b2bc2bb967368a68e9c6"
getPrivateKey¶
web3.shh.getPrivateKey(id, [callback])
Returns the private key for a key pair ID.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newKeyPair
andshh.addPrivateKey
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- Returns the private key on success and an error on failure.
Example¶
web3.shh.getPrivateKey('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0x234234e22b9ffc2387e18636e0534534a3d0c56b0243567432453264c16e78a2adc"
newSymKey¶
web3.shh.newSymKey([callback])
Generates a random symmetric key and stores it under an ID, which is then returned. Will be used for encrypting and decrypting of messages where the sym key is known to both parties.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- Returns the Key ID on success and an error on failure.
Example¶
web3.shh.newSymKey()
.then(console.log);
> "cec94d139ff51d7df1d228812b90c23ec1f909afa0840ed80f1e04030bb681e4"
addSymKey¶
web3.shh.addSymKey(symKey, [callback])
Stores the key, and returns its ID.
Parameters¶
String
- The raw key for symmetric encryption as HEX bytes.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- Returns the key ID on success and an error on failure.
Example¶
web3.shh.addSymKey('0x5e11b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "fea94d139ff51d7df1d228812b90c23ec1f909afa0840ed80f1e04030bb681e4"
generateSymKeyFromPassword¶
web3.shh.generateSymKeyFromPassword(password, [callback])
Generates the key from password, stores it, and returns its ID.
Parameters¶
String
- A password to generate the sym key from.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<String|Error>
- Returns the Key ID on success and an error on failure.
Example¶
web3.shh.generateSymKeyFromPassword('Never use this password - password!')
.then(console.log);
> "2e57b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f"
hasSymKey¶
web3.shh.hasSymKey(id, [callback])
Checks if there is a symmetric key stored with the given ID.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newSymKey
,shh.addSymKey
orshh.generateSymKeyFromPassword
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on if the symmetric key exist in the node, false
if not. Error on failure.
Example¶
web3.shh.hasSymKey('f6dcf21ed6a17bd78d8c4c63195ab997b3b65ea683705501eae82d32667adc92')
.then(console.log);
> true
getSymKey¶
web3.shh.getSymKey(id, [callback])
Returns the symmetric key associated with the given ID.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newKeyPair
andshh.addPrivateKey
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- Returns the raw symmetric key on success and an error on failure.
Example¶
web3.shh.getSymKey('af33b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0xa82a520aff70f7a989098376e48ec128f25f767085e84d7fb995a9815eebff0a"
deleteSymKey¶
web3.shh.deleteSymKey(id, [callback])
Deletes the symmetric key associated with the given ID.
Parameters¶
String
- The key pair ID, returned by the creation functions (shh.newKeyPair
andshh.addPrivateKey
).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- Returns true
on if the symmetric key was deleted, error on failure.
Example¶
web3.shh.deleteSymKey('bf31b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> true
post¶
web3.shh.post(object [, callback])
This method should be called, when we want to post whisper a message to the network.
Parameters¶
Object
- The post object:symKeyID
-String
(optional): ID of symmetric key for message encryption (EithersymKeyID
orpubKey
must be present. Can not be both.).pubKey
-String
(optional): The public key for message encryption (EithersymKeyID
orpubKey
must be present. Can not be both.).sig
-String
(optional): The ID of the signing key.ttl
-Number
: Time-to-live in seconds.topic
-String
: 4 Bytes (mandatory when key is symmetric): Message topic.payload
-String
: The payload of the message to be encrypted.padding
-Number
(optional): Padding (byte array of arbitrary length).powTime
-Number
(optional)?: Maximal time in seconds to be spent on proof of work.powTarget
-Number
(optional)?: Minimal PoW target required for this message.targetPeer
-Number
(optional): Peer ID (for peer-to-peer message only).
callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise
returns Promise
- returns a promise. Upon success, the then
function will be passed a string representing the hash of the sent message. On error, the catch
function will be passed a string containing the reason for the error.
Example¶
const identities = [];
Promise.all([
web3.shh.newSymKey().then((id) => {identities.push(id);}),
web3.shh.newKeyPair().then((id) => {identities.push(id);})
]).then(() => {
// will receive also its own message send, below
const subscription = shh.subscribe("messages", {
symKeyID: identities[0],
topics: ['0xffaadd11']
}).on('data', console.log);
}).then(() => {
web3.shh.post({
symKeyID: identities[0], // encrypts using the sym key ID
sig: identities[1], // signs the message using the keyPair ID
ttl: 10,
topic: '0xffaadd11',
payload: '0xffffffdddddd1122',
powTime: 3,
powTarget: 0.5
}).then(hash => console.log(`Message with hash ${hash} was successfuly sent`))
.catch(err => console.log("Error: ", err));
});
subscribe¶
web3.shh.subscribe('messages', options [, callback])
Subscribe for incoming whisper messages.
Parameters¶
"messages"
-String
: Type of the subscription.Object
- The subscription options:symKeyID
-String
: ID of symmetric key for message decryption.privateKeyID
-String
: ID of private (asymmetric) key for message decryption.sig
-String
(optional): Public key of the signature, to verify.topics
-Array
(optional when “privateKeyID” key is given): Filters messages by this topic(s). Each topic must be a 4 bytes HEX string.minPow
-Number
(optional): Minimal PoW requirement for incoming messages.allowP2P
-Boolean
(optional): Indicates if this filter allows processing of direct peer-to-peer messages (which are not to be forwarded any further, because they might be expired). This might be the case in some very rare cases, e.g. if you intend to communicate to MailServers, etc.
callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second. Will be called for each incoming subscription, and the subscription itself as 3 parameter.
Notification Returns¶
Object
- The incoming message:
hash
-String
: Hash of the enveloped message.sig
-String
: Public key which signed this message.recipientPublicKey
-String
: The recipients public key.timestamp
-String
: Unix timestamp of the message genertion.ttl
-Number
: Time-to-live in seconds.topic
-String
: 4 Bytes HEX string message topic.payload
-String
: Decrypted payload.padding
-Number
: Optional padding (byte array of arbitrary length).pow
-Number
: Proof of work value.
Example¶
web3.shh.subscribe('messages', {
symKeyID: 'bf31b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f',
sig: '0x04d1574d4eab8f3dde4d2dc7ed2c4d699d77cbbdd09167b8fffa099652ce4df00c4c6e0263eafe05007a46fdf0c8d32b11aeabcd3abbc7b2bc2bb967368a68e9c6',
ttl: 20,
topics: ['0xffddaa11'],
minPow: 0.8,
}, (error, message, subscription) => {
console.log(message);
> {
"hash": "0x4158eb81ad8e30cfcee67f20b1372983d388f1243a96e39f94fd2797b1e9c78e",
"padding": "0xc15f786f34e5cef0fef6ce7c1185d799ecdb5ebca72b3310648c5588db2e99a0d73301c7a8d90115a91213f0bc9c72295fbaf584bf14dc97800550ea53577c9fb57c0249caeb081733b4e605cdb1a6011cee8b6d8fddb972c2b90157e23ba3baae6c68d4f0b5822242bb2c4cd821b9568d3033f10ec1114f641668fc1083bf79ebb9f5c15457b538249a97b22a4bcc4f02f06dec7318c16758f7c008001c2e14eba67d26218ec7502ad6ba81b2402159d7c29b068b8937892e3d4f0d4ad1fb9be5e66fb61d3d21a1c3163bce74c0a9d16891e2573146aa92ecd7b91ea96a6987ece052edc5ffb620a8987a83ac5b8b6140d8df6e92e64251bf3a2cec0cca",
"payload": "0xdeadbeaf",
"pow": 0.5371803278688525,
"recipientPublicKey": null,
"sig": null,
"timestamp": 1496991876,
"topic": "0x01020304",
"ttl": 50
}
})
// or
.on('data', (message) => { ... });
clearSubscriptions¶
web3.shh.clearSubscriptions()
Resets subscriptions.
Note
This will not reset subscriptions from other packages like web3-eth
, as they use their own requestManager.
Parameters¶
Boolean
: Iftrue
it keeps the"syncing"
subscription.
Returns¶
Boolean
Example¶
web3.shh.subscribe('messages', {...} , () => { ... });
...
web3.shh.clearSubscriptions();
newMessageFilter¶
web3.shh.newMessageFilter(options)
Create a new filter within the node. This filter can be used to poll for new messages that match the set of criteria.
Parameters¶
Object
: See web3.shh.subscribe() options for details.
Returns¶
Promise<string>
- Returns the filter ID.
Example¶
web3.shh.newMessageFilter()
.then(console.log);
> "2b47fbafb3cce24570812a82e6e93cd9e2551bbc4823f6548ff0d82d2206b326"
deleteMessageFilter¶
web3.shh.deleteMessageFilter(id)
Deletes a message filter in the node.
Parameters¶
String
: The filter ID created withshh.newMessageFilter()
.
Returns¶
Promise<boolean>
- Returns true
on success, error on failure.
Example¶
web3.shh.deleteMessageFilter('2b47fbafb3cce24570812a82e6e93cd9e2551bbc4823f6548ff0d82d2206b326')
.then(console.log);
> true
getFilterMessages¶
web3.shh.getFilterMessages(id)
Retrieve messages that match the filter criteria and are received between the last time this function was called and now.
Parameters¶
String
: The filter ID created withshh.newMessageFilter()
.
Returns¶
Promise<Array>
- Returns an array of message objects like web3.shh.subscribe() notification returns
Example¶
web3.shh.getFilterMessages('2b47fbafb3cce24570812a82e6e93cd9e2551bbc4823f6548ff0d82d2206b326')
.then(console.log);
> [{
"hash": "0x4158eb81ad8e30cfcee67f20b1372983d388f1243a96e39f94fd2797b1e9c78e",
"padding": "0xc15f786f34e5cef0fef6ce7c1185d799ecdb5ebca72b3310648c5588db2e99a0d73301c7a8d90115a91213f0bc9c72295fbaf584bf14dc97800550ea53577c9fb57c0249caeb081733b4e605cdb1a6011cee8b6d8fddb972c2b90157e23ba3baae6c68d4f0b5822242bb2c4cd821b9568d3033f10ec1114f641668fc1083bf79ebb9f5c15457b538249a97b22a4bcc4f02f06dec7318c16758f7c008001c2e14eba67d26218ec7502ad6ba81b2402159d7c29b068b8937892e3d4f0d4ad1fb9be5e66fb61d3d21a1c3163bce74c0a9d16891e2573146aa92ecd7b91ea96a6987ece052edc5ffb620a8987a83ac5b8b6140d8df6e92e64251bf3a2cec0cca",
"payload": "0xdeadbeaf",
"pow": 0.5371803278688525,
"recipientPublicKey": null,
"sig": null,
"timestamp": 1496991876,
"topic": "0x01020304",
"ttl": 50
},{...}]
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
web3.utils¶
This package provides utility functions for Pchain dapps and other pweb3.js packages.
randomHex¶
web3.utils.randomHex(size)
The randomHex library to generate cryptographically strong pseudo-random HEX strings from a given byte size.
Parameters¶
size
-Number
: The byte size for the HEX string, e.g.32
will result in a 32 bytes HEX string with 64 characters preficed with “0x”.
Returns¶
String
: The generated random HEX string.
Example¶
web3.utils.randomHex(32)
> "0xa5b9d60f32436310afebcfda832817a68921beb782fabf7915cc0460b443116a"
web3.utils.randomHex(4)
> "0x6892ffc6"
web3.utils.randomHex(2)
> "0x99d6"
web3.utils.randomHex(1)
> "0x9a"
web3.utils.randomHex(0)
> "0x"
BN¶
web3.utils.BN(mixed)
The BN.js library for calculating with big numbers in JavaScript. See the BN.js documentation for details.
Note
For safe conversion of many types, incl BigNumber.js use utils.toBN
Parameters¶
value
-String|Number
: A number, number string or HEX string to convert to a BN object.
Example¶
const BN = web3.utils.BN;
new BN(1234).toString();
> "1234"
new BN('1234').add(new BN('1')).toString();
> "1235"
new BN('0xea').toString();
> "234"
isBN¶
web3.utils.isBN(bn)
Checks if a given value is a BN.js instance.
Returns¶
Boolean
Example¶
const number = new BN(10);
web3.utils.isBN(number);
> true
isBigNumber¶
web3.utils.isBigNumber(bignumber)
Checks if a given value is a BigNumber.js instance.
Parameters¶
BigNumber
-Object
: A BigNumber.js instance.
Returns¶
Boolean
Example¶
const number = new BigNumber(10);
web3.utils.isBigNumber(number);
> true
keccak256¶
web3.utils.keccak256(string)
web3.utils.sha3(string) // ALIAS
Will calculate the keccak256 of the input.
Note
To mimic the keccak256 behaviour of solidity use soliditySha3
Parameters¶
string
-String
: A string to hash.
Returns¶
String
: the result hash.
Example¶
web3.utils.keccak256('234'); // taken as string
> "0xc1912fee45d61c87cc5ea59dae311904cd86b84fee17cc96966216f811ce6a79"
web3.utils.keccak256(new BN('234'));
> "0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a"
web3.utils.keccak256(234);
> null // can't calculate the hash of a number
web3.utils.keccak256(0xea); // same as above, just the HEX representation of the number
> null
web3.utils.keccak256('0xea'); // will be converted to a byte array first, and then hashed
> "0x2f20677459120677484f7104c76deb6846a2c071f9b3152c103bb12cd54d1a4a"
soliditySha3¶
web3.utils.soliditySha3(param1 [, param2, ...])
Will calculate the sha3 of given input parameters in the same way solidity would. This means arguments will be ABI converted and tightly packed before being hashed.
Parameters¶
paramX
-Mixed
: Any type, or an object with{type: 'uint', value: '123456'}
or{t: 'bytes', v: '0xfff456'}
. Basic types are autodetected as follows:String
non numerical UTF-8 string is interpreted asstring
.String|Number|BN|HEX
positive number is interpreted asuint256
.String|Number|BN
negative number is interpreted asint256
.Boolean
asbool
.String
HEX string with leading0x
is interpreted asbytes
.HEX
HEX number representation is interpreted asuint256
.
Returns¶
String
: the result hash.
Example¶
web3.utils.soliditySha3('234564535', '0xfff23243', true, -10);
// auto detects: uint256, bytes, bool, int256
> "0x3e27a893dc40ef8a7f0841d96639de2f58a132be5ae466d40087a2cfa83b7179"
web3.utils.soliditySha3('Hello!%'); // auto detects: string
> "0x661136a4267dba9ccdf6bfddb7c00e714de936674c4bdb065a531cf1cb15c7fc"
web3.utils.soliditySha3('234'); // auto detects: uint256
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"
web3.utils.soliditySha3(0xea); // same as above
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"
web3.utils.soliditySha3(new BN('234')); // same as above
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"
web3.utils.soliditySha3({type: 'uint256', value: '234'})); // same as above
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"
web3.utils.soliditySha3({t: 'uint', v: new BN('234')})); // same as above
> "0x61c831beab28d67d1bb40b5ae1a11e2757fa842f031a2d0bc94a7867bc5d26c2"
web3.utils.soliditySha3('0x407D73d8a49eeb85D32Cf465507dd71d507100c1');
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b"
web3.utils.soliditySha3({t: 'bytes', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b" // same result as above
web3.utils.soliditySha3({t: 'address', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
> "0x4e8ebbefa452077428f93c9520d3edd60594ff452a29ac7d2ccc11d47f3ab95b" // same as above, but will do a checksum check, if its multi case
web3.utils.soliditySha3({t: 'bytes32', v: '0x407D73d8a49eeb85D32Cf465507dd71d507100c1'});
> "0x3c69a194aaf415ba5d6afca734660d0a3d45acdc05d54cd1ca89a8988e7625b4" // different result as above
web3.utils.soliditySha3({t: 'string', v: 'Hello!%'}, {t: 'int8', v:-23}, {t: 'address', v: '0x85F43D8a49eeB85d32Cf465507DD71d507100C1d'});
> "0xa13b31627c1ed7aaded5aecec71baf02fe123797fffd45e662eac8e06fbe4955"
isHex¶
web3.utils.isHex(hex)
Checks if a given string is a HEX string.
Parameters¶
hex
-String|HEX
: The given HEX string.
Returns¶
Boolean
Example¶
web3.utils.isHex('0xc1912');
> true
web3.utils.isHex(0xc1912);
> true
web3.utils.isHex('c1912');
> true
web3.utils.isHex(345);
> true // this is tricky, as 345 can be a a HEX representation or a number, be careful when not having a 0x in front!
web3.utils.isHex('0xZ1912');
> false
web3.utils.isHex('Hello');
> false
isHexStrict¶
web3.utils.isHexStrict(hex)
Checks if a given string is a HEX string. Difference to web3.utils.isHex()
is that it expects HEX to be prefixed with 0x
.
Parameters¶
hex
-String|HEX
: The given HEX string.
Returns¶
Boolean
Example¶
web3.utils.isHexStrict('0xc1912');
> true
web3.utils.isHexStrict(0xc1912);
> false
web3.utils.isHexStrict('c1912');
> false
web3.utils.isHexStrict(345);
> false // this is tricky, as 345 can be a a HEX representation or a number, be careful when not having a 0x in front!
web3.utils.isHexStrict('0xZ1912');
> false
web3.utils.isHex('Hello');
> false
isAddress¶
web3.utils.isAddress(address, [, chainId])
Checks if a given string is a valid Pchain address. It will also check the checksum, if the address has upper and lowercase letters.
Parameters¶
address
-String
: An address string.chainId
-number
(optional): Chain id where checksummed address should be valid, defaults tonull
. RSKIP-60 <https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md> for details.
Returns¶
Boolean
Example¶
web3.utils.isAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
> true
web3.utils.isAddress('c1912fee45d61c87cc5ea59dae31190fffff232d');
> true
web3.utils.isAddress('0XC1912FEE45D61C87CC5EA59DAE31190FFFFF232D');
> true // as all is uppercase, no checksum will be checked
web3.utils.isAddress('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
> true
web3.utils.isAddress('0xC1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
> false // wrong checksum
web3.utils.isAddress('0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD', 30);
> true
toChecksumAddress¶
web3.utils.toChecksumAddress(address[, chainId])
Will convert an upper or lowercase Pchain address to a checksum address.
Parameters¶
address
-String
: An address string.chainId
-number
(optional): Chain id where checksummed address should be valid, defaults tonull
. RSKIP-60 <https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md> for details.
Returns¶
String
: The checksum address.
Example¶
web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');
> "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d"
web3.utils.toChecksumAddress('0XC1912FEE45D61C87CC5EA59DAE31190FFFFF232D');
> "0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d" // same as above
web3.utils.toChecksumAddress('0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed', 30);
> "0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD"
stripHexPrefix¶
Removes the prefix0x
from a given hex if it exists.
Parameters¶
hex
-String
: Hex
Returns¶
String
: Hex without prefix.
Example¶
checkAddressChecksum¶
web3.utils.checkAddressChecksum(address [, chainId])
Checks the checksum of a given address. Will also return false on non-checksum addresses.
Parameters¶
address
-String
: An address string.chainId
-number
(optional): Chain id where checksummed address should be valid, defaults tonull
. RSKIP-60 <https://github.com/rsksmart/RSKIPs/blob/master/IPs/RSKIP60.md> for details.
Returns¶
Boolean
: true
when the checksum of the address is valid, false
if its not a checksum address, or the checksum is invalid.
Example¶
web3.utils.checkAddressChecksum('0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d');
> true
web3.utils.checkAddressChecksum('0x5aAeb6053F3e94c9b9A09F33669435E7EF1BEaEd', 31);
> true
toHex¶
web3.utils.toHex(mixed)
Will auto convert any given value to HEX. Number strings will interpreted as numbers. Text strings will be interpreted as UTF-8 strings.
Parameters¶
value
-String|Number|BN|BigNumber
: The input to convert to HEX.
Returns¶
String
: The resulting HEX string.
Example¶
web3.utils.toHex('234');
> "0xea"
web3.utils.toHex(234);
> "0xea"
web3.utils.toHex(new BN('234'));
> "0xea"
web3.utils.toHex(new BigNumber('234'));
> "0xea"
web3.utils.toHex('I have 100€');
> "0x49206861766520313030e282ac"
toBN¶
web3.utils.toBN(number)
Will safely convert any given value (including BigNumber.js instances) into a BN.js instance, for handling big numbers in JavaScript.
Parameters¶
number
-String|Number|HEX
: Number to convert to a big number.
Example¶
web3.utils.toBN(1234).toString();
> "1234"
web3.utils.toBN('1234').add(web3.utils.toBN('1')).toString();
> "1235"
web3.utils.toBN('0xea').toString();
> "234"
hexToNumberString¶
web3.utils.hexToNumberString(hex)
Returns the number representation of a given HEX value as a string.
Parameters¶
hexString
-String|HEX
: A string to hash.
Returns¶
String
: The number as a string.
Example¶
web3.utils.hexToNumberString('0xea');
> "234"
hexToNumber¶
web3.utils.hexToNumber(hex)
web3.utils.toDecimal(hex) // ALIAS, deprecated
Returns the number representation of a given HEX value.
Note
This is not useful for big numbers, rather use utils.toBN instead.
Parameters¶
hexString
-String|HEX
: A string to hash.
Returns¶
Number
Example¶
web3.utils.hexToNumber('0xea');
> 234
numberToHex¶
web3.utils.numberToHex(number)
web3.utils.fromDecimal(number) // ALIAS, deprecated
Returns the HEX representation of a given number value.
Parameters¶
number
-String|Number|BN|BigNumber
: A number as string or number.
Returns¶
String
: The HEX value of the given number.
Example¶
web3.utils.numberToHex('234');
> '0xea'
hexToUtf8¶
web3.utils.hexToUtf8(hex)
web3.utils.hexToString(hex) // ALIAS
web3.utils.toUtf8(hex) // ALIAS, deprecated
Returns the UTF-8 string representation of a given HEX value.
Parameters¶
hex
-String
: A HEX string to convert to a UTF-8 string.
Returns¶
String
: The UTF-8 string.
Example¶
web3.utils.hexToUtf8('0x49206861766520313030e282ac');
> "I have 100€"
hexToAscii¶
web3.utils.hexToAscii(hex)
web3.utils.toAscii(hex) // ALIAS, deprecated
Returns the ASCII string representation of a given HEX value.
Parameters¶
hex
-String
: A HEX string to convert to a ASCII string.
Returns¶
String
: The ASCII string.
utf8ToHex¶
web3.utils.utf8ToHex(string)
web3.utils.stringToHex(string) // ALIAS
web3.utils.fromUtf8(string) // ALIAS, deprecated
Returns the HEX representation of a given UTF-8 string.
Parameters¶
string
-String
: A UTF-8 string to convert to a HEX string.
Returns¶
String
: The HEX string.
Example¶
web3.utils.utf8ToHex('I have 100€');
> "0x49206861766520313030e282ac"
asciiToHex¶
web3.utils.asciiToHex(string)
web3.utils.fromAscii(string) // ALIAS, deprecated
Returns the HEX representation of a given ASCII string. If you would like to transform an ASCII string into a valid
bytes4
, bytes8
etc. value then please pass the correct length as the second parameter.
Parameters¶
string
-String
: A ASCII string to convert to a HEX string.length
-Number
: The length of the returned hex string. The default size is32
e.g.:bytes32
.
Returns¶
String
: The HEX string.
Example¶
web3.utils.asciiToHex('I have 100!');
> "0x4920686176652031303021000000000000000000000000000000000000000000"
// transforming to a bytes4 value:
web3.utils.asciiToHex('yes', 4);
// transforming to a bytes8 value:
web3.utils.asciiToHex('yes', 8);
//etc.
hexToBytes¶
web3.utils.hexToBytes(hex)
Returns a byte array from the given HEX string.
Parameters¶
hex
-String|HEX
: A HEX to convert.
Returns¶
Array
: The byte array.
Example¶
web3.utils.hexToBytes('0x000000ea');
> [ 0, 0, 0, 234 ]
web3.utils.hexToBytes(0x000000ea);
> [ 234 ]
bytesToHex¶
web3.utils.bytesToHex(byteArray)
Returns a HEX string from a byte array.
Parameters¶
byteArray
-Array
: A byte array to convert.
Returns¶
String
: The HEX string.
Example¶
web3.utils.bytesToHex([ 72, 101, 108, 108, 111, 33, 36 ]);
> "0x48656c6c6f2125"
toWei¶
web3.utils.toWei(number [, unit])
Converts any ether value value into wei.
Note
“wei” are the smallest ethere unit, and you should always make calculations in wei and convert only for display reasons.
Parameters¶
number
-String|BN
: The value.unit
-String
(optional, defaults to"ether"
): The ether to convert from. Possible units are:noether
: ‘0’wei
: ‘1’kwei
: ‘1000’Kwei
: ‘1000’babbage
: ‘1000’femtoether
: ‘1000’mwei
: ‘1000000’Mwei
: ‘1000000’lovelace
: ‘1000000’picoether
: ‘1000000’gwei
: ‘1000000000’Gwei
: ‘1000000000’shannon
: ‘1000000000’nanoether
: ‘1000000000’nano
: ‘1000000000’szabo
: ‘1000000000000’microether
: ‘1000000000000’micro
: ‘1000000000000’finney
: ‘1000000000000000’milliether
: ‘1000000000000000’milli
: ‘1000000000000000’ether
: ‘1000000000000000000’kether
: ‘1000000000000000000000’grand
: ‘1000000000000000000000’mether
: ‘1000000000000000000000000’gether
: ‘1000000000000000000000000000’tether
: ‘1000000000000000000000000000000’
Example¶
web3.utils.toWei('1', 'ether');
> "1000000000000000000"
web3.utils.toWei('1', 'finney');
> "1000000000000000"
web3.utils.toWei('1', 'szabo');
> "1000000000000"
web3.utils.toWei('1', 'shannon');
> "1000000000"
fromWei¶
web3.utils.fromWei(number [, unit])
Converts any wei value into a ether value.
Note
“wei” are the smallest ethere unit, and you should always make calculations in wei and convert only for display reasons.
Parameters¶
number
-String|BN
: The value in wei.unit
-String
(optional, defaults to"ether"
): The ether to convert to. Possible units are:noether
: ‘0’wei
: ‘1’kwei
: ‘1000’Kwei
: ‘1000’babbage
: ‘1000’femtoether
: ‘1000’mwei
: ‘1000000’Mwei
: ‘1000000’lovelace
: ‘1000000’picoether
: ‘1000000’gwei
: ‘1000000000’Gwei
: ‘1000000000’shannon
: ‘1000000000’nanoether
: ‘1000000000’nano
: ‘1000000000’szabo
: ‘1000000000000’microether
: ‘1000000000000’micro
: ‘1000000000000’finney
: ‘1000000000000000’milliether
: ‘1000000000000000’milli
: ‘1000000000000000’ether
: ‘1000000000000000000’kether
: ‘1000000000000000000000’grand
: ‘1000000000000000000000’mether
: ‘1000000000000000000000000’gether
: ‘1000000000000000000000000000’tether
: ‘1000000000000000000000000000000’
Returns¶
String
: It always returns a string number.
Example¶
web3.utils.fromWei('1', 'ether');
> "0.000000000000000001"
web3.utils.fromWei('1', 'finney');
> "0.000000000000001"
web3.utils.fromWei('1', 'szabo');
> "0.000000000001"
web3.utils.fromWei('1', 'shannon');
> "0.000000001"
unitMap¶
web3.utils.unitMap
Shows all possible ether value and their amount in wei.
Return value¶
Object
with the following properties:noether
: ‘0’wei
: ‘1’kwei
: ‘1000’Kwei
: ‘1000’babbage
: ‘1000’femtoether
: ‘1000’mwei
: ‘1000000’Mwei
: ‘1000000’lovelace
: ‘1000000’picoether
: ‘1000000’gwei
: ‘1000000000’Gwei
: ‘1000000000’shannon
: ‘1000000000’nanoether
: ‘1000000000’nano
: ‘1000000000’szabo
: ‘1000000000000’microether
: ‘1000000000000’micro
: ‘1000000000000’finney
: ‘1000000000000000’milliether
: ‘1000000000000000’milli
: ‘1000000000000000’ether
: ‘1000000000000000000’kether
: ‘1000000000000000000000’grand
: ‘1000000000000000000000’mether
: ‘1000000000000000000000000’gether
: ‘1000000000000000000000000000’tether
: ‘1000000000000000000000000000000’
Example¶
web3.utils.unitMap
> {
noether: '0',
wei: '1',
kwei: '1000',
Kwei: '1000',
babbage: '1000',
femtoether: '1000',
mwei: '1000000',
Mwei: '1000000',
lovelace: '1000000',
picoether: '1000000',
gwei: '1000000000',
Gwei: '1000000000',
shannon: '1000000000',
nanoether: '1000000000',
nano: '1000000000',
szabo: '1000000000000',
microether: '1000000000000',
micro: '1000000000000',
finney: '1000000000000000',
milliether: '1000000000000000',
milli: '1000000000000000',
ether: '1000000000000000000',
kether: '1000000000000000000000',
grand: '1000000000000000000000',
mether: '1000000000000000000000000',
gether: '1000000000000000000000000000',
tether: '1000000000000000000000000000000'
}
padLeft¶
web3.utils.padLeft(string, characterAmount [, sign])
web3.utils.leftPad(string, characterAmount [, sign]) // ALIAS
Adds a padding on the left of a string, Useful for adding paddings to HEX strings.
Parameters¶
string
-String
: The string to add padding on the left.characterAmount
-Number
: The number of characters the total string should have.sign
-String
(optional): The character sign to use, defaults to"0"
.
Returns¶
String
: The padded string.
Example¶
web3.utils.padLeft('0x3456ff', 20);
> "0x000000000000003456ff"
web3.utils.padLeft(0x3456ff, 20);
> "0x000000000000003456ff"
web3.utils.padLeft('Hello', 20, 'x');
> "xxxxxxxxxxxxxxxHello"
padRight¶
web3.utils.padRight(string, characterAmount [, sign])
web3.utils.rightPad(string, characterAmount [, sign]) // ALIAS
Adds a padding on the right of a string, Useful for adding paddings to HEX strings.
Parameters¶
string
-String
: The string to add padding on the right.characterAmount
-Number
: The number of characters the total string should have.sign
-String
(optional): The character sign to use, defaults to"0"
.
Returns¶
String
: The padded string.
Example¶
web3.utils.padRight('0x3456ff', 20);
> "0x3456ff00000000000000"
web3.utils.padRight(0x3456ff, 20);
> "0x3456ff00000000000000"
web3.utils.padRight('Hello', 20, 'x');
> "Helloxxxxxxxxxxxxxxx"
toTwosComplement¶
web3.utils.toTwosComplement(number)
Converts a negative numer into a two’s complement.
Parameters¶
number
-Number|String|BigNumber
: The number to convert.
Returns¶
String
: The converted hex string.
Example¶
web3.utils.toTwosComplement('-1');
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
web3.utils.toTwosComplement(-1);
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
web3.utils.toTwosComplement('0x1');
> "0x0000000000000000000000000000000000000000000000000000000000000001"
web3.utils.toTwosComplement(-15);
> "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1"
web3.utils.toTwosComplement('-0x1');
> "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
getSignatureParameters¶
web3.utils.getSignatureParameters(string)
Gets the r, s and v values of an ECDSA signature
Parameters¶
string
-String
: An ECDSA signature.
Returns¶
Object
: Object containing r,s,v values.
Example¶
web3.utils.getSignatureParameters('0x5763ab346198e3e6cc4d53996ccdeca0c941cb6cb70d671d97711c421d3bf7922c77ef244ad40e5262d1721bf9638fb06bab8ed3c43bfaa80d6da0be9bbd33dc1b');
> "{ r: '0x5763ab346198e3e6cc4d53996ccdeca0c941cb6cb70d671d97711c421d3bf792', s: '0x2c77ef244ad40e5262d1721bf9638fb06bab8ed3c43bfaa80d6da0be9bbd33dc', v: 27 }"
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Module API¶
The Module API
gives you the possibility to create your own custom Web3 Module with JSON-RPC methods, subscriptions, or contracts.
The provided modules from the Web3 library are also written with the Module API
the core does provide.
The goal of the Module API
is to provide the possibility to extend and customize the JSON-RPC methods, contracts, and subscriptions
to project specific classes with a similar kind of API the DApp developer knows from the PWeb3.js library.
It’s possible with the Web3 Module API to create complex contract APIs and tools for the development of a DApp.
These are the core modules which are providing all the classes for the Web3 Module API.
Example¶
import * as Utils from 'web3-utils';
import {formatters} from 'web3-core-helpers';
import {AbstractWeb3Module} from 'web3-core';
import {AbstractMethodFactory, GetBlockByNumberMethod, AbstractMethod} from 'web3-core-method';
class MethodFactory extends AbstractMethodFactory {
/**
* @param {Utils} utils
* @param {Object} formatters
*
* @constructor
*/
constructor(utils, formatters) {
super(utils, formatters);
this.methods = {
getBlockByNumber: GetBlockByNumberMethod
};
}
}
class Example extends AbstractWeb3Module {
/**
* @param {AbstractSocketProvider|HttpProvider|CustomProvider|String} provider
* @param {Web3ModuleOptions} options
* @param {Net.Socket} net
*
* @constructor
*/
constructor(provider, net, options) {
super(provider, net, new MethodFactory(Utils, formatters), options;
}
/**
* Executes the eth_sign JSON-RPC method
*
* @method sign
*
* @returns {Promise}
*/
sign() {
const method = new AbstractMethod('eth_sign', 2, Utils, formatters, this);
method.setArguments(arguments)
return method.execute();
}
/**
* Executes the eth_subscribe JSON-RPC method with the subscription type logs
*
* @method logs
*
* @returns {LogSubscription}
*/
logs(options) {
return new LogSubscription(
options,
Utils,
formatters,
this,
new GetPastLogsMethod(Utils, formatters, this)
);
}
}
const example = new Example(provider, net, options);
example.sign('0x0', 'message').then(console.log);
// > "response"
example.sign('0x0', 'message', (error, response) => {
console.log(response);
};
// > "response"
const block = example.getBlockByNumber(1).then(console.log);
// > {}
example.logs(options).subscribe(console.log);
> {}
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Contract Module API¶
The Contract Module API
does provide to possibility to create project specific contracts with pre-injecting of the ABI or customizing of the default behaviour of a Web3 contract.
Contract¶
The exported class Contract
is here to simply pre-inject a contract ABI.
Parameters¶
provider
-AbstractSocketProvider | HttpProvider | CustomProvider | String
: A PWeb3.js provider.abi
-Array
: Contract ABIaccounts
- Accountsoptions
-Web3ModuleOptions
Example¶
import {MyABI, options} from '../folder/file.js';
import {Accounts} from 'web3-pi-accounts';
import {Contract} from 'web3-pi-contract';
export class MyContract extends Contract {
constructor(provider) {
super(provider, MyAbi, new Accounts(...), '0x0', options);
}
}
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Core Module¶
The Core Module
does provide the AbstractWeb3Module
to implement Web3 compatible modules.
AbstractWeb3Module¶
Source: AbstractWeb3Module
The AbstractWeb3Module
does have the following constructor parameters:
provider
-AbstractSocketProvider | HttpProvider | CustomProvider | String
The provider class or string.options
-Web3ModuleOptions
These are the defaultoptions
of a Web3 module. (optional)methodFactory
-AbstractMethodFactory
The AbstractMethodFactory will be used in the module proxy for the JSON-RPC method calls. (optional)net
-net.Socket
Thenet.Socket
object of the NodeJS net module. (optional)
Example¶
import {AbstractWeb3Module} from 'web3-core';
class Example extends AbstractWeb3Module {
/**
* @param {AbstractSocketProvider|HttpProvider|CustomProvider|String} provider
* @param {AbstractMethodFactory} methodFactory
* @param {Web3ModuleOptions} options
* @param {Net.Socket} nodeNet
*
* @constructor
*/
constructor(provider, net, methodFactory, options) {
super(provider, net, methodFactory, options;
}
}
Interface of the AbstractWeb3Module
class:
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Core Method Module¶
The Core Method Module
does provide all method classes and the abstract method factory which will be used in the AbstractWeb3Module
.
AbstractMethodFactory¶
Source: AbstractMethodFactory
The AbstractMethodFactory
does have the following constructor parameters:
utils
-Utils
TheUtils
object from theweb3-utils
module.formatters
-Object
The formatters object from theweb3-core-helpers
module.
Example¶
import {
AbstractMethodFactory,
GetBlockByNumberMethod,
ListeningMethod,
PeerCountMethod,
VersionMethod
} from 'web3-core-method';
class MethodFactory extends AbstractMethodFactory {
/**
* @param {Utils} utils
* @param {Object} formatters
*
* @constructor
*/
constructor(utils, formatters) {
super(utils, formatters);
this.methods = {
getId: VersionMethod,
getBlockByNumber: GetBlockByNumberMethod,
isListening: ListeningMethod,
getPeerCount: PeerCountMethod
};
}
}
AbstractMethod¶
Source: AbstractMethod
Because we are always adding new JSON-RPC methods do we just link the methods folder as resource.
Source: Methods
The provided method classes do have the following interface:
The AbstractMethod
class does have the following constructor parameters:
rpcMethod
-String
The JSON-RPC method name.parametersAmount
-Number
The amount of parameters this JSON-RPC method has.utils
-Utils
formatters
-Object
The formatters object.moduleInstance
-AbstractWeb3Module
The AbstractMethod
class is the base JSON-RPC method class and does provide the basic methods and properties for creating a
PWeb3.js compatible JSON-RPC method.
You’re able to overwrite these methods:
- execute(): PromiEvent
- afterExecution(response: any): void
- beforeExecution(moduleInstance: AbstractWeb3Module): void
- setArguments(arguments: IArguments): void
- getArguments(arguments: IArguments): {parameters: any[], callback: Function}
This example will show the usage of the setArguments(arguments: IArguments)
method.
It’s also possible to set the parameters and callback method directly over the parameters
and callback
property
of the method class.
Example¶
class Example extends AbstractWeb3Module {
constructor(...) {
// ...
}
sign() {
const method = new AbstractMethod('eth_sign', 2, utils, formatters, this);
method.setArguments(arguments)
return method.execute();
}
}
const example = new Example(...);
const response = await example.sign('0x0', 'message').
// > "response"
example.sign('0x0', 'message', (error, response) => {
console.log(response);
};
// > "response"
The AbstractMethod
class interface:
Type¶
The static readonly
property Type
will be used in the AbstractMethodFactory
class to determine how the class should get initiated.
Reserved types:
observed-transaction-method
-AbstractObservedTransactionMethod
eth-send-transaction-method
-EthSendTransactionMethod
Returns¶
string
- Example: observed-transaction-method
beforeExecution¶
method.beforeExecution(moduleInstance)
This method will be executed before the JSON-RPC request. It provides the possibility to customize the given parameters or other properties of the current method.
afterExecution¶
method.afterExecution(response)
This method will get executed when the provider returns with the response.
The afterExecution
method does provide us the possibility to map the response to the desired value.
Parameters¶
response
-any
The response from the provider.
execute¶
method.execute()
This method will execute the current method.
Returns¶
Promise<Object|string>|PromiEvent|string
rpcMethod¶
method.rpcMethod
This property will return the rpcMethod
string.
It will be used for the creation of the JSON-RPC payload object.
Returns¶
string
parametersAmount¶
method.parametersAmount
This property will return the parametersAmount
.
It will be used for validating the given parameters length and for the detection of the callback method.
Returns¶
number
parameters¶
method.parameters
This property does contain the given parameters
.
Use the setArguments()
method for setting the parameters and the callback method with the given IArguments
object.
Returns¶
any[]
callback¶
method.callback
This property does contain the given callback
.
Use the setArguments()
method for setting the parameters and the callback method with the given IArguments
object.
setArguments¶
method.setArguments(arguments)
This method will be used to set the given method arguments.
The setArguments
method will set the parameters
and callback
property.
Parameters¶
arguments
-Array
: Thearguments
of the function call.
getArguments¶
method.getArguments()
This method will be used to get the method arguments.
The getArguments
method will return a object with the properties parameters
and callback
.
Returns¶
Object
isHash¶
method.isHash(value)
This method will check if the given value is a string and starts with 0x
.
It will be used in several methods for deciding which JSON-RPC method should get executed.
Parameters¶
value
-string
AbstractObservedTransactionMethod¶
Source: AbstractObservedTransactionMethod
The AbstractObservedTransactionMethod
extends from the AbstractMethod <web3-module-abstract-method and
does have the following constructor parameters:
rpcMethod
-String
The JSON-RPC method name.parametersAmount
-Number
The amount of parameters this JSON-RPC method has.utils
-Object
The Utils object.formatters
-Object
The formatters object.transactionObserver
-TransactionObserver
TheTransactionObserver
class which defines the confirmation process of the transaction.
The AbstractObservedTransactionMethod
is the base method class for all “send transaction” methods.
Abstract methods:
Type¶
The static readonly
property Type
will be used in the AbstractMethodFactory
class to determine how the class should get initiated.
Reserved types:
observed-transaction-method
-AbstractObservedTransactionMethod
eth-send-transaction-method
-EthSendTransactionMethod
Returns¶
string
- Example: observed-transaction-method
beforeExecution¶
method.beforeExecution(moduleInstance)
This method will be executed before the JSON-RPC request. It provides the possibility to customize the given parameters or other properties of the current method.
afterExecution¶
method.afterExecution(response)
This method will get executed when the provider returns with the response.
The afterExecution
method does provide us the possibility to map the response to the desired value.
Parameters¶
response
-any
The response from the provider.
execute¶
method.execute()
This method will execute the current method.
Returns¶
Promise<Object|string>|PromiEvent|string
rpcMethod¶
method.rpcMethod
This property will return the rpcMethod
string.
It will be used for the creation of the JSON-RPC payload object.
Returns¶
string
parametersAmount¶
method.parametersAmount
This property will return the parametersAmount
.
It will be used for validating the given parameters length and for the detection of the callback method.
Returns¶
number
parameters¶
method.parameters
This property does contain the given parameters
.
Use the setArguments()
method for setting the parameters and the callback method with the given IArguments
object.
Returns¶
any[]
callback¶
method.callback
This property does contain the given callback
.
Use the setArguments()
method for setting the parameters and the callback method with the given IArguments
object.
setArguments¶
method.setArguments(arguments)
This method will be used to set the given method arguments.
The setArguments
method will set the parameters
and callback
property.
Parameters¶
arguments
-Array
: Thearguments
of the function call.
getArguments¶
method.getArguments()
This method will be used to get the method arguments.
The getArguments
method will return a object with the properties parameters
and callback
.
Returns¶
Object
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Core Subscriptions Module¶
The Core Subscriptions Module
does provide all the subscriptions classes to extend and execute them.
AbstractSubscription¶
Source: AbstractSubscription
The AbstractSubscription
class extends from the EventEmitter
object and does have the following constructor parameters:
- type -
String
The subscriptions typeeth_subscribe
orshh_subscribe
. - method -
String
The subscription method which is the first parameter in the JSON-RPC payload object. - options -
Object
The options object of the subscription. - formatters -
Object
The formatters object. - moduleInstance -
AbstractWeb3Module
AnAbstractWeb3Module
instance.
The AbstractSubscription
class is the base subscription class of all subscriptions.
You’re able to overwrite these methods:
- subscribe
- unsubscribe
- beforeSubscription
- onNewSubscriptionItem
subscribe¶
subscription.subscribe(callback)
This method will start the subscription.
Parameters¶
callback
-Function
unsubscribe¶
subscription.unsubscribe(callback)
This method will end the subscription.
Parameters¶
callback
-Function
beforeSubscription¶
subscription.beforeSubscription(moduleInstance)
This method will be executed before the subscription happens.
The beforeSubscription
method gives you the possibility to customize the subscription class before the request will be sent.
onNewSubscriptionItem¶
subscription.onNewSubscriptionItem(moduleInstance)
This method will be executed on each subscription item.
The onNewSubscriptionItem
method gives you the possibility to map the response.
Parameters¶
item
-any
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Admin Module¶
The web3-pi-admin
package allows you to interact with the Pchain node’s admin management.
import Web3 from 'pweb3';
import {Admin} from 'web3-pi-admin';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const admin = new Admin(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
addPeer¶
admin.addPeer(url, [callback])
Add an admin peer on the node that Web3 is connected to with its provider.
The RPC method used is admin_addPeer
.
Parameters¶
url
-String
: The enode URL of the remote peer.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if peer added successfully.
Example¶
admin.addPeer("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303")
.then(console.log);
> true
getDataDirectory¶
admin.getDataDirectory([, callback])
Provides absolute path of the running node, which is used by the node to store all its databases.
The RPC method used is admin_datadir
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- The path.
Example¶
admin.getDataDirectory()
.then(console.log);
> "/home/ubuntu/.pchain"
getNodeInfo¶
admin.getNodeInfo([, callback])
This property can be queried for all the information known about the running node at the networking granularity.
The RPC method used is admin_nodeInfo
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<object>
- The node information array.
enode
-string
: Enode address of the node.id
-string
: Node Id.listenAddr
-string
: lister host and port address.name
-string
: Name of the node, including client type, version, OS, custom datadiscovery
-number
: UDP listening port for discovery protocollistener
-number
: TCP listening port for RLPxdifficulty
-number
: Difficulty level applied during the nonce discovering of this block.genesis
-string
: Very first block hash.head
-string
: Current block hash.network
-number
: currently used Pchain networks ids.
Example¶
admin.getNodeInfo().then(console.log);
> {
enode: "enode://44826a5d6a55f88a18298bca4773fca5749cdc3a5c9f308aa7d810e9b31123f3e7c5fba0b1d70aac5308426f47df2a128a6747040a3815cc7dd7167d03be320d@[::]:30303",
id: "44826a5d6a55f88a18298bca4773fca5749cdc3a5c9f308aa7d810e9b31123f3e7c5fba0b1d70aac5308426f47df2a128a6747040a3815cc7dd7167d03be320d",
ip: "::",
listenAddr: "[::]:30303",
name: "pchain/v1.5.0-unstable/linux/go1.6",
ports: {
discovery: 30303,
listener: 30303
},
protocols: {
eth: {
difficulty: 17334254859343145000,
genesis: "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
head: "0xb83f73fbe6220c111136aefd27b160bf4a34085c65ba89f24246b3162257c36a",
network: 1
}
}
}
getPeers¶
admin.getPeers([, callback])
This will provide all the information known about the connected remote nodes at the networking granularity.
The RPC method used is admin_peers
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- List of all connected peers.
caps
-Array
: Protocols advertised by this peer.id
-string
: Peer node Id.name
-string
: Peer name of the node, including client type, version, OS, custom datalocalAddress
-string
: Local endpoint of the TCP data connection.remoteAddress
-string
: Remote endpoint of the TCP data connection.difficulty
-number
: Difficulty level applied during the nonce discovering of this block.head
-string
: Peer’s current block hash.version
-number
: Version number of the protocol.
Example¶
admin.getPeers().then(console.log);
> [{
caps: ["eth/61", "eth/62", "eth/63"],
id: "08a6b39263470c78d3e4f58e3c997cd2e7af623afce64656cfc56480babcea7a9138f3d09d7b9879344c2d2e457679e3655d4b56eaff5fd4fd7f147bdb045124",
name: "pchain/v1.5.0-unstable/linux/go1.5.1",
network: {
localAddress: "192.168.0.104:51068",
remoteAddress: "71.62.31.72:30303"
},
protocols: {
eth: {
difficulty: 17334052235346465000,
head: "5794b768dae6c6ee5366e6ca7662bdff2882576e09609bf778633e470e0e7852",
version: 63
}
}
}, /* ... */ {
caps: ["eth/61", "eth/62", "eth/63"],
id: "fcad9f6d3faf89a0908a11ddae9d4be3a1039108263b06c96171eb3b0f3ba85a7095a03bb65198c35a04829032d198759edfca9b63a8b69dc47a205d94fce7cc",
name: "pchain/v1.3.5-506c9277/linux/go1.4.2",
network: {
localAddress: "192.168.0.104:55968",
remoteAddress: "121.196.232.205:30303"
},
protocols: {
eth: {
difficulty: 17335165914080772000,
head: "5794b768dae6c6ee5366e6ca7662bdff2882576e09609bf778633e470e0e7852",
version: 63
}
}
}]
setSolc¶
admin.setSolc(string, [, callback])
Sets the Solidity compiler path to be used by the node when invoking the eth_compileSolidity RPC method
The RPC method used is admin_setSolc
.
Parameters¶
String
- The path of the solidity compiler.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
- A message.
Example¶
admin.setSolc("/usr/bin/solc").then(console.log);
> "solc, the solidity compiler commandline interface\nVersion: 0.3.2-0/Release-Linux/g++/Interpreter\n\npath: /usr/bin/solc"
startRPC¶
admin.startRPC(host, port, cors, apis [, callback])
It starts an HTTP based JSON RPC API webserver to handle client requests. All the parameters are optional.
The RPC method used is admin_startRPC
.
Parameters¶
host
-String
- (optional) The network interface to open the listener socket on (defaults to “localhost”).port
-number
- (optional) The network port to open the listener socket on (defaults to 6969).cors
-string
- (optional) Cross-origin resource sharing header to use (defaults to “”).apis
-string
- (optional) API modules to offer over this interface (defaults to “eth,net,web3”).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if Remote Procedure Call (RPC) got started.
Example¶
admin.startRPC("127.0.0.1", 6969)
.then(console.log('RPC Started!'));
> "RPC Started!"
startWS¶
admin.startWS(host, port, cors, apis [, callback])
It starts an WebSocket based JSON RPC API webserver to handle client requests. All the parameters are optional.
The RPC method used is admin_startWS
.
Parameters¶
host
-String
- (optional) The network interface to open the listener socket on (defaults to “localhost”).port
-number
- (optional) The network port to open the listener socket on (defaults to 6969).cors
-string
- (optional) Cross-origin resource sharing header to use (defaults to “”).apis
-string
- (optional) API modules to offer over this interface (defaults to “eth,net,web3”).Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if Web socket (WS) got started.
Example¶
admin.startRPC("127.0.0.1", 6970)
.then(console.log('WS Started!'));
> "WS Started!"
stopRPC¶
admin.stopRPC([, callback])
This method closes the currently open HTTP RPC endpoint. As the node can only have a single HTTP endpoint running, this method takes no parameters, returning a boolean whether the endpoint was closed or not.
The RPC method used is admin_stopRPC
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if Remote Procedure Call (RPC) successfully stopped.
Example¶
admin.stopRPC().then(console.log);
> true
stopWS¶
admin.stopWS([, callback])
This method closes the currently open WebSocket RPC endpoint. As the node can only have a single WebSocket endpoint running, this method takes no parameters, returning a boolean whether the endpoint was closed or not.
The RPC method used is admin_stopWS
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if Web Socket (WS) successfully stopped.
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Debug Module¶
The web3-pi-debug
module allows you to interact with the Pchain node’s debug methods.
import Web3 from 'pweb3';
import {Debug} from 'web3-pi-debug';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const debug = new Debug(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
setBackTraceAt¶
debug.setBackTraceAt(location, [callback])
Sets the logging backtrace location.
Parameters¶
location
-String
: The location is specified as<filename>:<line>
.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
admin.setBackTraceAt('filename.go:200').then(console.log);
blockProfile¶
debug.blockProfile(file, seconds, [, callback])
Turns on block profiling for the given duration and writes profile data to disk.
If a custom rate is desired, set the rate and write the profile manually using debug.writeBlockProfile
.
Parameters¶
1. file
- String
1. seconds
- Number|String
The seconds as Hex string or number.
2. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.blockProfile('file', 100).then(console.log);
> null
cpuProfile¶
debug.cpuProfile(file, seconds, [, callback])
Turns on CPU profiling for the given duration and writes profile data to disk.
Parameters¶
1. file
- String
1. seconds
- Number | String
The seconds as Hex string or number.
2. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.cpuProfile('file', 100).then(console.log);
> null
dumpBlock¶
debug.dumpBlock(blockNumber, [, callback])
Retrieves the state that corresponds to the block number and returns a list of accounts (including storage and code).
Parameters¶
blockNumber
-Number | String
The block number as Hex string or number.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.dumpBlock('file', 100).then(console.log);
{
root: "19f4ed94e188dd9c7eb04226bd240fa6b449401a6c656d6d2816a87ccaf206f1",
accounts: {
fff7ac99c8e4feb60c9750054bdc14ce1857f181: {
balance: "49358640978154672",
code: "",
codeHash: "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
nonce: 2,
root: "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
storage: {}
},
fffbca3a38c3c5fcb3adbb8e63c04c3e629aafce: {
balance: "3460945928",
code: "",
codeHash: "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
nonce: 657,
root: "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
storage: {}
}
},
}
getGCStats¶
debug.getGCStats([, callback])
Returns GC statistics. See https://golang.org/pkg/runtime/debug/#GCStats for information about the fields of the returned object.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getGCStats().then(console.log);
getBlockRlp¶
debug.getBlockRlp(number, [, callback])
Retrieves and returns the RLP encoded block by number.
Parameters¶
number
-Number | String
The block number as hex string or number.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
Example¶
debug.getBlockRlp(100).then(console.log);
> '0x0'
goTrace¶
debug.goTrace(file, seconds, [, callback])
Turns on Go runtime tracing for the given duration and writes trace data to disk.
Parameters¶
1. file
- String
1. seconds
- Number | String
The seconds as Hex string or number.
2. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.goTrace('file', 100).then(console.log);
> null
getMemStats¶
debug.getMemStats([, callback])
Returns detailed runtime memory statistics.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getMemStats().then(console.log);
> MemStats // MemStats object from Go
getSeedHash¶
debug.getSeedHash(number, [, callback])
Fetches and retrieves the seed hash of the block by number
Parameters¶
1. number
- Number | String
The block number as Hex string or number.
1. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
Example¶
debug.getSeedHash().then(console.log);
> '0x0'
setBlockProfileRate¶
debug.setBlockProfileRate(rate, [, callback])
Sets the rate (in samples/sec) of goroutine block profile data collection. A non-zero rate enables block profiling, setting it to zero stops the profile.
Collected profile data can be written using debug.writeBlockProfile
.
Parameters¶
number
-Number | String
The block profile rate as number or Hex string.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.setBlockProfileRate().then(console.log);
> null
setHead¶
debug.setHead(number, [, callback])
Sets the current head of the local chain by block number. Note, this is a destructive action and may severely damage your chain. Use with extreme caution.
Parameters¶
number
-Number | String
The block number as Hex string or number.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.setHead(100).then(console.log);
> null
getStacks¶
debug.getStacks([, callback])
Returns a printed representation of the stacks of all goroutines.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<string>
Example¶
debug.getStacks().then(console.log);
startCPUProfile¶
debug.startCPUProfile(file, [, callback])
Turns on CPU profiling indefinitely, writing to the given file.
Parameters¶
file
-String
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.startCPUProfile().then(console.log);
> null
stopCPUProfile¶
debug.stopCPUProfile([, callback])
Stops an ongoing CPU profile.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.stopCPUProfile().then(console.log);
> null
startGoTrace¶
debug.startGoTrace(file, [, callback])
Turns on CPU profiling indefinitely, writing to the given file.
Parameters¶
file
-String
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.startGoTrace('file').then(console.log);
> null
stopGoTrace¶
debug.stopGoTrace([, callback])
Stops writing the Go runtime trace.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.stopGoTrace().then(console.log);
> null
getBlockTrace¶
debug.getBlockTrace(blockRlp, options, [, callback])
The traceBlock method will return a full stack trace of all invoked opcodes of all transaction that were included included in this block. Note, the parent of this block must be present or it will fail.
Parameters¶
blockRlp
-String
RLP encoded blockoptions
-Object
The block trace objectFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getBlockTrace('0x0', {}).then(console.log);
> {
gas: 85301,
returnValue: "",
structLogs: [{...}]
}
getBlockTraceByNumber¶
debug.getBlockTraceByNumber(number, options, [, callback])
The traceBlockByNumber method accepts a block number and will replay the block that is already present in the database.
Parameters¶
number
-Number | String
The block number as Hex string or number.options
-Object
The block trace objectFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getBlockTraceByNumber(100, {}).then(console.log);
> {
gas: 85301,
returnValue: "",
structLogs: [{...}]
}
getBlockTraceByHash¶
debug.getBlockTraceByHash(hash, options, [, callback])
The traceBlockByHash accepts a block hash and will replay the block that is already present in the database.
Parameters¶
hash
-String
The block hashoptions
-Object
The block trace objectFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getBlockTraceByHash('0x0', {}).then(console.log);
> {
gas: 85301,
returnValue: "",
structLogs: [{...}]
}
getBlockTraceFromFile¶
debug.getBlockTraceFromFile(fileName, options, [, callback])
The traceBlockFromFile accepts a file containing the RLP of the block.
Parameters¶
fileName
-String
The file nameoptions
-Object
The block trace objectFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getBlockTraceFromFile('filename', {}).then(console.log);
> {
gas: 85301,
returnValue: "",
structLogs: [{...}]
}
getTransactionTrace¶
debug.getTransactionTrace(txHash, options, [, callback])
The traceTransaction debugging method will attempt to run the transaction in the exact same manner as it was executed on the network. It will replay any transaction that may have been executed prior to this one before it will finally attempt to execute the transaction that corresponds to the given hash.
In addition to the hash of the transaction you may give it a secondary optional argument, which specifies the options for this specific call.
The possible options are:
1. disableStorage
- boolean
Setting this to true will disable storage capture (default = false).
1. disableMemory
- boolean
Setting this to true will disable memory capture (default = false).
1. disableStack
- boolean
Setting this to true will disable stack capture (default = false).
1. tracer
- string
Setting this will enable JavaScript-based transaction tracing, described below. If set, the previous four arguments will be ignored.
1. timeout
- string
Overrides the default timeout of 5 seconds for JavaScript-based tracing calls
JSON-RPC specification for debug_traceTransaction
Parameters¶
txHash
-String
The transaction hashoptions
-Object
The block trace objectFunction
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
Example¶
debug.getTransactionTrace('0x0', {}).then(console.log);
> {
gas: 85301,
returnValue: "",
structLogs: [{...}]
}
setVerbosity¶
debug.setVerbosity(level, [, callback])
Sets the logging verbosity ceiling. Log messages with level up to and including the given level will be printed.
The verbosity of individual packages and source files can be raised using debug.setVerbosityPattern
.
Parameters¶
1. level
- Number | String
The verbosity level as Hex string or number.
1. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.setVerbosity(1).then(console.log);
> null
setVerbosityPattern¶
debug.setVerbosityPattern(pattern, [, callback])
Sets the logging verbosity pattern.
Parameters¶
1. pattern
- String
The verbosity pattern
1. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
// If you want to see messages from a particular Go package (directory) and all subdirectories, use:
debug.setVerbosityPattern('eth/*=6').then(console.log);
> null
// If you want to restrict messages to a particular package (e.g. p2p) but exclude subdirectories, use:
debug.setVerbosityPattern('p2p=6').then(console.log);
> null
// If you want to see log messages from a particular source file, use:
debug.setVerbosityPattern('server.go=6').then(console.log);
> null
// You can compose these basic patterns. If you want to see all output from peer.go in a package below eth
// (eth/peer.go, eth/downloader/peer.go) as well as output from package p2p at level <= 5, use:
debug.setVerbosityPattern('eth/*/peer.go=6,p2p=5').then(console.log);
> null
writeBlockProfile¶
debug.writeBlockProfile(file, [, callback])
Writes a goroutine blocking profile to the given file.
Parameters¶
1. file
- String
The file
1. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.writeBlockProfile('file').then(console.log);
> null
writeMemProfile¶
debug.writeMemProfile(file, [, callback])
Writes an allocation profile to the given file.
Parameters¶
1. file
- String
The file
1. Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<null>
Example¶
debug.writeBlockProfile('file').then(console.log);
> null
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
Miner Module¶
The web3-pi-miner
package allows you to remote control the node’s mining operation and set various mining specific settings.
import {Miner} from 'web3-pi-miner';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const miner = new Miner(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
setExtra¶
miner.setExtra(extraData, [, callback])
This method allows miner to set extra data during mining the block.
The RPC method used is miner_setExtra
.
Parameters¶
extraData
-String
: Extra data which is to be set.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if successful.
Example¶
miner.setExtra('Hello').then(console.log);
> true
setGasPrice¶
miner.setGasPrice(gasPrice, [, callback])
This method allows to set minimal accepted gas price during mining transactions. Any transactions that are below this limit will get excluded from the mining process.
The RPC method used is miner_setGasPrice
.
———-
Parameters
———-
Number | String
- Gas price.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if successful.
Example¶
miner.setGasPrice("0x4a817c800").then(console.log);
> true
miner.setGasPrice(20000000000).then(console.log);
> true
setEtherBase¶
miner.setEtherBase(address, [, callback])
Sets etherbase, where mining reward will go.
The RPC method used is miner_setEtherbase
.
Parameters¶
String
- address where mining reward will go.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if successful.
Example¶
miner.setEtherBase("0x3d80b31a78c30fc628f20b2c89d7ddbf6e53cedc").then(console.log);
> true
startMining¶
miner.startMining(miningThread, [, callback])
Start the CPU mining process with the given number of threads.
The RPC method used is miner_start
.
Parameters¶
Number | String
- Mining threads.Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<boolean>
- True if successful.
Example¶
miner.startMining('0x1').then(console.log);
> true
miner.startMining(1).then(console.log);
> true
Note
This documentation is under construction and the pweb3.js 1.0 stable version isn’t released. If you’re using a version v0.x.x of pweb3.js then please have a look at github.com/pweb3/wiki/wiki/JavaScript-API.
TxPool Module¶
The web3-pi-txpool
package gives you access to several non-standard RPC methods to inspect the contents of the transaction pool containing all the currently pending transactions as well as the ones queued for future processing.
import Web3 from 'web3';
import {TxPool} from 'web3-pi-txpool';
// "Web3.givenProvider" will be set if in an Pchain supported browser.
const txPool = new TxPool(Web3.givenProvider || 'ws://some.local-or-remote.node:6970/pchain', null, options);
options¶
An Web3 module does provide several options for configuring the transaction confirmation worklfow or for defining default values. These are the currently available option properties on a Web3 module:
Module Options¶
Example¶
import Web3 from 'pweb3';
const options = {
defaultAccount: '0x0',
defaultBlock: 'latest',
defaultGas: 1,
defaultGasPrice: 0,
transactionBlockTimeout: 50,
transactionConfirmationBlocks: 24,
transactionPollingTimeout: 480,
transactionSigner: new CustomTransactionSigner()
}
const web3 = new Web3('http://localhost:6969/pchain', null, options);
defaultBlock¶
web3.defaultBlock
web3.pi.defaultBlock
web3.shh.defaultBlock
...
The default block is used for all methods which have a block parameter. You can override it by passing the block parameter if a block is required.
Example:
- web3.pi.getBalance()
- web3.pi.getCode()
- web3.pi.getTransactionCount()
- web3.pi.getStorageAt()
- web3.pi.call()
- new web3.pi.Contract() -> myContract.methods.myMethod().call()
Returns¶
The defaultBlock
property can return the following values:
Number
: A block number"genesis"
-String
: The genesis block"latest"
-String
: The latest block (current head of the blockchain)"pending"
-String
: The currently mined block (including pending transactions)
Default is "latest"
defaultAccount¶
web3.defaultAccount
web3.pi.defaultAccount
web3.shh.defaultAccount
...
This default address is used as the default "from"
property, if no "from"
property is specified.
Returns¶
String
- 20 Bytes: Any Pchain address. You need to have the private key for that address in your node or keystore. (Default is undefined
)
defaultGasPrice¶
web3.defaultGasPrice
web3.pi.defaultGasPrice
web3.shh.defaultGasPrice
...
The default gas price which will be used for a request.
defaultGas¶
web3.defaultGas
web3.pi.defaultGas
web3.shh.defaultGas
...
The default gas which will be used for a request.
transactionBlockTimeout¶
web3.transactionBlockTimeout
web3.pi.transactionBlockTimeout
web3.shh.transactionBlockTimeout
...
The transactionBlockTimeout
will be used over a socket based connection. This option does define the amount of new blocks it should wait until the first confirmation happens.
This means the PromiEvent rejects with a timeout error when the timeout got exceeded.
transactionConfirmationBlocks¶
web3.transactionConfirmationBlocks
web3.pi.transactionConfirmationBlocks
web3.shh.transactionConfirmationBlocks
...
This defines the number of blocks it requires until a transaction will be handled as confirmed.
transactionPollingTimeout¶
web3.transactionPollingTimeout
web3.pi.transactionPollingTimeout
web3.shh.transactionPollingTimeout
...
The transactionPollingTimeout
will be used over a HTTP connection.
This option does define the amount of polls (each second) it should wait until the first confirmation happens.
transactionSigner¶
web3.pi.transactionSigner
...
The transactionSigner
property does provide us the possibility to customize the signing process
of the Pi
module and the related sub-modules.
The interface of a TransactionSigner
:
interface TransactionSigner {
sign(txObject: Transaction): Promise<SignedTransaction>
}
interface SignedTransaction {
messageHash: string,
v: string,
r: string,
s: string,
rawTransaction: string
}
Returns¶
TransactionSigner
: A JavaScript class of type TransactionSigner.
setProvider¶
web3.setProvider(myProvider)
web3.pi.setProvider(myProvider)
web3.shh.setProvider(myProvider)
...
Will change the provider for its module.
Note
When called on the umbrella package web3
it will also set the provider for all sub modules web3.pi
, web3.shh
, etc.
Parameters¶
Object|String
-provider
: a valid providerNet
-net
: (optional) the node.js Net package. This is only required for the IPC provider.
Returns¶
Boolean
Example¶
import Web3 from 'pweb3';
const web3 = new Web3('http://localhost:6969/pchain');
// or
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:6969/pchain'));
// change provider
web3.setProvider('ws://localhost:6970/pchain');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
providers¶
Web3.providers
Pi.providers
...
Contains the current available providers.
Value¶
Object
with the following providers:
Object
-HttpProvider
: The HTTP provider is deprecated, as it won’t work for subscriptions.Object
-WebsocketProvider
: The Websocket provider is the standard for usage in legacy browsers.Object
-IpcProvider
: The IPC provider is used node.js dapps when running a local node. Gives the most secure connection.
Example¶
const Web3 = require('pweb3');
// use the given Provider, e.g in Mist, or instantiate a new websocket provider
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:6970/pchain');
// or
const web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://localhost:6970/pchain'));
// Using the IPC provider in node.js
const net = require('net');
const web3 = new Web3('/Users/myuser/Library/Pchain/pchain.ipc', net); // mac os path
// or
const web3 = new Web3(new Web3.providers.IpcProvider('/Users/myuser/Library/Pchain/pchain.ipc', net)); // mac os path
// on windows the path is: '\\\\.\\pipe\\pchain.ipc'
// on linux the path is: '/users/myuser/.pchain/pchain.ipc'
givenProvider¶
Web3.givenProvider
web3.pi.givenProvider
web3.shh.givenProvider
...
When using pweb3.js in an Pchain compatible browser, it will set with the current native provider by that browser.
Will return the given provider by the (browser) environment, otherwise null
.
Returns¶
Object
: The given provider set or false
.
Example¶
web3.setProvider(Web3.givenProvider || 'ws://localhost:6970/pchain');
currentProvider¶
web3.currentProvider
web3.pi.currentProvider
web3.shh.currentProvider
...
Will return the current provider.
Returns¶
Object
: The current provider set.
Example¶
if (!web3.currentProvider) {
web3.setProvider('http://localhost:6969/pchain');
}
BatchRequest¶
new web3.BatchRequest()
new web3.pi.BatchRequest()
new web3.shh.BatchRequest()
...
Class to create and execute batch requests.
Parameters¶
none
Returns¶
Object
: With the following methods:
add(request)
: To add a request object to the batch call.execute()
: Will execute the batch request.
Example¶
const contract = new web3.pi.Contract(abi, address);
const batch = new web3.BatchRequest();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));
batch.add(contract.methods.balance(address).call.request({from: '0x0000000000000000000000000000000000000000'}));
batch.execute().then(...);
getContent¶
txPool.getContent([callback])
This API can be used to list the exact details of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future executions.
The RPC method used is txpool_content
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- The list of pending as well as queued transactions.
pending
-Object
: List of pending transactions with transaction details.
queued
-Object
: List of queued transactions with transaction details.
hash
32 Bytes -String
: Hash of the transaction.nonce
-Number
: The number of transactions made by the sender prior to this one.blockHash
32 Bytes -String
: Hash of the block where this transaction was in.null
when its pending.blockNumber
-Number
: Block number where this transaction was in.null
when its pending.transactionIndex
-Number
: Integer of the transactions index position in the block.null
when its pending.from
-String
: Address of the sender.to
-String
: Address of the receiver.null
when its a contract creation transaction.value
-String
: Value transferred in wei.gasPrice
-String
: The wei per unit of gas provided by the sender in wei.gas
-Number
: Gas provided by the sender.input
-String
: The data sent along with the transaction.
Example¶
txPool.getContent().then(console.log);
> {
pending: {
0x0216d5032f356960cd3749c31ab34eeff21b3395: {
806: [{
blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
blockNumber: null,
from: "0x0216d5032f356960cd3749c31ab34eeff21b3395",
gas: "0x5208",
gasPrice: "0xba43b7400",
hash: "0xaf953a2d01f55cfe080c0c94150a60105e8ac3d51153058a1f03dd239dd08586",
input: "0x",
nonce: "0x326",
to: "0x7f69a91a3cf4be60020fb58b893b7cbb65376db8",
transactionIndex: null,
value: "0x19a99f0cf456000"
}]
},
0x24d407e5a0b506e1cb2fae163100b5de01f5193c: {
34: [{
blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
blockNumber: null,
from: "0x24d407e5a0b506e1cb2fae163100b5de01f5193c",
gas: "0x44c72",
gasPrice: "0x4a817c800",
hash: "0xb5b8b853af32226755a65ba0602f7ed0e8be2211516153b75e9ed640a7d359fe",
input: "0xb61d27f600000000000000000000000024d407e5a0b506e1cb2fae163100b5de01f5193c00000000000000000000000000000000000000000000000053444835ec580000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
nonce: "0x22",
to: "0x7320785200f74861b69c49e4ab32399a71b34f1a",
transactionIndex: null,
value: "0x0"
}]
}
},
queued: {
0x976a3fc5d6f7d259ebfb4cc2ae75115475e9867c: {
3: [{
blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
blockNumber: null,
from: "0x976a3fc5d6f7d259ebfb4cc2ae75115475e9867c",
gas: "0x15f90",
gasPrice: "0x4a817c800",
hash: "0x57b30c59fc39a50e1cba90e3099286dfa5aaf60294a629240b5bbec6e2e66576",
input: "0x",
nonce: "0x3",
to: "0x346fb27de7e7370008f5da379f74dd49f5f2f80f",
transactionIndex: null,
value: "0x1f161421c8e0000"
}]
},
0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a: {
2: [{
blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
blockNumber: null,
from: "0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a",
gas: "0x15f90",
gasPrice: "0xba43b7400",
hash: "0x3a3c0698552eec2455ed3190eac3996feccc806970a4a056106deaf6ceb1e5e3",
input: "0x",
nonce: "0x2",
to: "0x24a461f25ee6a318bdef7f33de634a67bb67ac9d",
transactionIndex: null,
value: "0xebec21ee1da40000"
}]
}
}
}
getInspection¶
txPool.getInspection([, callback])
The property can be queried to list a textual summary of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future executions.
The RPC method used is txpool_inspect
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- The List of pending and queued transactions summary.
pending
-Object
: List of pending transactions with transaction details.queued
-Object
: List of queued transactions with transaction details.
Example¶
txPool.getInspection().then(console.log);
> {
pending: {
0x26588a9301b0428d95e6fc3a5024fce8bec12d51: {
31813: ["0x3375ee30428b2a71c428afa5e89e427905f95f7e: 0 wei + 500000 × 20000000000 gas"]
},
0x2a65aca4d5fc5b5c859090a6c34d164135398226: {
563662: ["0x958c1fa64b34db746925c6f8a3dd81128e40355e: 1051546810000000000 wei + 90000 × 20000000000 gas"],
563663: ["0x77517b1491a0299a44d668473411676f94e97e34: 1051190740000000000 wei + 90000 × 20000000000 gas"],
563664: ["0x3e2a7fe169c8f8eee251bb00d9fb6d304ce07d3a: 1050828950000000000 wei + 90000 × 20000000000 gas"],
563665: ["0xaf6c4695da477f8c663ea2d8b768ad82cb6a8522: 1050544770000000000 wei + 90000 × 20000000000 gas"],
563666: ["0x139b148094c50f4d20b01caf21b85edb711574db: 1048598530000000000 wei + 90000 × 20000000000 gas"],
563667: ["0x48b3bd66770b0d1eecefce090dafee36257538ae: 1048367260000000000 wei + 90000 × 20000000000 gas"],
563668: ["0x468569500925d53e06dd0993014ad166fd7dd381: 1048126690000000000 wei + 90000 × 20000000000 gas"],
563669: ["0x3dcb4c90477a4b8ff7190b79b524773cbe3be661: 1047965690000000000 wei + 90000 × 20000000000 gas"],
563670: ["0x6dfef5bc94b031407ffe71ae8076ca0fbf190963: 1047859050000000000 wei + 90000 × 20000000000 gas"]
},
0x9174e688d7de157c5c0583df424eaab2676ac162: {
3: ["0xbb9bc244d798123fde783fcc1c72d3bb8c189413: 30000000000000000000 wei + 85000 × 21000000000 gas"]
},
0xb18f9d01323e150096650ab989cfecd39d757aec: {
777: ["0xcd79c72690750f079ae6ab6ccd7e7aedc03c7720: 0 wei + 1000000 × 20000000000 gas"]
},
0xb2916c870cf66967b6510b76c07e9d13a5d23514: {
2: ["0x576f25199d60982a8f31a8dff4da8acb982e6aba: 26000000000000000000 wei + 90000 × 20000000000 gas"]
},
0xbc0ca4f217e052753614d6b019948824d0d8688b: {
0: ["0x2910543af39aba0cd09dbb2d50200b3e800a63d2: 1000000000000000000 wei + 50000 × 1171602790622 gas"]
},
0xea674fdde714fd979de3edf0f56aa9716b898ec8: {
70148: ["0xe39c55ead9f997f7fa20ebe40fb4649943d7db66: 1000767667434026200 wei + 90000 × 20000000000 gas"]
}
},
queued: {
0x0f6000de1578619320aba5e392706b131fb1de6f: {
6: ["0x8383534d0bcd0186d326c993031311c0ac0d9b2d: 9000000000000000000 wei + 21000 × 20000000000 gas"]
},
0x5b30608c678e1ac464a8994c3b33e5cdf3497112: {
6: ["0x9773547e27f8303c87089dc42d9288aa2b9d8f06: 50000000000000000000 wei + 90000 × 50000000000 gas"]
},
0x976a3fc5d6f7d259ebfb4cc2ae75115475e9867c: {
3: ["0x346fb27de7e7370008f5da379f74dd49f5f2f80f: 140000000000000000 wei + 90000 × 20000000000 gas"]
},
0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a: {
2: ["0x24a461f25ee6a318bdef7f33de634a67bb67ac9d: 17000000000000000000 wei + 90000 × 50000000000 gas"],
6: ["0x6368f3f8c2b42435d6c136757382e4a59436a681: 17990000000000000000 wei + 90000 × 20000000000 gas", "0x8db7b4e0ecb095fbd01dffa62010801296a9ac78: 16998950000000000000 wei + 90000 × 20000000000 gas"],
7: ["0x6368f3f8c2b42435d6c136757382e4a59436a681: 17900000000000000000 wei + 90000 × 20000000000 gas"]
}
}
}
getStatus¶
txPool.getStatus([, callback])
This will provide the number of transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future executions.
The RPC method used is txpool_status
.
Parameters¶
Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns¶
Promise<Object>
- A list of number of pending and queued transactions.
pending
-number
: Number of pending transactions.queued
-number
: Number of queued transactions.