PWeb3 Javascript API

Getting Started

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

Adding web3

First, you need to get web3.js into your project. This can be done using the following methods:

  • npm: npm install pweb3

  • bower: bower install pweb3

  • vanilla: link the dist./pweb3.min.js

Then you need to create a web3 instance, setting a provider. To make sure you don't overwrite the already set provider when in mist, check first if the web3 is available:

if (typeof web3 !== 'undefined') {
 web3 = new Web3(web3.currentProvider);
} else {
 // set the provider you want from Web3.providers
 web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545/pchain"));
}

After that, you can use the API of the web3 object.

Using callbacks

As this API is designed to work with a local RPC node, all its functions use synchronous HTTP requests by default. If you want to make an asynchronous request, you can pass an optional callback as the last parameter to most functions. All callbacks are using an error first callback style:

web3.pi.getBlock(48, function(error, result){
   if(!error)
       console.log(JSON.stringify(result));
   else
       console.error(error);
})

Batch requests

Batch requests allow queuing up requests and processing them at once. Note Batch requests are not faster! In fact making many requests at once will in some cases be faster, as requests are processed asynchronously. Batch requests are mainly useful to ensure the serial processing of requests.

var batch = web3.createBatch();
batch.add(web3.pi.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback));
batch.add(web3.pi.contract(abi).at(address).balance.request(address, callback2));
batch.execute();

A note on big numbers in web3.js

You will always get a BigNumber object for number values as JavaScript is not able to handle big numbers correctly. Look at the following examples:

"101010100324325345346456456456456456456"
// "101010100324325345346456456456456456456"
101010100324325345346456456456456456456
// 1.0101010032432535e+38

web3.js depends on the BigNumber Library and adds it automatically.

var balance = new BigNumber('131242344353464564564574574567456');
// or var balance = web3.pi.getBalance(someAddress);
balance.plus(21).toString(10); // toString(10) converts it to a number string
// "131242344353464564564574574567477"

The next example wouldn't work as we have more than 20 floating points, therefore it is recommended to always keep your balance in wei and only transform it to other units when presenting to the user:

var balance = new BigNumber('13124.234435346456466666457455567456');
 balance.plus(21).toString(10); // toString(10) converts it to a number string, but can only show upto 20 digits
// "13145.23443534645646666646" // your number will be truncated after the 20th digit

PWeb3 API Reference

web3

version

net

pi

db

shh

chain

tdm

del

Library

web3

The web3 object provides all methods.

Example

var Web3 = require('web3');
// create an instance of web3 using the HTTP provider.
// NOTE in mist web3 is already available, so check first if it's available before instantiating
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

Example using HTTP Basic Authentication

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545", 0, BasicAuthUsername, BasicAuthPassword));
//Note: HttpProvider takes 4 arguments (host, timeout, user, password)

web3.version.api

web3.version.api

Returns

String - The pchain js api version.

Example

var version = web3.version.api;
console.log(version); // "0.2.0"

web3.version.node

 web3.version.node
// or async
web3.version.getNode(callback(error, result){ ... })

Returns

String - The client/node version.

Example

var version = web3.version.node;
console.log(version); // "Mist/v0.9.3/darwin/go1.4.1"

web3.version.network

 web3.version.network
// or async
web3.version.getNetwork(callback(error, result){ ... })

Returns

String - The network protocol version.

Example

var version = web3.version.network;
console.log(version); // 54

web3.version.pchain

 web3.version.pchain
// or async
web3.version.pchain(callback(error, result){ ... })

Returns

String - The pchain protocol version.

Example

var version = web3.version.pchain;
console.log(version); // 60

web3.version.whisper

 web3.version.whisper
// or async
web3.version.getWhisper(callback(error, result){ ... })

Returns

String - The whisper protocol version.

Example

var version = web3.version.whisper;
console.log(version); // 20

web3.isConnected

 web3.isConnected()

Should be called to check if a connection to a node exists

Parameters

none

Returns

Boolean

Example

if(!web3.isConnected()) {
 
  // show some dialog to ask the user to start a node
} else {

  // start web3 filters, calls, etc
 
}

web3.setProvider

 web3.setProvider(provider)

Should be called to set provider.

Parameters

none

Returns

undefined

Example

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545')); // 8080 for cpp/AZ, 8545 for go/mist

web3.currentProvider

 web3.currentProvider

Will contain the current provider, if one is set. This can be used to check if mist etc. has set already a provider.

Returns

Object - The provider set or null;

Example

// Check if mist etc. already set a provider
if(!web3.currentProvider)
   web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));

web3.reset

 web3.reset(keepIsSyncing)

Should be called to reset state of web3. Resets everything except manager. Uninstalls all filters. Stops polling.

Parameters

  1. Boolean - If true it will uninstall all filters, but will keep the web3.pi.isSyncing() polls

Returns

undefined

Example

web3.reset();

web3.sha3

 web3.sha3(string [, options])

Parameters

  1. String - The string to hash using the Keccak-256 SHA3 algorithm

  2. Object - (optional) Set encoding to hex if the string to hash is encoded in hex. A leading 0x will be automatically ignored.

Returns

String - The Keccak-256 SHA3 of the given data.

Example

var hash = web3.sha3("Some string to be hashed");
console.log(hash); // "0xed973b234cf2238052c9ac87072c71bcf33abc1bbd721018e0cca448ef79b379"
var hashOfHash = web3.sha3(hash, {encoding: 'hex'});
console.log(hashOfHash); // "0x85dd39c91a64167ba20732b228251e67caed1462d4bcf036af88dc6856d0fdcc"

web3.getVoteHash

 web3.getVoteHash(from, pubKey,amount,salt)

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. pubkey: hex string, 128 Bytes - the BLS Public Key who triggers the action,How To Get Your Pubkey

  3. amount: hex string - the amount of vote

  4. salt: string - salt string

Returns

String - The Keccak-256 SHA3 of the given data.

Example

var from = "4CACBCBF218679DCC9574A90A2061BCA4A8D8B6C";
var pubkey = "7315DF293B07C52EF6C1FC05018A1CA4FB630F6DBD4F1216804FEDDC2F04CD2932A5AB72B6910145ED97A5FFA0CDCB818F928A8921FDAE8033BF4259AC3400552065951D2440C25A6994367E1DC60EE34B34CB85CD95304B24F9A07473163F1F24C79AC5CBEC240B5EAA80907F6B3EDD44FD8341BF6EB8179334105FEDE6E790";
var amount = "0x1f4";
var salt = "ABCD";

var hash  = web3.getVoteHash(from,pubkey,amount,salt);
// "0x78701448b4ee6fc4edc940266bcebc3e21b1b3c208957cb081cfba5a629beb72"

web3.toHex

 web3.toHex(mixed);

Converts any value into HEX.

Parameters

  1. String|Number|Object|Array|BigNumber - The value to parse to HEX. If its an object or array it will be JSON.stringify first. If its a BigNumber it will make it the HEX value of a number.

Returns

String - The hex string of mixed.

Example

var str = web3.toHex({test: 'test'});
console.log(str); // '0x7b2274657374223a2274657374227d'

web3.toAscii

 web3.toAscii(hexString);

Converts a HEX string into a ASCII string.

Parameters

  1. String - A HEX string to be converted to ascii.

Returns

String - An ASCII string made from the given hexString.

Example

var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "pchain"

