This repository has been archived by the owner on Mar 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
76 lines (61 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import Web3 from "web3";
import metaCoinArtifact from "../../build/contracts/MetaCoin.json";
const App = {
web3: null,
account: null,
meta: null,
start: async function() {
const { web3 } = this;
try {
// get contract instance
const networkId = await web3.eth.net.getId();
const deployedNetwork = metaCoinArtifact.networks[networkId];
this.meta = new web3.eth.Contract(
metaCoinArtifact.abi,
deployedNetwork.address,
);
// get accounts
const accounts = await web3.eth.getAccounts();
this.account = accounts[0];
this.refreshBalance();
} catch (error) {
console.error("Could not connect to contract or chain.");
}
},
refreshBalance: async function() {
const { getBalance } = this.meta.methods;
const balance = await getBalance(this.account).call();
const balanceElement = document.getElementsByClassName("balance")[0];
balanceElement.innerHTML = balance;
},
sendCoin: async function() {
const amount = parseInt(document.getElementById("amount").value);
const receiver = document.getElementById("receiver").value;
this.setStatus("Initiating transaction... (please wait)");
const { sendCoin } = this.meta.methods;
await sendCoin(receiver, amount).send({ from: this.account });
this.setStatus("Transaction complete!");
this.refreshBalance();
},
setStatus: function(message) {
const status = document.getElementById("status");
status.innerHTML = message;
},
};
window.App = App;
window.addEventListener("load", function() {
if (window.ethereum) {
// use MetaMask's provider
App.web3 = new Web3(window.ethereum);
window.ethereum.enable(); // get permission to access accounts
} else {
console.warn(
"No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
App.web3 = new Web3(
new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
);
}
App.start();
});