123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import API from '@/api'
- // import Web3 from 'web3'
- import { showError } from '@/util/util'
- import { Promise } from 'es6-promise'
- let ethHelper = {
- isInitEth: false,
- curAccount: '',
- network: 0,
- checkMainNetwork () {
- return new Promise((resolve, reject) => {
- window.web3.version.getNetwork((err, netId) => {
- if (netId != 1) {
- console.log(err)
- return reject(new Error(''))
- } else {
- resolve()
- }
- })
- })
- },
- /**
- * @des 签名认证
- */
- async initEth () {
- if (!window.ethereum || !window.web3) {
- showError('你还没有安装eth插件')
- return Promise.reject(new Error(''))
- }
- if (window.ethereum && !this.isInitEth) {
- await window.ethereum.enable()
- this.isInitEth = true
- }
- await this.checkMainNetwork()
- let accounts = window.web3.eth.accounts
- let account = this.account = accounts[0]
- if (account) {
- this.curAccount = account
- let randomRes = await API.user.getRandom2({ account: account })
- return new Promise((resolve, reject) => {
- try {
- window.web3.personal.sign(window.web3.fromUtf8(`Welcome to MeeChat! Decentralization Social Platform (${randomRes.data.data.random})`), window.web3.eth.coinbase, (err, rs) => {
- if (err) {
- reject(err)
- } else {
- resolve({
- account: account,
- sign: rs
- })
- }
- })
- } catch (err) {
- reject(err)
- }
- })
- } else {
- return Promise.reject(new Error(''))
- }
- },
- /**
- * @des 转账
- * @param {Number} money 转账金额
- */
- async doTransfer (money) {
- try {
- await this.initEth()
- let balance = await window.web3.eth.getBalance(this.curAccount)
- if (10e17 * money > balance) {
- showError('The balance of account is insufficient.')
- return
- }
- const txData = {
- from: this.account,
- to: '0x42eb768f2244c8811c63729a21a3569731535f06',
- value: window.web3.utils.toWei(money.toString(), 'ether')
- }
- return new Promise((resolve, reject) => {
- window.web3.eth.sendTransaction(txData, (err, txHash) => {
- if (err) {
- reject(err)
- } else {
- // this.waitEthTransfer(txHash)
- resolve()
- }
- })
- })
- } catch (e) {
- return Promise.reject(e)
- }
- },
- // 检测转账进度
- waitEthTransfer (txHash) {
- window.web3.eth.getTransactionReceipt(txHash, (err, res) => {
- console.log('waitEthTransfer', err, res)
- if (err) {
- console.error(err)
- }
- if (!res) {
- setTimeout(this.waitEthTransfer, 1000, txHash)
- } else if (res && res.status) {
- this.visible = false
- }
- console.log('res', res)
- })
- }
- }
- export default ethHelper
|