web3.fromAscii

 web3.fromAscii(string);

Converts any ASCII string to a HEX string.

Parameters

  1. String - An ASCII string to be converted to HEX.

Returns

String - The converted HEX string.

Example

var str = web3.fromAscii('pchain');
console.log(str); // "0x657468657265756d"

web3.toDecimal

 web3.toDecimal(hexString);

Converts a HEX string to its number representation.

Parameters

  1. String - A HEX string to be converted to a number.

Returns

Number - The number representing the data hexString.

Example

var number = web3.toDecimal('0x15');
console.log(number); // 21

web3.fromDecimal

 web3.fromDecimal(number);

Converts a number or number string to its HEX representation.

Parameters

  1. Number|String - A number to be converted to a HEX string.

Returns

String - The HEX string representing of the given number.

Example

var value = web3.fromDecimal('21');
console.log(value); // "0x15"

web3.fromWei

 web3.fromWei(number, unit)

Converts a number of wei into the following pchain units:

  • Gwei

  • Kwei

  • Mwei/babbage/pi/femtoether

  • pi

  • finney/gpi/grand/gwei

  • kpi/kwei/lovelace/mether/micro

  • microether/milli/milliether

  • mwei/nano/nanoether

  • noether

  • picoether/shannon

  • szabo

  • tpi

  • wei

Parameters

  1. Number|String|BigNumber - A number or BigNumber instance.

  2. String - One of the above pi units.

Returns

String|BigNumber - Either a number string, or a BigNumber instance, depending on the given number parameter.

Example

var value = web3.fromWei('21000000000000', 'finney');
console.log(value); // "0.021"

web3.toWei

 web3.toWei(number, unit)

Converts an pchain unit into wei. Possible units are:

  • kwei/ada

  • mwei/babbage

  • gwei/shannon

  • szabo

  • finney

  • pi

  • kpi/grand/einstein

  • mpi

  • gpi

  • tpi

Parameters

  1. Number|String|BigNumber - A number or BigNumber instance.

  2. String - One of the above pi units.

Returns

String|BigNumber - Either a number string, or a BigNumber instance, depending on the given number parameter.

Example

var value = web3.toWei('1', 'pi');
console.log(value); // "1000000000000000000"

web3.toBigNumber

 web3.toBigNumber(numberOrHexString);

Converts a given number into a BigNumber instance. See the note on BigNumber.

Parameters

  1. Number|String - A number, number string or HEX string of a number.

Returns

BigNumber - A BigNumber instance representing the given value.

Example

var value = web3.toBigNumber('200000000000000000000001');
console.log(value); // instanceOf BigNumber
console.log(value.toNumber()); // 2.0000000000000002e+23
console.log(value.toString(10)); // '200000000000000000000001'

web3.isAddress

 web3.isAddress(HexString);

Checks if the given string is an address.

Parameters

  1. String - A HEX string.

Returns

Boolean - false if it's not on a valid address format. Returns true if it's an all lowercase or all uppercase valid address. If it's a mixed case address, it checks using web3.isChecksumAddress().

Example

var isAddress = web3.isAddress("0x8888f1f195afa192cfee860698584c030f4c9db1");
console.log(isAddress); // true

web3.net.listening

 web3.net.listening
// or async
web3.net.getListening(callback(error, result){ ... })

This property is read only and says whether the node is actively listening for network connections or not.

Returns

Boolean - true if the client is actively listening for network connections, otherwise false.

Example

var listening = web3.net.listening;
console.log(listening); // true of false

web3.net.peerCount

 web3.net.peerCount
// or async
web3.net.getPeerCount(callback(error, result){ ... })

This property is read only and returns the number of connected peers.

Returns

Number - The number of peers currently connected to the client.

Example

var peerCount = web3.net.peerCount;
console.log(peerCount); // 4

web3.pi

Contains the pchain blockchain related methods.

Example

var eth = web3.pi;

web3.pi.defaultAccount

 web3.pi.defaultAccount

This default address is used for the following methods (optionally you can overwrite it by specifying the from property):

Values

String, 20 Bytes - Any address you own, or where you have the private key for. Default is undefined.

Returns

String, 20 Bytes - The currently set default address.

Example

var defaultAccount = web3.pi.defaultAccount;
console.log(defaultAccount); // ''
// set the default account
web3.pi.defaultAccount = '0x8888f1f195afa192cfee860698584c030f4c9db1';

web3.pi.defaultBlock

 web3.pi.defaultBlock

This default block is used for the following methods (optionally you can override it by passing the defaultBlock parameter):

Values

Default block parameters can be one of the following:

  • Number - a block number

  • String - "earliest", the genesis block

  • String - "latest", the latest block (current head of the blockchain)

  • String - "pending", the currently mined block (including pending transactions) Default is latest

Returns

Number|String - The default block number to use when querying a state.

Example

var defaultBlock = web3.pi.defaultBlock;
console.log(defaultBlock); // 'latest'
// set the default block
web3.pi.defaultBlock = 231;

web3.pi.syncing

 web3.pi.syncing
// or async
web3.pi.getSyncing(callback(error, result){ ... })

This property is read only and returns the either a sync object, when the node is syncing or false.

Returns

Object|Boolean - A sync object as follows, when the node is currently syncing or false:

  • startingBlock: Number - The block number where the sync started.

  • currentBlock: Number - The block number where at which block the node currently synced to already.

  • highestBlock: Number - The estimated block number to sync to.

Example

var sync = web3.pi.syncing;
console.log(sync);
/*
{
  startingBlock: 300,
  currentBlock: 312,
  highestBlock: 512
}
*/

web3.pi.isSyncing

 web3.pi.isSyncing(callback);

This convenience function calls the callback everytime a sync starts, updates and stops.

Returns

Object - a isSyncing object with the following methods:

  • syncing.addCallback(): Adds another callback, which will be called when the node starts or stops syncing.

  • syncing.stopWatching(): Stops the syncing callbacks.

Callback return value

  • Boolean - The callback will be fired with true when the syncing starts and with false when it stopped.

  • Object - While syncing it will return the syncing object:

    • startingBlock: Number - The block number where the sync started.

    • currentBlock: Number - The block number where at which block the node currently synced to already.

    • highestBlock: Number - The estimated block number to sync to.

Example

web3.pi.isSyncing(function(error, sync){
   if(!error) {
       // stop all app activity
       if(sync === true) {
          // we use `true`, so it stops all filters, but not the web3.pi.syncing polling
          web3.reset(true);
       
       // show sync info
       } else if(sync) {
          console.log(sync.currentBlock);
       
       // re-gain app operation
       } else {
           // run your app init function...
       }
   }
});

web3.pi.coinbase

 web3.pi.coinbase
// or async
web3.pi.getCoinbase(callback(error, result){ ... })

This property is read only and returns the coinbase address where the mining rewards go to.

Returns

String - The coinbase address of the client.

Example

var coinbase = web3.pi.coinbase;
console.log(coinbase); // "0x407d73d8a49eeb85d32cf465507dd71d507100c1"

web3.pi.mining

 web3.pi.mining
// or async
web3.pi.getMining(callback(error, result){ ... })

This property is read only and says whether the node is mining or not.

Returns

Boolean - true if the client is mining, otherwise false.

Example

var mining = web3.pi.mining;
console.log(mining); // true or false

web3.pi.hashrate

 web3.pi.hashrate
