platon-js-qianqian v1.0.0
Web3.js Interface
Interact with nodes through web3 objects provided by web3.js. On the underlying implementation, it communicates with the local node through RPC calls. web3.js can connect to any PlatON node that exposes the RPC interface.
Usage
First, make sure the nodeJS environment is successfully installed locally. WEB3.JS
uses the lerna management tool to optimize the workflow of the multi-package code base hosted on git/npm
, so you should make sure the lerna package has been installed globally before installing. If not, execute the command npm i lerna -g
for global installation.
Then you can integrate client-sdk-js into the project through package management tools such as npm or yarn, the steps are as follows:
- npm:
npm i PlatONnetwork/client-sdk-js#0.15.1-develop
- yarn:
yarn add PlatONnetwork/client-sdk-js#0.15.1-develop
Create a web3 instance and set up a provider. You can refer to the following code:
// in node.js
var Web3 = require('web3');
var web3 = new Web3('http://127.0.0.1:6789');
console.log(web3);
> {
platon: ... ,
utils: ...,
ppos: ...,
...
}
After successful introduction, you can use the relevant API of web3.
API Reference
web3.version
web3.version
: Contains the current package version of the web3.js library.
Method:
Web3.version
web3.version
Returns:
String
: Current version number.
Example:
web3.version;
> "0.13.1"
web3.modules
web3.modules
Will return an object with the classes of all major sub modules, to be able to instantiate them manually.
Method:
Web3.modules
web3.modules
Returns:
Object
: A list of module constructors:
Platon
- Function: The PlatON module for interacting with the PlatON network see web3.platon for more.Net
- Function: The Net module for interacting with network properties see web3.platon.net for more.Personal
- Function: The Personal module for interacting with the PlatON accounts see web3.platon.personal for more.
Example:
web3.modules
> {
Platon: Platon function(provider),
Net: Net function(provider),
Personal: Personal function(provider)
}
web3.setProvider
web3.setProvider()
Will change the provider for it's module.
Method:
web3.setProvider(myProvider)
web3.platon.setProvider(myProvider)
...
Notes: When called on the umbrella package web3 it will also set the provider for all sub modules web3.platon, web3.shh, etc EXCEPT web3.bzz which needs a separate provider at all times.
Parameter:
Object
- myProvider
: a valid provider.
Returns:
Boolean
Example:
var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// or
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
web3.providers
Contains the current available providers.
Method:
web3.providers
web3.platon.providers
...
Returns:
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.
Example:
var Web3 = require('web3');
// // use the given Provider, e.g in Mist, or instantiate a new websocket provider.
var web3 = new Web3(Web3.givenProvider || 'ws://remotenode.com:8546');
// or
var web3 = new Web3(Web3.givenProvider || new Web3.providers.WebsocketProvider('ws://remotenode.com:8546'));
web3.givenProvider
When using web3.js in an PlatON compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise null.
Method:
web3.givenProvider
web3.platon.givenProvider
...
Returns:
Object
: The given provider set or null;
web3.currentProvider
web3.currentProvider
Will return the current provider, otherwise null.
Method:
web3.currentProvider
web3.platon.currentProvider
...
Returns:
Object
: The current provider set or null;
web3.BatchRequest
web3.BatchRequest
Class to create and execute batch requests.
Method:
new web3.BatchRequest()
new web3.platon.BatchRequest()
Parameter:
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:
var contract = new web3.platon.Contract(abi, address);
var batch = new web3.BatchRequest();
batch.add(web3.platon.getBalance.request('lax1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmscn5j', 'latest', callback));
batch.add(contract.methods.balance(address).call.request({from: 'lax1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmscn5j'}, callback2));
batch.execute();
web3.platon.defaultAccount
web3.platon.defaultAccount
This default address is used as the default "from" property, if no "from" property is specified in the following methods:
- web3.platon.sendTransaction()
- web3.platon.call()
- new web3.platon.Contract() -> myContract.methods.myMethod().call()
- new web3.platon.Contract() -> myContract.methods.myMethod().send()
Method:
web3.platon.defaultAccount
Property:
String
- 20 Bytes: 20 Bytes: Any PlatON address. You should have the private key for that address in your node or keystore. (Default is undefined)
Example:
web3.platon.defaultAccount;
> undefined
// set the default account
web3.platon.defaultAccount = 'atx1fyeszufxwxk62p46djncj86rd553skpph926ws';
Note:
All addresses must be quoted, as above: 'lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6'.
web3.platon.defaultBlock
web3.platon.defaultBlock
The default block is used for certain methods.
- web3.platon.getBalance()
- web3.platon.getCode()
- web3.platon.getTransactionCount()
- web3.platon.getStorageAt()
- web3.platon.call()
- new web3.platon.Contract() -> myContract.methods.myMethod().call()
You can override it by passing in the defaultBlock as last parameter.
Method:
web3.platon.defaultBlock
Property:
Default block parameters can be one of the following:
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"
Example:
web3.platon.defaultBlock;
> "latest"
// set the default block
web3.platon.defaultBlock = 231;
web3.platon.getProtocolVersion
Returns the PlatON protocol version of the node.
Method:
web3.platon.getProtocolVersion([callback])
Returns:
Promise
returns String
: the protocol version.
Example:
web3.platon.getProtocolVersion().then(console.log);
> "63"
web3.platon.isSyncing
web3.platon.isSyncing()
Checks if the node is currently syncing and returns either a syncing object, or false.
Method:
web3.platon.isSyncing([callback])
Returns:
Promise
returns 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 download.pulledStates
-Number
: The already downloaded states.
Example:
web3.platon.isSyncing().then(console.log);
> {
startingBlock: 100,
currentBlock: 312,
highestBlock: 512,
knownStates: 234566,
pulledStates: 123455
}
web3.platon.getGasPrice
web3.platon.getGasPrice()
Returns the current gas price oracle. The gas price is determined by the last few blocks median gas price.
Method:
web3.platon.getGasPrice([callback])
Returns:
Promise
returns String
- Number string of the current gas price in von.
Example:
web3.platon.getGasPrice().then(console.log);
> "20000000000"
web3.platon.getAccounts
web3.platon.getAccounts()
Returns a list of accounts the node controls.
Method:
web3.platon.getAccounts([callback])
Returns:
Promise
returns Array
- An array of addresses controlled by node.
Example:
web3.platon.getAccounts().then(console.log);
> ["atx1fyeszufxwxk62p46djncj86rd553skpph926ws", "atx1kg7y7wfwzqsyxppyxcdvhkkkwlf64cclmnav7p"]
web3.platon.getBlockNumber
web3.platon.getBlockNumber()
Returns the current block number.
Method:
web3.platon.getBlockNumber([callback])
Returns:
Promise
returns Number
- The number of the most recent block.
Example:
web3.platon.getBlockNumber().then(console.log);
> 2744
web3.platon.getBalance
web3.platon.getBalance()
Get the balance of an address at a given block.
Method:
web3.platon.getBalance(address [, defaultBlock] [, callback])
Parameter:
address
:String - The address to get the balance of.defaultBlock
:Number|String - (optional) If you pass this parameter it will not use the default block set with web3.platon.defaultBlock. Pre-defined block numbers as "latest", "earliest", "pending", and "genesis" can also be used.callback
:Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns String
- The current balance for the given address in von.
Example:
web3.platon.getBalance("atx1fyeszufxwxk62p46djncj86rd553skpph926ws")
.then(console.log);
> "1000000000000"
web3.platon.getStorageAt
web3.platon.getStorageAt()
Get the storage at a specific position of an address.
Method:
web3.platon.getStorageAt(address, position [, defaultBlock] [, callback])
Parameter:
address
-String
: The address to get the storage from.position
-Number
: The index position of the storage.defaultBlock
-Number|String
(optional) If you pass this parameter it will not use the default block set with web3.platon.defaultBlock. Pre-defined block numbers as "latest", "earliest", "pending", and "genesis" can also be used.callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns String
- The value in storage at the given position.
Example:
web3.platon.getStorageAt("atx1fyeszufxwxk62p46djncj86rd553skpph926ws", 0)
.then(console.log);
> "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"
web3.platon.getCode
web3.platon.getCode()
Get the code at a specific address.
Method:
web3.platon.getCode(address [, defaultBlock] [, callback])
Parameter:
address
-String
: The address to get the code from.defaultBlock
-Number|String
: (optional) If you pass this parameter it will not use the default block set with web3.platon.defaultBlock. Pre-defined block numbers as "latest", "earliest", "pending", and "genesis" can also be used.callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns String
- The data at given address.
Example:
web3.platon.getCode("atx1fyeszufxwxk62p46djncj86rd553skpph926ws")
.then(console.log);
> "0x600160008035811a818181146012578301005b601b6001356025565b8060005260206000f25b600060078202905091905056"
web3.platon.getBlock
web3.platon.getBlock()
Returns a block matching the block number or block hash.
Method:
web3.platon.getBlock(blockHashOrBlockNumber [, returnTransactionObjects] [, callback])
Parameter:
blockHashOrBlockNumber
-String|Number
: The block number or block hash. Or the string "genesis", "latest", "earliest", or "pending" as in the default block parameter.returnTransactionObjects
-Boolean
: (optional, default false) If specified true, the returned block will contain all transactions as objects. By default it is false so, there is no need to explictly specify false. And, if false it will only contains the transaction hashes.callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise returns Object - The block object:
number
-Number
: The block number. null when it's pending block.hash
32 Bytes -String
: Hash of the block. null when it's pending block.parentHash
32 Bytes -String
: Hash of the parent block.nonce
8 Bytes -String
: Hash of the generated proof-of-work. null when it's 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 it's 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.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
: The unix timestamp for when the block was collated.transactions
-Array
: Array of transaction objects, or 32 Bytes transaction hashes depending on the returnTransactionObjects parameter.uncles
-Array
: Array of uncle hashes.
Example:
web3.platon.getBlock(3150)
.then(console.log);
> {
"number": 3,
"hash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"parentHash": "0x2302e1c0b972d00932deb5dab9eb2982f570597d9d42504c05d9c2147eaf9c88",
"nonce": "0xfb6e1a62d119228b",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"transactionsRoot": "0x3a1b03875115b79539e5bd33fb00d8f7b7cd61929d5a3c574f507b8acf415bee",
"stateRoot": "0xf1133199d44695dfa8fd1bcfe424d82854b5cebef75bddd7e40ea94cda515bcb",
"miner": "atx1fyeszufxwxk62p46djncj86rd553skpph926ws",
"difficulty": '21345678965432',
"totalDifficulty": '324567845321',
"size": 616,
"extraData": "0x",
"gasLimit": 3141592,
"gasUsed": 21662,
"timestamp": 1429287689,
"transactions": [
"0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b"
],
"uncles": []
}
web3.platon.getBlockTransactionCount
web3.platon.getBlockTransactionCount()
Returns the number of transaction in a given block.
Method:
web3.platon.getBlockTransactionCount(blockHashOrBlockNumber [, callback])
Parameter:
blockHashOrBlockNumber
-String|Number
: The block number or hash. Or the string "genesis", "latest", "earliest", or "pending" as in the default block parameter.callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns Number
- The number of transactions in the given block.
Example:
web3.platon.getBlockTransactionCount("atx1fyeszufxwxk62p46djncj86rd553skpph926ws")
.then(console.log);
> 1
web3.platon.getTransaction
web3.platon.getTransaction()
Returns a transaction matching the given transaction hash.
Method:
web3.platon.getTransaction(transactionHash [, callback])
Parameter:
transactionHash
-String
: The transaction hash.callback
-Function
: (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns Object
- A transaction object it's 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 it's pending.blockNumber
-Number
: Block number where this transaction was in. null when it's pending.transactionIndex
-Number
: Integer of the transactions index position in the block. null when it's pending.from
-String
: Address of the sender.to
-String
: Address of the receiver. null when it's a contract creation transaction.value
-String
: Value transferred in von.gasPrice
-String
: Gas price provided by the sender in von.gas
-Number
: Gas provided by the sender.input
-String
: The data sent along with the transaction.
Example:
web3.platon.getTransaction('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b§234')
.then(console.log);
> {
"hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"nonce": 2,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"transactionIndex": 0,
"from": "atx14984xa8uuhkmer32s6tuz5e3valxa0ctxj9j67",
"to": "atx1v227ux60dht9q3mk97fyanfk0st740u06lv59d",
"value": '123450000000000000',
"gas": 314159,
"gasPrice": '2000000000000',
"input": "0x57cb2fc4"
}
web3.platon.getTransactionFromBlock
web3.platon.getTransactionFromBlock()
Returns a transaction based on a block hash or number and the transactions index position.
Method:
getTransactionFromBlock(hashStringOrNumber, indexNumber [, callback])
Parameter:
hashStringOrNumber
:String - A block number or hash. Or the string "genesis", "latest", "earliest", or "pending" as in the default block parameter.indexNumber
:Number - The transactions index position.callback
:Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns Object
- A transaction object, see web3.eth.getTransaction:
Example:
var transaction = web3.platon.getTransactionFromBlock('0x4534534534', 2)
.then(console.log);
> // see web3.platon.getTransaction
web3.platon.getTransactionReceipt
web3.platon.getTransactionReceipt()
Returns the receipt of a transaction by transaction hash.
Notes: The receipt is not available for pending transactions and returns null.
Method:
web3.platon.getTransactionReceipt(hash [, callback])
Parameter:
hash
:String - The transaction hash.callback
: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 it's a contract creation transaction.contractAddress
-String
: The contract address created, if the transaction was a contract creation, otherwise null.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:
var receipt = web3.platon.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b')
.then(console.log);
> {
"status": true,
"transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": 0,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"contractAddress": "lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6",
"cumulativeGasUsed": 314159,
"gasUsed": 30234,
"logs": [{
// logs as returned by getPastLogs, etc.
}, ...]
}
web3.platon.getTransactionCount
web3.platon.getTransactionCount()
Get the numbers of transactions sent from this address.
Method:
web3.platon.getTransactionCount(address [, defaultBlock] [, callback])
Parameter:
address
:String - The address to get the numbers of transactions from.defaultBlock
:Number|String - (optional) If you pass this parameter it will not use the default block set with web3.platon.defaultBlock. Pre-defined block numbers as "latest", "earliest", "pending", and "genesis" can also be used.callback
:Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns Number
- The number of transactions sent from the given address.
Example:
web3.platon.getTransactionCount("lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6")
.then(console.log);
> 1
web3.platon.sendTransaction
web3.platon.sendTransaction()
Sends a transaction to the network.
Method:
web3.platon.sendTransaction(transactionObject [, callback])
Parameter:
transactionObject
:Object
- The transaction object to send:from
-String|Number
: The address for the sending account. Uses the web3.platon.defaultAccount property, if not specified. Or an address or index of a local wallet in web3.platon.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.platon.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.
Returns:
web3.platon.sendTransaction()
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" returns String: Is fired right after the transaction is sent and a transaction hash is available.
- "receipt" returns
Object
: Is fired when the transaction receipt is available. - "confirmation" returns Number, 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 it's minded.
- "error" returns Error and Object|undefined: Is fired if an error occurs during sending. If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
Example:
// compiled solidity source code using https://remix.ethereum.org
var code = "603d80600c6000396000f3007c01000000000000000000000000000000000000000000000000000000006000350463c6888fa18114602d57005b6007600435028060005260206000f3";
// using the callback
web3.platon.sendTransaction({
from: 'atx1mc9jj4nf487e840j3k0vshjq7n9kj7aw9qvc0x',
data: code // deploying a contracrt
}, function(error, hash){
...
});
// using the promise
web3.platon.sendTransaction({
from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv',
to: 'lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6',
value: '1000000000000000'
})
.then(function(receipt){
...
});
// using the event emitter
web3.platon.sendTransaction({
from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv',
to: 'lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6',
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.
web3.platon.sendSignedTransaction
web3.platon.sendSignedTransaction()
Sends an already signed transaction, generated for example using web3.platon.accounts.signTransaction.
Method:
web3.platon.sendSignedTransaction(signedTransactionData [, callback])
Parameter:
signedTransactionData
:String - Signed transaction data in HEX format.callback
:Function - (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.platon.sendTransaction for details.
Example:
var Web3 = require("web3");
const transaction_demo = async function () {
web3 = new Web3("http://127.0.0.1:6789");
var privateKey="0xb416b341437c420a45cb6ba5ca883655eec169360d36866124d23682c03766ba";
// 主网地址
let from = web3.platon.accounts.privateKeyToAccount(privateKey).address;
let nonce = web3.utils.numberToHex(await web3.platon.getTransactionCount(from));
let tx = {
from:from,
to: "atp1j9x482k50kl86qvx5cyw7hp48qcx5mezayxj8t",
value: "1000000000000000000",
chainId: 201018,
gasPrice: "10000000000000",
gas: "21000",
nonce: nonce,
};
// 签名交易
let signTx = await web3.platon.accounts.signTransaction(tx, privateKey);
// 发送交易
let receipt = await web3.platon.sendSignedTransaction(signTx.rawTransaction);
console.log("sign tx data:\n", signTx.rawTransaction)
}
web3.platon.sign
web3.platon.sign()
Signs data using a specific account. This account needs to be unlocked.
Method:
web3.platon.sign(dataToSign, address [, callback])
Parameter:
dataToSign
:String - Data to sign. If String it will be converted using web3.utils.utf8ToHex.address
:String|Number - Address to sign data with. Or an address or index of a local wallet in web3.platon.accounts.wallet.callback
:Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns String
- The signature.
Example:
web3.platon.sign("Hello world", "lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
// the below is the same
web3.platon.sign(web3.utils.utf8ToHex("Hello world"), "lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6")
.then(console.log);
> "0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"
web3.platon.signTransaction
web3.platon.signTransaction()
Signs a transaction. This account needs to be unlocked.
Method:
web3.platon.signTransaction(transactionObject, address [, callback])
Parameter:
transactionObject
:Object
- The transaction data to sign web3.eth.sendTransaction() for more.address
:String
- Address to sign transaction with.callback
:Function
- (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise returns Object - The RLP encoded transaction. The raw property can be used to send the transaction using web3.platon.sendSignedTransaction.
Example:
web3.platon.signTransaction({
from: "atx1avq5lrytgxxmddzhwnpjdg8xf3ufznwql8t8dx",
gasPrice: "20000000000",
gas: "21000",
to: 'atx1x56n2df4x56n2df4x56n2df4x56n2df4fcrvnj',
value: "1000000000000000000",
data: ""
}).then(console.log);
> {
raw: '0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88da07e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
tx: {
nonce: '0x0',
gasPrice: '0x4a817c800',
gas: '0x5208',
to: 'atx1x56n2df4x56n2df4x56n2df4x56n2df4fcrvnj',
value: '0xde0b6b3a7640000',
input: '0x',
v: '0x25',
r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d',
s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0',
hash: '0xda3be87732110de6c1354c83770aae630ede9ac308d9f7b399ecfba23d923384'
}
}
web3.platon.estimateGas
web3.platon.estimateGas()
Executes a message call or transaction and returns the amount of the gas used.
Method:
web3.platon.estimateGas(callObject [, callback])
Parameter:
callObject
:Object - A transaction object see web3.platon.sendTransaction, with the difference that for calls the from property is optional as well.callback
:Function - (optional) Optional callback, returns an error object as first parameter and the result as second.
Returns:
Promise
returns Number
- the used gas for the simulated call/transaction.
Example:
web3.platon.estimateGas({
to: "lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6",
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
})
.then(console.log);
> "0x0000000000000000000000000000000000000000000000000000000000000015"
web3.platon.getPastLogs
web3.platon.getPastLogs()
Gets past logs, matching the given options.
Method:
web3.platon.getPastLogs(options [, callback])
Parameter:
options
: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 use null, 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
returns 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 it's still pending.blockNumber
-Number
: The block number where this log was created in. null when it's still pending.
Example:
web3.platon.getPastLogs({
address: "lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6",
topics: ["0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234"]
})
.then(console.log);
> [{
data: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
topics: ['0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7', '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385']
logIndex: 0,
transactionIndex: 0,
transactionHash: '0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385',
blockHash: '0xfd43ade1c09fade1c0d57a7af66ab4ead7c2c2eb7b11a91ffdd57a7af66ab4ead7',
blockNumber: 1234,
address: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'
},{...}]
web3.platon.subscribe
The web3.platon.subscribe function lets you subscribe to specific events in the blockchain.
Method:
web3.platon.subscribe(type [, options] [, callback]);
Parameter:
type
:String - The subscription, you want to subscribe to.options
:Mixed - (optional) Optional additional parameters, depending on the subscription type.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.
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.arguments
: The subscription arguments, used when re-subscribing.on("data")
returns Object: Fires on each incoming log with the log object as argument.on("changed")
returns Object: Fires on each log which was removed from the blockchain. The log will have the additional property"removed: true"
.on("error")
returns Object: Fires when an error in the subscription occurs.on("connected")
returns String: Fires once after the subscription successfully connected. Returns the subscription id.
Notification returns:
Mixed - depends on the subscription, see the different subscriptions for more.
Example:
var subscription = web3.platon.subscribe('logs', {
address: 'atx..',
topics: ['atx...']
}, function(error, result){
if (!error)
console.log(log);
});
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if(success)
console.log('Successfully unsubscribed!');
});
web3.platon.clearSubscriptions
web3.platon.clearSubscriptions()
Resets subscriptions. This will not reset subscriptions from other packages like web3-shh, as they use their own requestManager.
Method:
web3.platon.clearSubscriptions(flag)
Parameters:
flag
:Boolean - 值为true则表示保持同步订阅
Returns:
Boolean
: If true it keeps the "syncing" subscription.
Example:
web3.platon.subscribe('logs', {} ,function(){ ... });
...
web3.platon.clearSubscriptions();
web3.platon.subscribe("pendingTransactions")
pendingTransactions
Subscribes to incoming pending transactions.
Method:
web3.platon.subscribe('pendingTransactions' [, callback]);
Parameter:
type
:String - "pendingTransactions",the type of the subscription.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" returns
String
: Fires on each incoming pending transaction and returns the transaction hash. - "error" returns
Object
: Fires when an error in the subscription occurs.
Notification returns:
- Object|Null - First parameter is an error object if the subscription failed.
- Object - Second parameter is the transaction hash.
Example:
var subscription = web3.platon.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!');
});
web3.platon.subscribe('newBlockHeaders')
newBlockHeaders
Subscribes to incoming block headers. This can be used as timer to check for changes on the blockchain.
Method:
web3.platon.subscribe('newBlockHeaders' [, callback]);
Parameter:
type
:String
-"newBlockHeaders"
, the type of the subscription.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 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 it's pending block.hash
32 Bytes -String
: Hash of the block. null when it's pending block.parentHash
32 Bytes -String
: Hash of the parent block.nonce
8 Bytes -String
: Hash of the generated proof-of-work. null when it's 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 it's 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
: The root of the receipts.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.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:
var subscription = web3.platon.subscribe('newBlockHeaders', function(error, result){
if (error)
console.log(error);
})
.on("data", function(blockHeader){
});
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if(success)
console.log('Successfully unsubscribed!');
});
web3.platon.subscribe('syncing')
syncing
Subscribe to syncing events. This will return an object when the node is syncing and when it's finished syncing will return FALSE.
Method:
web3.platon.subscribe('syncing' [, callback]);
Parameter:
type
:String -"syncing"
, the type of the subscription.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 sync object as argument."changed"
returnsObject
: Fires when the synchronisation is started with true and when finished with false."error"
returnsObject
: Fires when an error in the subscription occurs.
For the structure of a returned event Object see web3.platon.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 return true once or when finished it will return false once.
Example:
var subscription = web3.platon.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!');
});
web3.platon.subscribe('logs')
Subscribes to incoming logs, filtered by the given options. If a valid numerical fromBlock options property is set, Web3 will retrieve logs beginning from this point, backfilling the response as necessary.
Method:
web3.platon.subscribe('logs', options [, callback]);
Parameter:
"logs"
:String
, the type of the subscription.options
:Object
- The subscription options:fromBlock
-Number
: The number of the earliest block. By default null.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 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']
callback
- Function: 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:
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
: returns Object: 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.platon.getPastEvents return values.
Notification returns:
Object|Null
- First parameter is an error object if the subscription failed.Object
- The log object like in web3.platon.getPastEvents return values.
Example:
var subscription = web3.platon.subscribe('logs', {
address: 'atx..',
topics: ['atx...']
}, function(error, result){
if (!error)
console.log(result);
})
.on("data", function(log){
console.log(log);
})
.on("changed", function(log){
});
// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
if(success)
console.log('Successfully unsubscribed!');
});
web3.platon.Contract
The web3.platon.Contract
object makes it easy to interact with smart contracts on the PlatON 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:
new web3.platon.Contract(jsonInterface[, address][, options])
Parameter:
jsonInterface
-Object
: The json interface for the contract to instantiateaddress
-String
: (optional): The address of the smart contract to call.options
-Object
: (optional): The options of the contract. Some are used as fallbacks for calls and transactions:from
-String
: The address transactions should be made from.gasPrice
-String
: The gas price in von to use for transactions.gas
-Number
: The maximum gas provided for a transaction (gas limit).data
-String
: The byte code of the contract. Used when the contract gets deployed.vmType
-Number
: The contract type. 0 means solidity contract, 1 means WASM contract. The default is the solidity contract. (New field)net_type
-String
: The network type.lat
represents the primary network,lax
represents the test network. The default is to the test network. (New field)
Returns:
Object
: The contract instance with all it's methods and events.
Example:
var myContract = new web3.platon.Contract([...], 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv', {
from: 'lax1zg69v7yszg69v7yszg69v7yszg69v7y3q7dnwf', // default from address
gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
});
options
The options object for the contract instance. from, gas and gasPrice are used as fallback values when sending transactions.
Method:
myContract.options
options
options:
address
-String
: The address where the contract is deployed.jsonInterface
-Array
: The json interface of the contract.data
-String
: The byte code of the contract.from
-String
: The address transactions should be made from.gasPrice
-String
: The gas price in von to use for transactions.gas
-Number
: The maximum gas provided for a transaction (gas limit).
Example:
myContract.options;
> {
address: 'atx1zg69v7yszg69v7yszg69v7yszg69v7y3ut4wvr',
jsonInterface: [...],
from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv',
gasPrice: '10000000000000',
gas: 1000000
}
myContract.options.from = 'lax1zg69v7yszg69v7yszg69v7yszg69v7y3q7dnwf'; // default from address
myContract.options.gasPrice = '20000000000000'; // default gas price in wei
myContract.options.gas = 5000000; // provide as fallback always 5M gas
options.address - contract address
The address used for this contract instance. All transactions generated by web3.js from this contract will contain this address as the “to”. The address will be stored in lowercase.
Method:
myContract.options.address
Property:
address
- String|null
: The address for this contract, or null if it’s not yet set.
Example:
myContract.options.address;
> 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'
// set a new address
myContract.options.address = 'lax...';
options.jsonInterface
jsonInterface
The json interface object derived from the ABI of this contract.
Method:
myContract.options.jsonInterface
Property:
jsonInterface
- Array
: The json interface for this contract. Re-setting this will regenerate the methods and events of the contract instance.
Example:
myContract.options.jsonInterface;
> [{
"type":"function",
"name":"foo",
"inputs": [{"name":"a","type":"uint256"}],
"outputs": [{"name":"b","type":"address"}]
},{
"type":"event",
"name":"Event"
"inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"bytes32","indexed":false}],
}]
// set a new interface
myContract.options.jsonInterface = [...];
deploy
Call this function to deploy the contract to the blockchain. After successful deployment the promise will resolve with a new contract instance.
Method:
myContract.deploy(options)
Parameter:
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. If you deploy a WASM contract, you can refer to WASM contract parameter passing reference。
Returns:
Object
: The transaction object:
arguments
:Array
- The arguments passed to the method before. They can be changed.send
:Function
- Will deploy the contract. The promise will resolve with the new contract instance, instead of the receipt!estimateGas
:Function
- Will estimate the gas used for deploying.encodeABI
:Function
- Encodes the ABI of the deployment, which is contract data + constructor parameters
Example:
myContract.deploy({
data: '0x12345...',
arguments: [123, 'My String']
})
.send({
from: 'atx1zg69v7yszg69v7yszg69v7yszg69v7y3ut4wvr',
gas: 1500000,
gasPrice: '30000000000000'
}, function(error, transactionHash){ ... })
.on('error', function(error){ ... })
.on('transactionHash', function(transactionHash){ ... })
.on('receipt', function(receipt){
console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation', function(confirmationNumber, receipt){ ... })
.then(function(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: 'atx1zg69v7yszg69v7yszg69v7yszg69v7y3ut4wvr',
gas: 1500000,
gasPrice: '30000000000000'
})
.then(function(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(function(err, gas){
console.log(gas);
});
methods
Creates a transaction object for that method, which then can be called, send, estimated.
If it is a WASM contract, you can refer to WASM contract parameter passing reference。 Method:
myContract.methods.myMethod([param1[, param2[, ...]]])
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.
Parameter:
Parameters of any method depend on the smart contracts methods, defined in the JSON interface.
Returns:
Object: The transaction object:
arguments
: Array - The arguments passed to the method before. They can be changed.call
: Function - Will call the “constant” method and execute it's smart contract method in the EVM without sending a transaction (Can’t alter the smart contract state).send
: Function - Will send a transaction to the smart contract and execute it's method (Can alter the smart contract state).estimateGas
: Function - Will estimate the gas used when the method would be executed on chain.encodeABI
: Function - 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.
Example:
// calling a method
myContract.methods.myMethod(123).call({from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'}, function(error, result){
...
});
// or sending and using a promise
myContract.methods.myMethod(123).send({from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'})
.then(function(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: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'})
.on('transactionHash', function(hash){
...
})
.on('receipt', function(receipt){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('error', console.error);
methods.myMethod.call
Will call a “constant” method and execute it's smart contract method in the EVM without sending any transaction. Note calling can not alter the smart contract state.
Method:
myContract.methods.myMethod([param1[, param2[, ...]]]).call(options[, callback])
Parameter:
options
- Object : (optional): The options used for calling.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”.
- gas - Number (optional): The maximum gas provided for this call “transaction” (gas limit).
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 returns Mixed: 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: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'}, function(error, result){
...
});
// using the promise
myContract.methods.myMethod(123).call({from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'})
.then(function(result){
...
});
MULTI-ARGUMENT RETURN:
// Solidity
contract MyContract {
function myFunction() returns(uint256 myNumber, string myString) {
return (23456, "Hello!%");
}
}
// web3.js
var MyContract = new web3.platon.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!%";
}
}
Then in web3.js, the call
method will also return a single value:
// web3.js
var MyContract = new web3.platon.contract(abi, address);
MyContract.methods.myFunction().call()
.then(console.log);
> "Hello!%"
send - methods.myMethod.send
Will send a transaction to the smart contract and execute it's method. Note this can alter the smart contract state.
Method:
myContract.methods.myMethod([param1[, param2[, ...]]]).send(options[, callback])
Parameter:
options
-Object
: The options used for sending.from
-String
: The address the transaction should be sent from.gasPrice
-String
: (optional): The gas price in von to use for this transaction.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 von.
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" returns
String
: is fired right after the transaction is sent and a transaction hash is available. - "receipt" returns
Object
: is fired when the transaction receipt is available. Receipts from contracts will have no logs property, but instead an events property with event names as keys and events as properties. See getPastEvents return values for details about the returned event object. - "confirmation" returns
Number
, 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 minded. - "error" returns
Error and Object|undefined
: Is fired if an error occurs during sending. If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
Example:
// using the callback
myContract.methods.myMethod(123).send({from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'}, function(error, transactionHash){
...
});
// using the promise
myContract.methods.myMethod(123).send({from: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'})
.then(function(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: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'})
.on('transactionHash', function(hash){
...
})
.on('confirmation', function(confirmationNumber, receipt){
...
})
.on('receipt', function(receipt){
// receipt example
console.log(receipt);
> {
"transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
"transactionIndex": 0,
"blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
"blockNumber": 3,
"contractAddress": "lax1fyeszufxwxk62p46djncj86rd553skpptsj8v6",
"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: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'
},
"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.
estimateGas - methods.myMethod.estimateGas
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.
Method:
myContract.methods.myMethod([param1[, param2[, ...]]]).estimateGas(options[, callback])
Parameter:
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 von.
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 returns 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: 'lax1mc9jj4nf487e840j3k0vshjq7n9kj7awe459dv'})
.then(function(gasAmount){
...
})
.catch(function(error){
...
});
encodeABI - methods.myMethod.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.
Method:
myContract.methods.myMethod([param1[, param2[, ...]]]).encodeABI()
Parameter:
none
Returns:
String
: The encoded ABI byte code to send via a transaction or call.
Example:
myContract.methods.myMethod(123).encodeABI();
> '0x58cf5f1000000000000000000000000000000000000000000000000000000000000007B'
events
Subscribe to an event.
Method:
myContract.events.MyEvent([options][, callback])
Parameter:
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 (greater than or equal to) from which to get events on. Pre-defined block numbers as "latest", "earlist", "pending", and "genesis" can also be used.topics
-Array
(optional): This allows to manually set the topics for the event filter. If given the filter property and event signature, (topic0) 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 occours.
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 it's still pending.raw.data
-String
: The data containing non-indexed log parameter.raw.topics
-Array
: An array with
3 years ago