Ethereum, like Bitcoin, has a concept of the longest chain, and therefore a concept of the number of confirmed transactions. When an Ethereum exchange is added to the blockchain on a block, the number of confirmations for the transaction is 1, and for each additional block, the number of confirmations for the transaction is 1. Obviously, the more confirmations an Ethereum transaction has, the deeper it is buried in the blockchain, the less likely it is to be tampered with. So how do you get a confirmation number for an Ethereum transaction?
If you want to quickly master the development of Ethereum application, I recommend the Introduction of Ethereum smart Contract and DApp development by Huizhi. Based on the online programming environment, I can complete the actual development of a voting DApp. If you have any questions, you can also consult the teaching assistant.
To get the number of confirmations for an Ethereum transaction, two RPC calls are used:
- Eth_getTransactionReceipt: Gets the transaction receipt
- Eth_blockNumber: obtains the latest block number
First get the specified transaction receipt with the eth_getTransactionReceipt call, for example, The following command to get deals 0 xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238 receipt:
~$ curl -X POST --data '{" jsonrpc ":" 2.0 ", "method" : "eth_getTransactionReceipt." "params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"], "id":1}' http://localhost:8545
Copy the code
The block number of the exchange can be obtained in the result:
{
"id": 1,"jsonrpc":"2.0"."result": {... blockNumber:'0xb', // Block 11... }}Copy the code
You can then use the eth_blockNumber call at any subsequent time to get the current latest block information, for example:
~$ curl -X POST --data '{" jsonrpc ":" 2.0 ", "method" : "eth_blockNumber", "params" : [], "id" : 83}' http://localhost:8545
Copy the code
The latest block number can be obtained in the result:
{
"id": 83,"jsonrpc": "2.0"."result": "0xf"// block 15}Copy the code
Take the number of the last block in the blockchain, subtract the block number of the exchange, and add 1 to get a confirmation number of Ethereum transactions:
Trade confirmations = latest block number - Exchange in Block number + 1 = 15-11 + 1 = 5Copy the code
Get ethereum transaction confirmations using web3.js
Based on the above principle, it is easy to write web3.js code to get ethereum transaction confirmations:
async function getTxConfirms(txhash){
const receipt = await web3.eth.getTransactionReceipt(txhash)
//later...
const latest = await web3.eth.getBlockNumber()
//confirms
return latest - receipt.number + 1
}
Copy the code
Call the getTxConfirms() function implemented above to get the current number of guarantees made:
getTxConfirms('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b')
.then(confirms => console.log(confirms))
Copy the code
How to obtain the confirmation number of Ethereum transaction – Hui Zhi net