// or async
web3.pi.getHashrate(callback(error, result){ ... })

This property is read only and returns the number of hashes per second that the node is mining with.

Returns

Number - number of hashes per second.

Example

var hashrate = web3.pi.hashrate;
console.log(hashrate); // 493736

web3.pi.gasPrice

 web3.pi.gasPrice
// or async
web3.pi.getGasPrice(callback(error, result){ ... })

This property is read only and returns the current gas price. The gas price is determined by the x latest blocks median gas price.

Returns

BigNumber - A BigNumber instance of the current gas price in wei. See the note on BigNumber.

Example

var gasPrice = web3.pi.gasPrice;
console.log(gasPrice.toString(10)); // "10000000000000"

web3.pi.accounts

 web3.pi.accounts
// or async
web3.pi.getAccounts(callback(error, result){ ... })

This property is read only and returns a list of accounts the node controls.

Returns

Array - An array of addresses controlled by client.

Example

var accounts = web3.pi.accounts;
console.log(accounts); // ["0x407d73d8a49eeb85d32cf465507dd71d507100c1"] 

web3.pi.blockNumber

 web3.pi.blockNumber
// or async
web3.pi.getBlockNumber(callback(error, result){ ... })

This property is read only and returns the current block number.

Returns

Number - The number of the most recent block.

Example

var number = web3.pi.blockNumber;
console.log(number); // 2744

web3.pi.register

 web3.pi.register(addressHexString [, callback])

(Not Implemented yet) Registers the given address to be included in web3.pi.accounts. This allows non-private-key owned accounts to be associated as an owned account (e.g., contract wallets).

Parameters

  1. String - The address to register

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

?

Example

web3.pi.register("0x407d73d8a49eeb85d32cf465507dd71d507100ca")

web3.pi.unRegister

  web3.pi.unRegister(addressHexString [, callback])

(Not Implemented yet) Unregisters a given address.

Parameters

  1. String - The address to unregister.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

?

Example

web3.pi.unregister("0x407d73d8a49eeb85d32cf465507dd71d507100ca")

web3.pi.getBalance

 web3.pi.getBalance(addressHexString [, defaultBlock] [, callback])

Get the balance of an address at a given block.

Parameters

  1. String - The address to get the balance of.

  2. Number|String - (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - A BigNumber instance of the current balance for the given address in wei. See the note on BigNumber.

Example

var balance = web3.pi.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1");
console.log(balance); // instanceof BigNumber
console.log(balance.toString(10)); // '1000000000000'
console.log(balance.toNumber()); // 1000000000000

web3.pi.getFullBalance

 web3.pi.getFullBalance(from,blockNumber,fullProxied [, callback])

Get the balance of an address at a given block.

parameters

  1. from - address, 20 Bytes - address to check for balance.

  2. blockNumber - QUANTITY|TAG - integer block number, or the string "latest", "earliest" or "pending".

  3. 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"
           }
       }
   }

web3.pi.getStorageAt

 web3.pi.getStorageAt(addressHexString, position [, defaultBlock] [, callback])

Get the storage at a specific position of an address.

Parameters

  1. String - The address to get the storage from.

  2. Number - The index position of the storage.

  3. Number|String - (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.

  4. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The value in storage at the given position.

Example

var state = web3.pi.getStorageAt("0x407d73d8a49eeb85d32cf465507dd71d507100c1", 0);
console.log(state); // "0x03"

web3.pi.getCode

 web3.pi.getCode(addressHexString [, defaultBlock] [, callback])

Get the code at a specific address.

Parameters

  1. String - The address to get the code from.

  2. Number|String - (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The data at given address addressHexString.

Example

var code = web3.pi.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8");
console.log(code); // "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056"

web3.pi.getBlock

  web3.pi.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])

Returns a block matching the block number or block hash.

Parameters

  1. String|Number - The block number or hash. Or the string "earliest", "latest" or "pending" as in the default block parameter.

  2. Boolean - (optional, default false) If true, the returned block will contain all transactions as objects, if false it will only contains the transaction hashes.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Object - The block object:

  • number: Number - the block number. null when its pending block.

  • hash: String, 32 Bytes - hash of the block. null when its pending block.

  • parentHash: String, 32 Bytes - hash of the parent block.

  • nonce: String, 8 Bytes - hash of the generated proof-of-work. null when its pending block.

  • sha3Uncles: String, 32 Bytes - SHA3 of the uncles data in the block.

  • logsBloom: String, 256 Bytes - the bloom filter for the logs of the block. null when its pending block.

  • transactionsRoot: String, 32 Bytes - the root of the transaction trie of the block

  • stateRoot: String, 32 Bytes - the root of the final state trie of the block.

  • miner: String, 20 Bytes - the address of the beneficiary to whom the mining rewards were given.

  • difficulty: BigNumber - integer of the difficulty for this block.

  • totalDifficulty: BigNumber - 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 - the unix timestamp for when the block was collated.

  • transactions: Array - Array of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter.

  • uncles: Array - Array of uncle hashes.

Example

var info = web3.pi.getBlock(3150);
console.log(info);
/*
{
 "number": 3,
 "hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
 "parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88",
 "nonce": "0xfb6e1a62d119228b",
 "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
 "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
 "transactionsRoot": "0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee",
 "stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb",
 "miner": "0x8888f1f195afa192cfee860698584c030f4c9db1",
 "difficulty": BigNumber,
 "totalDifficulty": BigNumber,
 "size": 616,
 "extraData": "0x",
 "gasLimit": 3141592,
 "gasUsed": 21662,
 "timestamp": 1429287689,
 "transactions": [
   "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
 ],
 "uncles": []
}
*/

web3.pi.getBlockTransactionCount

 web3.pi.getBlockTransactionCount(hashStringOrBlockNumber [, callback])

Returns the number of transaction in a given block.

Parameters

  1. String|Number - The block number or hash. Or the string "earliest", "latest" or "pending" as in the default block parameter.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Number - The number of transactions in the given block.

Example

var number = web3.pi.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1");
console.log(number); // 1

web3.pi.getUncle

 web3.pi.getUncle(blockHashStringOrNumber, uncleNumber [, returnTransactionObjects] [, callback])

Returns a blocks uncle by a given uncle index position.

Parameters

  1. String|Number - The block number or hash. Or the string "earliest", "latest" or "pending" as in the default block parameter.

  2. Number - The index position of the uncle.

  3. Boolean - (optional, default false) If true, the returned block will contain all transactions as objects, if false it will only contains the transaction hashes.

  4. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Object - the returned uncle. For a return value see web3.pi.getBlock(). Note: An uncle doesn't contain individual transactions.

Example

var uncle = web3.pi.getUncle(500, 0);
console.log(uncle); // see web3.pi.getBlock

web3.pi.getTransaction

 web3.pi.getTransaction(transactionHash [, callback])

Returns a transaction matching the given transaction hash.

Parameters

  1. String - The transaction hash.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Object - A transaction object its hash transactionHash:

  • hash: String, 32 Bytes - hash of the transaction.

  • nonce: Number - the number of transactions made by the sender prior to this one.

  • blockHash: String, 32 Bytes - 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, 20 Bytes - address of the sender.

  • to: String, 20 Bytes - address of the receiver. null when its a contract creation transaction.

  • value: BigNumber - value transferred in Wei.

  • gasPrice: BigNumber - gas price provided by the sender in Wei.

  • gas: Number - gas provided by the sender.

  • input: String - the data sent along with the transaction.

