使用web3.js连接ropsten测试网络本地签名发送交易

一.前言

在实际开发过程中,我们钱包的私钥大概率是要存在本地,那么我们就需要在本地签名,然后发送交易到节点,由节点帮我们广播交易出去。

 

二.流程

1.引入对应的标准库 

通过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

引入需要的库,方便我们操作,引入后在package.json文件可看到对应的依赖如下

 "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.在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.定义初始化web3的方法

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

在页面初始化的时候 调用这个方法可以看到浏览器的打印,看到Web3对象 说明初始化成功了。

4.接下来我们可以导入助记词,保存我们的私钥,我这里就取第一个地址和私钥

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.有了私钥我们就可以调用转账的方法了,fromAccount是我们存在本地的账户 私钥我们能直接拿到,用来测试

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.点击转账后,我们本地签名好的交易就会被发送到测试节点上了,可以看到一个txhash返回0x0e2bbc47eeecfd898da620303be0f081b2098be154d6ff7ac591f6555f73b909

通过这个txHash 我们可以去 https://ropsten.etherscan.io/tx/0x0e2bbc47eeecfd898da620303be0f081b2098be154d6ff7ac591f6555f73b909 查看到我们的交易。

猜你喜欢

转载自blog.csdn.net/cjy_win/article/details/117251539