Use web3.js to connect to the ropsten test network to locally sign and send transactions

I. Introduction

In the actual development process, the private key of our wallet is likely to exist locally, so we need to sign locally, and then send the transaction to the node, and the node will broadcast the transaction for us.

 

2. Process

1. Introduce the corresponding standard library 

Via npm install web3   https://www.npmjs.com/package/web3    

    npm install  bip39 https://www.npmjs.com/package/bip39

    npm install  ethereumjs-tx   https://www.npmjs.com/package/ethereumjs-tx  

    npm install ethereumjs-util  https://www.npmjs.com/package/ethereumjs-util

    npm install ethereumjs-wallet     https://www.npmjs.com/package/ethereumjs-wallet

Introduce the required libraries to facilitate our operation. After introduction, you can see the corresponding dependencies in the package.json file as follows

 "dependencies": {
    "bip39": "^3.0.4",
    "ethereumjs-tx": "^2.1.2",
    "ethereumjs-util": "^6.2.1",
    "ethereumjs-wallet": "^1.0.1",
    "web3": "^1.3.6"
  }

2. Introduce the required library in the corresponding interface of vue.

<script >
	const Web3 = require('web3');
	const Tx = require('ethereumjs-tx').Transaction
	const BigNumber = require('bignumber.js');
	const Ether = new BigNumber(10e+17);
    //引入我们自己封装的一些方法
	const grgWallet= require('../../common/grgwallet.js')
    //连接的测试节点
	const url="https://ropsten.infura.io/v3/54828bfa2cb14873a43512fd8d3fc24b" 
    //定义页面的web3对象
	let web3;
</script>

3. Define the method of initializing web3

    //初始化web3
	async initWeb3(){
				 web3 = new Web3(new Web3.providers.HttpProvider(url));
				console.log(web3)
			}

Call this method when the page is initialized to see the browser's print, and seeing the Web3 object indicates that the initialization is successful.

4. Next, we can import the mnemonic and save our private key. I will take the first address and private key here.

async importWord(){
				let word="message convince........." //这里是你的12个助记词
				let pri=await grgWallet.getPrivatekeyWithMnemonic(word,0)
				let address=grgWallet.getPrivatekeyAddress(pri)
				uni.setStorageSync('address',address)
				uni.setStorageSync('privateKey',pri)
				console.log('我的地址',address)
			},

5. With the private key, we can call the transfer method. fromAccount is the private key of our local account that we can get directly for testing.

transcation(){
				
				
				// let fromAccount="0x79b4aded3f376c60cc4392b2641404402003213d"
				// let toAccount="0x02232F0F0578A5C0988263511A6cDFCBdC3c9BD3"
				if(this.from==''||this.to==''){
					this.$u.toast('地址为空')
					return
				}
				
				let fromAccount=this.from
				let toAccount=this.to
                //获取当前节点的平均gas价格
				web3.eth.getGasPrice().then(res=>{
					console.log('gasPrice--',res)
					let gasPrice=res
                      //获取该账户的nonece
					web3.eth.getTransactionCount(fromAccount).then(nonce=>{
						console.log('nonce---',nonce)
						let gasLimit = 300000;					
						let gas=6000000
						let value=web3.utils.toWei('1', 'ether')
						var rawTransaction = {
						    "from": fromAccount,
						    "nonce": web3.utils.toHex(count+1),
						    "gasPrice": web3.utils.toHex(gasPrice),
						    "gasLimit": web3.utils.toHex(gasLimit),
						    "to": toAccount,
						    "value": web3.utils.toHex(value),
						    "data": '0x0',
							//自定义
							// "common":{
							// 	customChain:{
							// 		name:"",
							// 		"networkId":5777,
							// 		"chainId":""
							// 	}
							// },
							
						};
						console.log('交易数据--',rawTransaction)
						let privateKey=uni.getStorageSync('privateKey')
						 var index=privateKey.lastIndexOf("0x");
						 privateKey=privateKey.substring(index+2,privateKey.length);
						 console.log('截取的私钥',privateKey)
						// 读取私钥,这里不包含‘0x’两个字符
						var privKey = new Buffer.from(privateKey, 'hex');
						var tx = new Tx(rawTransaction,{chain:'ropsten',
							 hardfork: 'petersburg'});
						// var tx = new Tx(rawTransaction,{chain:'FRIGHTENING-PROSE',
						// 	 hardfork: 'petersburg'});
						// 用私钥签名交易信息
						tx.sign(privKey);
						var serializedTx = tx.serialize();
						
						// 发送交易
						web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), 
						    function(err, hash) {
						        if (!err){
									console.log('转账成功',hash);
									uni.setStorageSync('txhash',hash)
								} else{
									console.log(err);
								}
						         
						}).on('receipt', res=>{
							console.log('监听状态',res)
						});;
					})
				}).catch(err=>{
					console.log('获取价格报错',err)
				})
			
			},

6. After clicking transfer, our local signed transaction will be sent to the test node. You can see that a txhash returns 0x0e2bbc47eeecfd898da620303be0f081b2098be154d6ff7ac591f6555f73b909

Through this txHash we can go to  https://ropsten.etherscan.io/tx/0x0e2bbc47eeecfd898da620303be0f081b2098be154d6ff7ac591f6555f73b909  to view our transaction.

Guess you like

Origin blog.csdn.net/cjy_win/article/details/117251539