Example

var transaction = web3.pi.getTransaction('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b');
console.log(transaction);
/*
{
 "hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
 "nonce": 2,
 "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
 "blockNumber": 3,
 "transactionIndex": 0,
 "from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
 "to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
 "value": BigNumber,
 "gas": 314159,
 "gasPrice": BigNumber,
 "input": "0x57cb2fc4"
}
*/

web3.pi.getTransactionFromBlock

 getTransactionFromBlock(hashStringOrNumber, indexNumber [, callback])

Returns a transaction based on a block hash or number and the transactions index position.

Parameters

  1. String - A block number or hash. Or the string "earliest", "latest" or "pending" as in the default block parameter.

  2. Number - The transactions index position.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Object - A transaction object, see web3.pi.getTransaction:

Example

var transaction = web3.pi.getTransactionFromBlock('0x4534534534', 2);
console.log(transaction); // see web3.pi.getTransaction

web3.pi.getTransactionReceipt

 web3.pi.getTransactionReceipt(hashString [, callback])

Returns the receipt of a transaction by transaction hash. Note That the receipt is not available for pending transactions.

Parameters

  1. String - The transaction hash.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Object - A transaction receipt object, or null when no receipt was found:

  • blockHash: String, 32 Bytes - hash of the block where this transaction was in.

  • blockNumber: Number - block number where this transaction was in.

  • transactionHash: String, 32 Bytes - hash of the transaction.

  • transactionIndex: Number - integer of the transactions index position in the block.

  • from: String, 20 Bytes - address of the sender.

  • to: String, 20 Bytes - address of the receiver. null when its a contract creation transaction.

  • 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.

  • contractAddress : String - 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null.

  • logs : Array - Array of log objects, which this transaction generated.

  • status : String - '0x0' indicates transaction failure , '0x1' indicates transaction succeeded.

Example

var receipt = web3.pi.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b');
console.log(receipt);
{
  "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
  "transactionIndex": 0,
  "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
  "blockNumber": 3,
  "contractAddress": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
  "cumulativeGasUsed": 314159,
  "gasUsed": 30234,
  "logs": [{
         // logs as returned by getFilterLogs, etc.
     }, ...],
  "status": "0x1"
}

web3.pi.getTransactionCount

 web3.pi.getTransactionCount(addressHexString [, defaultBlock] [, callback])

Get the numbers of transactions sent from this address.

