My getWeb3.js file:
import Web3 from 'web3'
export default async () => {
var web3Provider = null;
if (typeof window.ethereum !== "undefined") {
web3 = new Web3(window.ethereum)
try {
// Request account access if needed
await window.ethereum.enable()
// Acccounts now exposed
} catch (error) {
// User denied account access...
console.log("MetaMask cannot be enabled!")
}
}
// Legacy dapp browsers...
else if (window.web3) {
web3Provider = new Web3(window.web3.currentProvider);
}
// Non-dapp browsers...we use ganache
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
console.log("ganache")
}
return web3
}
Here is how I call getWeb3
, it always complain on this var accounts = await this.web3.eth.getAccounts()
, saying this.web3.eth is undefined
export default class PaypalContract {
constructor() {
console.log(instance)
if (!instance) {
```
instance = this
this.web3 = getWeb3()
console.log("web3 init:",this.web3)
this.contract = contract(PaypalContractMeta)
this.contract.setProvider(this.web3)
this.usdtcontract = contract(usdtContractMeta)
this.usdtcontract.setProvider(this.web3)
}
return instance
```
}
async payToContract(coin_address,recipient,price,order_id) {
//const { eth: { accounts: [ account ] } } = this.web3
```
var accounts = await this.web3.eth.getAccounts()
var account = accounts[0]
console.log('account:',account)
console.log("coin address:",coin_address)
const coincontractInstance = await this.usdtcontract.at(coin_address)
const contractInstance = await this.contract.deployed()
var priceUnit = this.web3.utils.toBN(price).mul(this.web3.utils.toBN(this.web3.utils.toWei("1")))
await coincontractInstance.approve(contractInstance.address,priceUnit,{from: account})
await contractInstance.deposit(coin_address,recipient,priceUnit,order_id,{ from: account })
await contractInstance.setExpiryDate(order_id,0,{ from: account })
```
}