How to use web3.js to save data on Etay Fong block chain
This article will explain in detail how to use web3.js to save data on the etheric block chain. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
We know that blockchain still has its advantages, such as the unusurable modification of data is of great significance for copyright protection, while the anonymity of addresses has other potential uses. So, how do you write any data, such as images or text, into the ethernet block chain? The following will explain how to use web3.js to implement this function and give the corresponding implementation code.
The core of implementing arbitrary data winding is the use of the web3.eth.sendTransaction () method, and we will complete the task of arbitrary data winding with the help of a transfer transaction. In the transaction object to be sent, you can pass in any hexadecimal string using the data field.
Convert data to hexadecimal strings
We can use the web3.toHex () method to convert a string to a hexadecimal string:
Let data = web3.toHex ('you can write any data to the ethernet block chain')
The resulting data value is: 0x4f6053ef4ee55c064efb610f6570636e519951654ee5592a574a533a575794fe.
Of course, you don't have to use the web3.toHex () method, but you can use any method that can get a hexadecimal string, such as using Buffer in NodeJS:
Let data = '0x' + Buffer.from (' better processing image data using Buffer') .toString ('hex')
The resulting data value is: 0xe4bdbfe794a8427566666572e69bb4e5a5bde5a484e79086e59bbee5838fe695b0e68dae.
Declare the object of the transaction
Next, we need to set the transaction object to be sent. We need to use a transfer transaction to upload the data, so the main fields set are from, to, value, and, of course, data, for which we need to make a transaction:
Let txo = {from: web3.eth.accounts [0], to: web3.eth.accounts [1], value:'0x00', data: data}
If you only have one account, you can transfer it to yourself:)
Send a deal
Finally, call the web3.eth.sendTransaction () method:
Web3.eth.sendTransaction (txo, (error, hash) = > console.log (hash))
When the transaction is successful, you can use etherscan.io to view the input data in the transaction information.
On how to use web3.js to save data on the etheric block chain is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.