Parameters

  1. String - The address to get the numbers of transactions from.

  2. Number|String - (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Number - The number of transactions sent from the given address.

Example

var number = web3.pi.getTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1");
console.log(number); // 1

web3.pi.sendTransaction

 web3.pi.sendTransaction(transactionObject [, callback])

Sends a transaction to the network.

Parameters

  1. Object - The transaction object to send:

  • from: String - The address for the sending account. Uses the web3.pi.defaultAccount property, if not specified.

  • to: String - (optional) The destination address of the message, left undefined for a contract-creation transaction.

  • value: Number|String|BigNumber - (optional) The value transferred for the transaction in Wei, also the endowment if it's a contract-creation transaction.

  • gas: Number|String|BigNumber - (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).

  • gasPrice: Number|String|BigNumber - (optional, default: To-Be-Determined) The price of gas for this transaction in wei, defaults to the mean network gas price.

  • data: String - (optional) Either a byte string containing the associated data of the message, 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.

  1. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The 32 Bytes transaction hash as HEX string. If the transaction was a contract creation use web3.pi.getTransactionReceipt() to get the contract address, after the transaction was mined.

Example

// compiled solidity source code using https://chriseth.github.io/cpp-pchain/
var code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";
web3.pi.sendTransaction({data: code}, function(err, transactionHash) {
 if (!err)
   console.log(transactionHash); // "0x7f9fade1c0d57a7af66ab4ead7c2eb7b11a91385"
});

web3.pi.sendRawTransaction

 web3.pi.sendRawTransaction(signedTransactionData [, callback])

Sends an already signed transaction. For example can be signed using: https://github.com/SilentCicero/pchainjs-accounts

Parameters

  1. String - Signed transaction data in HEX format

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The 32 Bytes transaction hash as HEX string. If the transaction was a contract creation use web3.pi.getTransactionReceipt() to get the contract address, after the transaction was mined.

Example

var Tx = require('pchainjs-tx');
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')
var rawTx = {
 nonce: '0x00',
 gasPrice: '0x09184e72a000', 
 gasLimit: '0x2710',
 to: '0x0000000000000000000000000000000000000000', 
 value: '0x00', 
 data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();
//console.log(serializedTx.toString('hex'));
//f889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f
web3.pi.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
 if (!err)
   console.log(hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385"
});

web3.pi.sign

 web3.pi.sign(address, dataToSign, [, callback])

Signs data from a specific account. This account needs to be unlocked.

Parameters

  1. String - Address to sign with.

  2. String - Data to sign.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The signed data. After the hex prefix, characters correspond to ECDSA values like this:

r = signature[0:64]
s = signature[64:128]
v = signature[128:130]

Note that if you are using ecrecover, v will be either "00" or "01". As a result, in order to use this value, you will have to parse it to an integer and then add 27. This will result in either a 27 or a 28.

Example

var result = web3.pi.sign("0x135a7de83802408321b74c322f8558db1679ac20",
   "0x9dd2c369a187b4e6b9c402f030e50743e619301ea62aa4c0737d4ef7e10a3d49"); // second argument is web3.sha3("xyz")
console.log(result); // "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"

web3.pi.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

  1. Object - A transaction object see web3.pi.sendTransaction, with the difference that for calls the from property is optional as well.

  2. Number|String - (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.

  3. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The returned data of the call, e.g. a codes functions return value.

Example

var result = web3.pi.call({
   to: "0xc4abd0339eb8d57087278718986382264244252f", 
   data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
});
console.log(result); // "0x0000000000000000000000000000000000000000000000000000000000000015"

web3.pi.estimateGas

 web3.pi.estimateGas(callObject [, callback])

Executes a message call or transaction, which is directly executed in the VM of the node, but never mined into the blockchain and returns the amount of the gas used.

Parameters

See web3.pi.sendTransaction, except that all properties are optional.

Returns

Number - the used gas for the simulated call/transaction.

Example

var result = web3.pi.estimateGas({
   to: "0xc4abd0339eb8d57087278718986382264244252f", 
   data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
});
console.log(result); // "0x0000000000000000000000000000000000000000000000000000000000000015"

web3.pi.filter

// can be 'latest' or 'pending'
var filter = web3.pi.filter(filterString);
// OR object are log filter options
var filter = web3.pi.filter(options);
// watch for changes
filter.watch(function(error, result){
 if (!error)
   console.log(result);
});
// Additionally you can start watching right away, by passing a callback:
web3.pi.filter(options, function(error, result){
 if (!error)
   console.log(result);
});

Parameters

  1. String|Object - The string "latest" or "pending" to watch for changes in the latest block or pending transactions respectively. Or a filter options object 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 - An address or a list of addresses to only get logs from particular account(s).

  • topics: Array of Strings - An array of values which must each appear in the log entries. The order is important, if you want to leave topics out use null, e.g. [null, '0x00...']. You can also pass another array for each topic with options for that topic e.g. [null, ['option1', 'option2']]

Returns

Object - A filter object with the following methods:

  • filter.get(callback): Returns all of the log entries that fit the filter.

  • filter.watch(callback): Watches for state changes that fit the filter and calls the callback. See this note for details.

  • filter.stopWatching(): Stops the watch and uninstalls the filter in the node. Should always be called once it is done.

Watch callback return value

  • String - When using the "latest" parameter, it returns the block hash of the last incoming block.

  • String - When using the "pending" parameter, it returns a transaction hash of the most recent pending transaction.

  • Object - When using manual filter options, it returns a log object as follows:

    • logIndex: Number - integer of the log index position in the block. null when its pending log.

    • transactionIndex: Number - integer of the transactions index position log was created from. null when its pending log.

    • transactionHash: String, 32 Bytes - hash of the transactions this log was created from. null when its pending log.

    • blockHash: String, 32 Bytes - hash of the block where this log was in. null when its pending. null when its pending log.

    • blockNumber: Number - the block number where this log was in. null when its pending. null when its pending log.

    • address: String, 32 Bytes - address from which this log originated.

    • data: String - contains one or more 32 Bytes non-indexed arguments of the log.

    • topics: Array of Strings - Array of 0 to 4 32 Bytes DATA of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except if you declared the event with the anonymous specifier.)

    • type: STRING - pending when the log is pending. mined if log is already mined. Note For event filter return values see Contract Events

Example

var filter = web3.pi.filter({toBlock:'pending'});
filter.watch(function (error, log) {
 console.log(log); //  {"address":"0x0000000000000000000000000000000000000000", "data":"0x0000000000000000000000000000000000000000000000000000000000000000", ...}
});
// get all past logs again.
var myResults = filter.get(function(error, logs){ ... });
...
// stops and uninstalls the filter
filter.stopWatching();

web3.pi.contract

 web3.pi.contract(abiArray)

Creates a contract object for a solidity contract, which can be used to initiate contracts on an address. You can read more about events here.

Parameters

  1. Array - ABI array with descriptions of functions and events of the contract.

Returns

Object - A contract object, which can be initiated as follows:

var MyContract = web3.pi.contract(abiArray);
// instantiate by address
var contractInstance = MyContract.at(address);
// deploy new contract
var contractInstance = MyContract.new([constructorParam1] [, constructorParam2], {data: '0x12345...', from: myAccount, gas: 1000000});
// Get the data to deploy the contract manually
var contractData = MyContract.new.getData([constructorParam1] [, constructorParam2], {data: '0x12345...'});
// contractData = '0x12345643213456000000000023434234'

And then you can either initiate an existing contract on an address, or deploy the contract using the compiled byte code:

// Instantiate from an existing address:
var myContractInstance = MyContract.at(myContractAddress);
// Or deploy a new contract:
// Deploy the contract asynchronous from Solidity file:
...
const fs = require("fs");
const solc = require('solc')
let source = fs.readFileSync('nameContract.sol', 'utf8');
let compiledContract = solc.compile(source, 1);
let abi = compiledContract.contracts['nameContract'].interface;
let bytecode = compiledContract.contracts['nameContract'].bytecode;
let gasEstimate = web3.pi.estimateGas({data: bytecode});
let MyContract = web3.pi.contract(JSON.parse(abi));
var myContractReturned = MyContract.new(param1, param2, {
  from:mySenderAddress,
  data:bytecode,
  gas:gasEstimate}, function(err, myContract){
   if(!err) {
      // NOTE: The callback will fire twice!
      // Once the contract has the transactionHash property set and once its deployed on an address.
       // e.g. check tx hash on the first call (transaction send)
      if(!myContract.address) {
          console.log(myContract.transactionHash) // The hash of the transaction, which deploys the contract
      
      // check address on the second call (contract deployed)
      } else {
          console.log(myContract.address) // the contract address
      }
       // Note that the returned "myContractReturned" === "myContract",
      // so the returned "myContractReturned" object will also get the address set.
   }
 });
// Deploy contract syncronous: The address will be added as soon as the contract is mined.
// Additionally you can watch the transaction by using the "transactionHash" property
var myContractInstance = MyContract.new(param1, param2, {data: bytecode, gas: 300000, from: mySenderAddress});
myContractInstance.transactionHash // The hash of the transaction, which created the contract
myContractInstance.address // undefined at start, but will be auto-filled later

Example

// contract abi
var abi = [{
    name: 'myConstantMethod',
    type: 'function',
    constant: true,
    inputs: [{ name: 'a', type: 'string' }],
    outputs: [{name: 'd', type: 'string' }]
}, {
    name: 'myStateChangingMethod',
    type: 'function',
    constant: false,
    inputs: [{ name: 'a', type: 'string' }, { name: 'b', type: 'int' }],
    outputs: []
}, {
    name: 'myEvent',
    type: 'event',
    inputs: [{name: 'a', type: 'int', indexed: true},{name: 'b', type: 'bool', indexed: false}]
}];
// creation of contract object
var MyContract = web3.pi.contract(abi);
// initiate contract for an address
var myContractInstance = MyContract.at('0xc4abd0339eb8d57087278718986382264244252f');
// call constant function
var result = myContractInstance.myConstantMethod('myParam');
console.log(result) // '0x25434534534'
// send a transaction to a function
myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000});
// short hand style
web3.pi.contract(abi).at(address).myAwesomeMethod(...);
// create filter
var filter = myContractInstance.myEvent({a: 5}, function (error, result) {
 if (!error)
   console.log(result);
   /*
   {
       address: '0x8718986382264244252fc4abd0339eb8d5708727',
       topics: "0x12345678901234567890123456789012", "0x0000000000000000000000000000000000000000000000000000000000000005",
       data: "0x0000000000000000000000000000000000000000000000000000000000000001",
       ...
   }
   */
});

Contract Methods

// Automatically determines the use of call or sendTransaction based on the method type
myContractInstance.myMethod(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]);
// Explicitly calling this method
myContractInstance.myMethod.call(param1 [, param2, ...] [, transactionObject] [, defaultBlock] [, callback]);
// Explicitly sending a transaction to this method
myContractInstance.myMethod.sendTransaction(param1 [, param2, ...] [, transactionObject] [, callback]);
// Get the call data, so you can call the contract through some other means
// var myCallData = myContractInstance.myMethod.request(param1 [, param2, ...]);
var myCallData = myContractInstance.myMethod.getData(param1 [, param2, ...]);
// myCallData = '0x45ff3ff6000000000004545345345345..'

The contract object exposes the contract's methods, which can be called using parameters and a transaction object.

Parameters

  • String|Number|BigNumber - (optional) Zero or more parameters of the function. If passing in a string, it must be formatted as a hex number, e.g. "0xdeadbeef" If you have already created BigNumber object, then you can just pass it too.

  • Object - (optional) The (previous) last parameter can be a transaction object, see web3.pi.sendTransaction parameter 1 for more. Note: data and to properties will not be taken into account.

  • Number|String - (optional) If you pass this parameter it will not use the default block set with web3.pi.defaultBlock.

  • Function - (optional) If you pass a callback as the last parameter the HTTP request is made asynchronous. See this note for details.

Returns

String - If its a call the result data, if its a send transaction a created contract address, or the transaction hash, see web3.pi.sendTransaction for details.

Example

