Vue develops ether system

Generate mnemonic & mnemonic generate address private key

 ethereumjs-util	6.2.1
 ethereumjs-wallet	1.0.2
 bip39				3.0.4

let bip39 = require('bip39')
let hdkey = require('ethereumjs-wallet').hdkey
let util = require('ethereumjs-util')


async function create(callback){
    
    
  // 1.生成助记词
  let mnemonic = bip39.generateMnemonic()
  //传入助记词  即可助记词生成	私钥&地址
  //mnemonic = "reward nation sense clinic catch region vocal perfect turtle heavy among picnic"
  //2.将助记词转成seed
  let seed = bip39.mnemonicToSeedSync(mnemonic)
  // //3.通过hdkey将seed生成HD Wallet
  let hdWallet = hdkey.fromMasterSeed(seed);
    //4.生成钱包中在 m/44'/60'/0'/0/0 路径的keypair
      let key = hdWallet.derivePath("m/44'/60'/0'/0/0")
      //5.从keypair中获取私钥
      let privateKey = util.bufferToHex(key._hdkey._privateKey);
      //6.从keypair中获取公钥
      // console.log("公钥:" + util.bufferToHex(key._hdkey._publicKey))
      //7.使用keypair中的公钥生成地址
      let address = util.pubToAddress(key._hdkey._publicKey, true)
      //编码地址
      address = util.toChecksumAddress(address.toString('hex'))
      // console.log("地址:" + address,"\n")
  // }
  callback(mnemonic, privateKey, address)
}

export default {
    
    
  create
}

Balance Inquiry & Transaction


import {
    
    Transaction} from "ethereumjs-tx";

var web3
if (typeof web3 !== 'undefined') {
    
    
	web3 = new Web3(web3.currentProvider);
} else {
    
    
	// set the provider you want from Web3.providers
	web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/***"));
}

//创建账户
function create(){
    
    
	let acc = web3.eth.accounts.create()
	return acc
}
//获取gas价格
async function getGasPrice(){
    
    
	let price
	await web3.eth.getGasPrice().then((res) => {
    
    
		price = res
	})
	return price
}
//查询账户余额
async function balance(account){
    
    
	let balance
	await web3.eth.getBalance(account).then((res) => {
    
    
		balance = web3.utils.fromWei(res, 'ether')
	})
	return balance
}
//交易eth
async function tran(fromAdd, to, num, limit, privatekey){
    
    
	let gasPrice = await getGasPrice();
	console.log(gasPrice)
	let hash;
	await web3.eth.getTransactionCount(fromAdd, (err,txcount)=>{
    
    
		if(err){
    
    
			console.log(err)
		} else{
    
    
			const txObject = {
    
    
				nonce: web3.utils.toHex(txcount),
				to: to,
				value: web3.utils.toHex(web3.utils.toWei(num, 'ether')),
				gasLimit: web3.utils.toHex(limit),
				gasPrice: web3.utils.toHex(gasPrice)
			}
			console.log(txObject)
			// 签署交易
			const tx = new Transaction(txObject, {
    
    
				chain: 'ropsten',
				hardfork: 'petersburg'
			})
			tx.sign(Buffer.from(privatekey.substring(2),'hex'))
			const serializedTx = tx.serialize()
			const raw = '0x' + serializedTx.toString('hex')
			// 广播交易

			web3.eth.sendSignedTransaction(raw , (err, txHash) => {
    
    
				if (!err){
    
    
					hash = txHash
				}else{
    
    
					console.log(err);
				}
			})
		}
	})
	return hash
}
export default {
    
    
	create,
	getGasPrice,
	balance,
	tran
}

token operation


import {
    
    Transaction} from "ethereumjs-tx";

var web3
if (typeof web3 !== 'undefined') {
    
    
	web3 = new Web3(web3.currentProvider);
} else {
    
    
	// set the provider you want from Web3.providers
	web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"));
}
let abi = `[{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]`
let conAdd = "0x....."
let contract = new web3.eth.Contract(JSON.parse(abi), conAdd);

async function getGasPrice(){
    
    
	let price
	await web3.eth.getGasPrice().then((res) => {
    
    
		price = res
	})
	return price
}

async function balance(account,callback) {
    
    
  await contract.methods.balanceOf(account).call().then((res) => {
    
    
    let balance = web3.utils.fromWei(res, 'ether')
    callback(balance)
  })
}

async function tran(from,to, num,limit, priKey) {
    
    
	let gasPrice = await getGasPrice();
	let hash;
	await web3.eth.getTransactionCount(from, (err,txcount)=>{
    
    
		if(err){
    
    
			console.log(err)
		} else{
    
    
			const txObject = {
    
    
				nonce: web3.utils.toHex(txcount),
				to: conAdd,
				gasLimit: web3.utils.toHex(limit),
				gasPrice: web3.utils.toHex(gasPrice*2),
				data: contract.methods.transfer(to, web3.utils.toWei(num, 'ether')).encodeABI()
			}// console.log(txObject)
			// 签署交易
			const tx = new Transaction(txObject, {
    
    
				chain: 'ropsten',
				hardfork: 'petersburg'
			})
			tx.sign(Buffer.from(priKey.substring(2),'hex'))
			const serializedTx = tx.serialize()
			const raw = '0x' + serializedTx.toString('hex')
			// 广播交易
			web3.eth.sendSignedTransaction(raw , (err, txHash) => {
    
    
				if (!err){
    
    
					hash = txHash
					console.log("success:" + txHash)
					return hash
				}else{
    
    
					console.log(err);
				}
			})
		}
	})
}
export default {
    
    
	tran,
  balance
}

Guess you like

Origin blog.csdn.net/weixin_42704356/article/details/129043700