// creation of contract object
var MyContract = web3.pi.contract(abi);
// initiate contract for an address
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');
var result = myContractInstance.myConstantMethod('myParam');
console.log(result) // '0x25434534534'
myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000}, function(err, result){ ... });

Contract Events

var event = myContractInstance.myEvent({valueA: 23} [, additionalFilterObject])
// watch for changes
event.watch(function(error, result){
 if (!error)
   console.log(result);
});
// Or pass a callback to start watching immediately
var event = myContractInstance.myEvent([{valueA: 23}] [, additionalFilterObject] , function(error, result){
 if (!error)
   console.log(result);
});

You can use events like filters and they have the same methods, but you pass different objects to create the event filter.

Parameters

  1. Object - Indexed return values you want to filter the logs by, e.g. {'valueA': 1, 'valueB': [myFirstAddress, mySecondAddress]}. By default all filter values are set to null. It means, that they will match any event of given type sent from this contract.

  2. Object - Additional filter options, see filters parameter 1 for more. By default filterObject has field 'address' set to address of the contract. Also first topic is the signature of event.

  3. Function - (optional) If you pass a callback as the last parameter it will immediately start watching and you don't need to call myEvent.watch(function(){}). See this note for details.

Callback return

Object - An event object as follows:

  • address: String, 32 Bytes - address from which this log originated.

  • args: Object - The arguments coming from the event.

  • blockHash: String, 32 Bytes - hash of the block where this log was in. null when its pending.

  • blockNumber: Number - the block number where this log was in. null when its pending.

  • logIndex: Number - integer of the log index position in the block.

  • event: String - The event name.

  • removed: bool - indicate if the transaction this event was created from was removed from the blockchain (due to orphaned block) or never get to it (due to rejected transaction).

  • transactionIndex: Number - integer of the transactions index position log was created from.

  • transactionHash: String, 32 Bytes - hash of the transactions this log was created from.

Example

var MyContract = web3.pi.contract(abi);
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');
// watch for an event with {some: 'args'}
var myEvent = myContractInstance.myEvent({some: 'args'}, {fromBlock: 0, toBlock: 'latest'});
myEvent.watch(function(error, result){
  ...
});
// would get all past logs again.
var myResults = myEvent.get(function(error, logs){ ... });
...
// would stop and uninstall the filter
myEvent.stopWatching();

Contract allEvents

var events = myContractInstance.allEvents([additionalFilterObject]);
// watch for changes
events.watch(function(error, event){
 if (!error)
   console.log(event);
});
// Or pass a callback to start watching immediately
var events = myContractInstance.allEvents([additionalFilterObject], function(error, log){
 if (!error)
   console.log(log);
});

Will call the callback for all events which are created by this contract.

Parameters

  1. Object - Additional filter options, see filters parameter 1 for more. By default filterObject has field 'address' set to address of the contract. This method sets the topic to the signature of event, and does not support additional topics.

  2. Function - (optional) If you pass a callback as the last parameter it will immediately start watching and you don't need to call myEvent.watch(function(){}). See this note for details.

Callback return

Object - See Contract Events for more.

Example

var MyContract = web3.pi.contract(abi);
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');
// watch for an event with {some: 'args'}
var events = myContractInstance.allEvents({fromBlock: 0, toBlock: 'latest'});
events.watch(function(error, result){
  ...
});
// would get all past logs again.
events.get(function(error, logs){ ... });
...
// would stop and uninstall the filter
events.stopWatching();

web3.pi.getCompilers

Compiling features being deprecated https://github.com/pchain/EIPs/issues/209

web3.pi.getCompilers([callback])

Gets a list of available compilers.

Parameters

  1. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Array - An array of strings of available compilers.

Example

var number = web3.pi.getCompilers();
console.log(number); // ["lll", "solidity", "serpent"]

web3.pi.compile.solidity

 web3.pi.compile.solidity(sourceString [, callback])

Compiles solidity source code.

Parameters

  1. String - The solidity source code.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Object - Contract and compiler info.

Example

var source = "" + 
   "contract test {\n" +
   "   function multiply(uint a) returns(uint d) {\n" +
   "       return a * 7;\n" +
   "   }\n" +
   "}\n";
var compiled = web3.pi.compile.solidity(source);
console.log(compiled); 
// {
 "test": {
   "code": "0x605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056",
   "info": {
     "source": "contract test {\n\tfunction multiply(uint a) returns(uint d) {\n\t\treturn a * 7;\n\t}\n}\n",
     "language": "Solidity",
     "languageVersion": "0",
     "compilerVersion": "0.8.2",
     "abiDefinition": [
       {
         "constant": false,
         "inputs": [
           {
             "name": "a",
             "type": "uint256"
           }
         ],
         "name": "multiply",
         "outputs": [
           {
             "name": "d",
             "type": "uint256"
           }
         ],
         "type": "function"
       }
     ],
     "userDoc": {
       "methods": {}
     },
     "developerDoc": {
       "methods": {}
     }
   }
 }
}

web3.pi.compile.lll

 web3. eth.compile.lll(sourceString [, callback])

Compiles LLL source code.

Parameters

  1. String - The LLL source code.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The compiled LLL code as HEX string.

Example

var source = "...";
var code = web3.pi.compile.lll(source);
console.log(code); // "0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702905091905056"

web3.pi.compile.serpent

 web3.pi.compile.serpent(sourceString [, callback])

Compiles serpent source code.

Parameters

  1. String - The serpent source code.

  2. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

String - The compiled serpent code as HEX string.

var source = "...";
var code = web3.pi.compile.serpent(source);
console.log(code); // "0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702905091905056"

web3.pi.namereg

 web3.pi.namereg

Returns GlobalRegistrar object.

Usage

see namereg example.

web3.db.putString

 web3.db.putString(db, key, value)

This method should be called, when we want to store a string in the local leveldb database.

Parameters

  1. String - The database to store to.

  2. String - The name of the store.

  3. String - The string value to store.

Returns

Boolean - true if successfull, otherwise false.

Example

param is db name, second is the key, and third is the string value.

web3.db.putString('testDB', 'key', 'myString') // true

web3.db.getString

 web3.db.getString(db, key)

This method should be called, when we want to get string from the local leveldb database.

Parameters

  1. String - The database string name to retrieve from.

  2. String - The name of the store.

Returns

String - The stored value.

Example

param is db name and second is the key of string value.

var value = web3.db.getString('testDB', 'key');
console.log(value); // "myString"

web3.db.putHex

 web3.db.putHex(db, key, value)

This method should be called, when we want to store binary data in HEX form in the local leveldb database.

Parameters

  1. String - The database to store to.

  2. String - The name of the store.

  3. String - The HEX string to store.

Returns

Boolean - true if successfull, otherwise false.

Example

web3.db.putHex('testDB', 'key', '0x4f554b443'); // true

web3.db.getHex

 web3.db.getHex(db, key)

This method should be called, when we want to get a binary data in HEX form from the local leveldb database.

Parameters

  1. String - The database to store to.

  2. String - The name of the store.

Returns

String - The stored HEX value.

Example

param is db name and second is the key of value.

var value = web3.db.getHex('testDB', 'key');
console.log(value); // "0x4f554b443"

web3.shh

The web3-shh package allows you to interact with the whisper protocol for broadcasting. For more see Whisper Overview.

import Web3 from 'web3';
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:8546', null, options);


// or using the web3 umbrella package
const web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546', null, options;

// -> web3.shh

Example

import Web3 from 'web3';

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:8545', null, options);

web3.shh.addPrivateKey

web3.shh.addPrivateKey(privateKey,[callback])

Stores a key pair derived from a private key, and returns its ID.

Parameters

  1. String - The private key as HEX bytes to import.

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - The Key ID on success and an error on failure.

Example

web3.shh.addPrivateKey('0x8bda3abeb454847b515fa9b404cede50b1cc63cfdeddd4999d074284b4c21e15')
.then(console.log);

web3.shh.addSymKey

web3.shh.addSymKey(symKey,[callback])

Stores the key, and returns its ID.

Parameters

  1. String - The raw key for symmetric encryption as HEX bytes.

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - Returns the key ID on success and an error on failure.

Example

web3.shh.addSymKey('0x5e11b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);

web3.shh.deleteKeyPair

web3.shh.deleteKeyPair(id,[callback])
Deletes the specifies key if it exists.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.addPrivateKey).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - Returns true on success, error on failure.

Example

web3.shh.deleteKeyPair('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);

web3.shh.deleteSymKey

web3.shh.deleteSymKey(id,[callback])

Deletes the symmetric key associated with the given ID.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.addPrivateKey).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - Returns true on success, error on failure.

Example

web3.shh.deleteSymKey('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);

web3.shh.generateSymKeyFromPassword

web3.shh.generateSymKeyFromPassword(password,[callback])

Generates the key from password, stores it, and returns its ID.

Parameters

  1. String - A password to generate the sym key from.

  2. 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);

web3.shh.getPrivateKey

web3.shh.getPrivateKey(id,[callback])

Returns the private key for a key pair ID.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.addPrivateKey).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - Returns the private key on success and an error on failure.

Example

web3.shh.getPrivateKey('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0x234234e22b9ffc2387e18636e0534534a3d0c56b0243567432453264c16e78a2adc"

web3.shh.getPublicKey

web3.shh.getPublicKey(id,[callback])

Returns the public key for a key pair ID.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.addPrivateKey).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - Returns the Public key on success and an error on failure.

Example

web3.shh.getPublicKey('3e22b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0x04d1574d4eab8f3dde4d2dc7ed2c4d699d77cbbdd09167b8fffa099652ce4df00c4c6e0263eafe05007a46fdf0c8d32b11aeabcd3abbc7b2bc2bb967368a68e9c6"

web3.shh.getSymKey

web3.shh.getSymKey(id,[callback])

Returns the symmetric key associated with the given ID.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.addPrivateKey).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - Returns the raw symmetric key on success and an error on failure.

Example

web3.shh.getSymKey('af33b9ffc2387e18636e0a3d0c56b023264c16e78a2adcba1303cefc685e610f')
.then(console.log);
> "0xa82a520aff70f7a989098376e48ec128f25f767085e84d7fb995a9815eebff0a"

web3.shh.hasKeyPair

web3.shh.hasKeyPair(id,[callback])

Checks if the whisper node has a private key of a key pair matching the given ID.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newKeyPair and shh.addPrivateKey).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - 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

web3.shh.hasSymKey

web3.shh.hasSymKey(id,[callback])

Checks if there is a symmetric key stored with the given ID.

Parameters

  1. String - The key pair ID, returned by the creation functions (shh.newSymKey, shh.addSymKey or shh.generateSymKeyFromPassword).

  2. Function - (optional) Optional callback, returns an error object as first parameter and the result as second.

Returns

Promise - 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

web3.shh.post

web3.shh.post(object [, callback])

This method should be called, when we want to post whisper message to the network.

Parameters

  1. Object - The post object:

  • from: String, 60 Bytes HEX - (optional) The identity of the sender.

  • to: String, 60 Bytes HEX - (optional) The identity of the receiver. When present whisper will encrypt the message so that only the receiver can decrypt it.

  • topics: Array of Strings - Array of topics Strings, for the receiver to identify messages.

  • payload: String|Number|Object - The payload of the message. Will be autoconverted to a HEX string before.

  • priority: Number - The integer of the priority in a range from ... (?).

  • ttl: Number - integer of the time to live in seconds.

  1. Function - (optional) If you pass a callback the HTTP request is made asynchronous. See this note for details.

Returns

Boolean - returns true if the message was sent, otherwise false.

Example

var identity = web3.shh.newIdentity();
var topic = 'example';
var payload = 'hello whisper world!';
var message = {
 from: identity,
 topics: [topic],
 payload: payload,
 ttl: 100,
 workToProve: 100 // or priority TODO
};
web3.shh.post(message);

web3.pi.sendIBANTransaction

var txHash = web3.pi.sendIBANTransaction('0x00c5496aee77c1ba1f0854206a26dda82a81d6d8', 'XE81ETHXREGGAVOFYORK', 0x100);

Sends IBAN transaction from user account to destination IBAN address.

Parameters

  • string - address from which we want to send transaction

  • string - IBAN address to which we want to send transaction

  • value - value that we want to send in IBAN transaction

web3.pi.iban

var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");

web3.pi.iban.toAddress

var i = web3.pi.iban.toAddress('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS');
console.log(i.toString()); // '0x00c5496aEe77C1bA1f0854206A26DdA82a81D6D8

web3.pi.iban.toIban

var i = web3.pi.iban.toIban('0x00c5496aee77c1ba1f0854206a26dda82a81d6d8');
console.log(i.toString()); // 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS

web3.pi.iban.fromAddress

var i = web3.pi.iban.fromAddress('0x00c5496aee77c1ba1f0854206a26dda82a81d6d8');
console.log(i.toString()); // 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS

web3.pi.iban.fromBban

var i = web3.pi.iban.fromBban('ETHXREGGAVOFYORK');
console.log(i.toString()); // "XE81ETHXREGGAVOFYORK"

web3.pi.iban.createIndirect

var i = web3.pi.iban.createIndirect({
 institution: "XREG",
 identifier: "GAVOFYORK"
});
console.log(i.toString()); // "XE81ETHXREGGAVOFYORK"

web3.pi.iban.isValid

var valid = web3.pi.iban.isValid("XE81ETHXREGGAVOFYORK");
console.log(valid); // true
var valid2 = web3.pi.iban.isValid("XE82ETHXREGGAVOFYORK");
console.log(valid2); // false, cause checksum is incorrect
var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");
var valid3 = i.isValid();
console.log(valid3); // true

web3.pi.iban.isDirect

var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");
var direct = i.isDirect();
console.log(direct); // false

web3.pi.iban.isIndirect

var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");
var indirect = i.isIndirect();
console.log(indirect); // true

web3.pi.iban.checksum

var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");
var checksum = i.checksum();
console.log(checksum); // "81"

web3.pi.iban.institution

var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");
var institution = i.institution();
console.log(institution); // 'XREG'

web3.pi.iban.client

var i = new web3.pi.iban("XE81ETHXREGGAVOFYORK");
var client = i.client();
console.log(client); // 'GAVOFYORK'

web3.pi.iban.address

var i = new web3.pi.iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS');
var address = i.address();
console.log(address); // '00c5496aee77c1ba1f0854206a26dda82a81d6d8'

web3.pi.iban.toString

var i = new web3.pi.iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS');
console.log(i.toString()); // 'XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'

web3.chain.createChildChain

 web3.chain.createChildChain(from,chainId,minValidators,minDepositAmount,startBlock,endBlock,gasPrice [, callback])

Send an application of subchain Creation, save the application into the ChainInfo DB

Parameters

  1. from, address - the address who triggers the action

  2. chainId, string - subchain id

  3. minValidators, hex string - Minimum Validators of the new subchain

  4. minDepositAmount, hex string - Minimum Deposit PAI of the new subchain

  5. startBlock, hex string - Start Block height for launch subchain

  6. endBlock, hex string - End Block height for launch subchain

  7. 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 = "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); 
});

web3.chain.joinChildChain

 web3.chain.joinChildChain(from,pubkey,chainId,depositAmount,signature,gasPrice [, callback])

Send a request to Join the subchain, save the Join Application into the ChainInfo DB, after the blockchain match the criteria of the subchain, chainMgr will load the subchain Data from ChainInfo DB then start it

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. pubkey: hex string, 128 Bytes - the BLS Public Key who triggers the action

  3. chainId: string - subchain id

  4. depositAmount: hex string - Amount of the Deposit PAI to join the subchain

  5. signature: hex string, 64 Bytes - the signature of From Address, signed by BLS Private Key. (How to sign, see web3.chain.signAddress)

  6. 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); 
});

web3.chain.depositInMainChain

 web3.chain.depositInMainChain(from,chainId,amount,gasPrice [, callback])

Send a request to Join the subchain, save the Join Application into the ChainInfo DB, after the blockchain match the criteria of the subchain, chainMgr will load the subchain Data from ChainInfo DB then start it

Parameters

  1. from, address - the address who triggers the action

  2. chainId, string - subchain id

  3. amount, hex string - amount of PAI to deposit

  4. 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 = "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); 
});

web3.chain.depositInChildChain

 web3.chain.depositInChildChain(from,txHash [, callback])

Deposit from the main chain to subchain (step 2). Should be used with chain_depositInMainChain

Parameters

  1. from, address - the address who triggers the action

  2. txHash, 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); 
});

web3.chain.withdrawFromChildChain

 web3.chain.withdrawFromChildChain(from,amount,gasPrice [, callback])

Withdraw from subchain to the main chain (step 1). Should be used with chain_withdrawFromMainChain

Parameters

  1. from, address - the address who triggers the action

  2. amount, hex string - amount of PAI to withdraw

  3. gasPrice, hex string - 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); 
});

web3.chain.withdrawFromMainChain

 web3.chain.withdrawFromMainChain(from,amount,chainId,txHash [, callback])

Withdraw from subchain to the main chain (step 2). Should be used with chain_withdrawFromChildChain

Parameters

  1. from, address - the address who triggers the action

  2. amount, hex string - amount of PAI to withdraw

  3. chainId, string - subchain id

  4. txHash, 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); 
});

web3.chain.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

  1. from: address, 20 Bytes - Address which will be signed

  2. privateKey: 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); 
});

web3.chain.setBlockReward

 web3.chain.setBlockReward(from,reward [, callback])

Set the Reward of each block for the subchain, only subchain 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 subchain Address 0x0000000000000000000000000000000000000064 balance, which accept anyone to transfer their contribution

Parameters

  1. from: address, 20 Bytes - Owner Address of subchain

  2. reward: 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); 
});

web3.chain.getBlockReward

 web3.chain.getBlockReward(blockNumber [, callback])

Get the Reward of each block for the subchain

Parameters

  1. 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); 
});

web3.chain.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 epoch

  • validators: Array - Array of validator object

    • address: Address - Address of the Validator

  • voting_power: QUANTITY - Voting Power (Stack) of the Validator

Example

web3.chain.getAllChains(function(err, result) {
 if (!err)
   console.log(result); 
});

web3.tdm.voteNextEpoch

 web3.tdm.voteNextEpoch(from,voteHash,gasPrice [, callback])

Send hash of Vote for the next epoch

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. voteHash: 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) ),see web3.getVoteHash

  3. 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 = "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); 
});

web3.tdm.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

  1. from: address, 20 Bytes - the address who triggers the action

  2. pubkey: hex string, 128 Bytes - the BLS Public Key who triggers the action

  3. amount: hex string - the amount of vote

  4. salt: string - salt string

  5. signature: hex string, 64 Bytes - the signature of From Address, signed by BLS Private Key. (How to sign, see chain_signAddress)

  6. 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 = "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); 
});

web3.tdm.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); 
});

web3.tdm.getEpoch

 web3.tdm.getEpoch(number [, callback])

Returns the epoch details

Parameters

  1. number, int - epoch number

Returns

the epoch details

Example

var number = 1;
web3.tdm.getEpoch(number,function(err, result) {
 if (!err)
   console.log(result); 
});

web3.tdm.getNextEpochVote

 web3.tdm.getNextEpochVote([, callback])

Returns the votes details of the next epoch

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); 
});

web3.tdm.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); 
});

web3.tdm.generatePrivateValidator

 web3.tdm.generatePrivateValidator(from,[, callback])

Returns the generated BLS Public/Private Key associate with provided address

Parameters

  1. from: address, 20 Bytes - the address

Returns

  1. address: address, 20 Bytes - address from the request

  2. consensus_pub_key: hex string, 128 Bytes - the generated BLS Public Key

  3. consensus_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); 
});

web3.del.delegate

 web3.del.delegate(from,candidate,amount,gasPrice [, callback])

Create a new transaction to Delegate your balance to Candidate

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. candidate: address, 20 Bytes - the address of candidate

  3. amount: hex string - Amount of the Delegate PAI

  4. gasPrice: hex string - (if set to null,system will give default value(1 gwei) ) gas price from the request

Returns

hash, hex 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); 
});

web3.del.cancelDelegate

 web3.del.cancelDelegate(from,candidate,amount,gasPrice [, callback])

Create a new transaction to Cancel your Delegation from Candidate

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. candidate: address, 20 Bytes - the address of candidate

  3. amount: hex string - Amount of the Delegate PAI

  4. gasPrice: hex string - (if set to null,system will give default value(1 gwei) ) gas price from the request

Returns

hash, hex 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); 
});

web3.del.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

  1. from: address, 20 Bytes - the address who triggers the action

  2. securityDeposit: hex string - Amount of the security deposit PAI (minimum 10,000 PAI)

  3. commission: integer - the commission fee percentage of each Block Reward be charged to proxied de, when Candidate become a Validator (between 0 - 100)

  4. gasPrice: hex string - (if set to null,system will give default value(1 gwei) ) gas price from the request

Returns

hash, hex 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); 
});

web3.del.cancelCandidate

 web3.del.cancelCandidate(from,gasPrice [, callback])

Create a new transaction to become a Candidate (with specific security deposit and commission fee rate)

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. gasPrice: hex string - (if set to null,system will give default value(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); 
});

web3.del.checkCandidate

 web3.del.checkCandidate(from,blockNumber [, callback])

CReturns the candidate status of the account of given address.

Parameters

  1. from: address, 20 Bytes - the address who triggers the action

  2. blockNumber: QUANTITY|TAG - integer block number, or the string "latest", "earliest" or "pending"

Returns

  1. candidate: Boolean - Candidate Flag of the given address

  2. commission: QUANTITY - commission percentage of Candidate Address

Example

var from = "0xd833b6738285f4a50cf42cf1a40c4000256589d4";
web3.del.checkCandidate(from,"latest",function(err, result) {
 if (!err)
   console.log(result); 
});

最后更新于