-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
166 lines (125 loc) · 6.2 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
//Metamask sending trasactions:
//https://docs.metamask.io/guide/sending-transactions.html#transaction-parameters
detectMetamaskInstalled() //When the page is opened check for error handling issues.
let accounts = []; ////Empty array to be filled once Metamask is called.
document.getElementById("enableEthereumButton").innerHTML = "Connect Metamask 🦊"
document.getElementById("getValueStateSmartContract").innerHTML = "Loading..."
const baseSepoliaChainId = 84532;
const provider = new ethers.providers.Web3Provider(window.ethereum); //Imported ethers from index.html with "<script src="https://cdn.ethers.io/lib/ethers-5.6.umd.min.js" type="text/javascript"></script>".
// const signer = provider.getSigner(); //Do this when the user clicks "enableEthereumButton" which will call getAccount() to get the signer private key for the provider.
const contractAddress_JS = '0xeD62F27e9e886A27510Dc491F5530996719cEd3d'
const contractABI_JS = [{"anonymous":false,"inputs":[],"name":"setEvent","type":"event"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"set","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"storedData","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]
const contractDefined_JS = new ethers.Contract(contractAddress_JS, contractABI_JS, provider);
// const contractDefined_JS = new ethers.Contract(contractAddress_JS, contractABI_JS, signer);
getDataOnChainToLoad()
async function getDataOnChainToLoad(){
let chainIdConnected = await getChainIdConnected();
if(chainIdConnected == baseSepoliaChainId){
getStoredData()
}
if(chainIdConnected != baseSepoliaChainId){
document.getElementById("getValueStateSmartContract").innerHTML = "Install Metamask and select Base Sepolia Testnet to have a Web3 provider to read blockchain data."
}
}
async function getStoredData() {
let storedDataCallValue = await contractDefined_JS.storedData()
if(storedDataCallValue === undefined){
document.getElementById("getValueStateSmartContract").innerHTML = "Install Metamask and select Sepolia Testnet to have a Web3 provider to read blockchain data."
}
else{
document.getElementById("getValueStateSmartContract").innerHTML = storedDataCallValue
}
}
async function sentTxAsync(x) {
const callDataObject = await contractDefined_JS.populateTransaction.set(x);
const txData = callDataObject.data;
ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: contractAddress_JS,
data: txData
},
],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);
}
contractDefined_JS.on("setEvent", () => {
getStoredData()
});
//Connect to Metamask.
const ethereumButton = document.querySelector('#enableEthereumButton');
ethereumButton.addEventListener('click', () => {
detectMetamaskInstalled()
enableMetamaskOnSepolia()
});
// MODIFY CONTRACT STATE WITH SET FUNCTION WITH PREDEFINED DATA FROM WEB3.JS
const changeStateInContractEvent = document.querySelector('.changeStateInContractEvent');
changeStateInContractEvent.addEventListener('click', () => {
checkAddressMissingMetamask()
var inputContractText = document.getElementById("setValueSmartContract").value.toString();
if(/^\d+$/.test(inputContractText)==false) {
alert("Can only accept numeric characters.")
return
}
if(BigInt(inputContractText) > (BigInt(2**256)-BigInt(1)) ) {
alert("Value is larger than uin256 max value ((2^256)-1).")
return
}
sentTxAsync(inputContractText)
})
//If Metamask is not detected the user will be told to install Metamask.
function detectMetamaskInstalled(){
try{
ethereum.isMetaMask
}
catch(missingMetamask) {
alert("Metamask not detected in browser! Install Metamask browser extension, then refresh page!")
document.getElementById("getValueStateSmartContract").innerHTML = "Install Metamask and select Sepolia Testnet to have a Web3 provider to read blockchain data."
}
}
//Alert user to connect their Metamask address to the site before doing any transactions.
function checkAddressMissingMetamask() {
if(accounts.length == 0) {
alert("No address from Metamask found. Click the top button to connect your Metamask account then try again without refreshing the page.")
}
}
async function getChainIdConnected() {
const connectedNetworkObject = await provider.getNetwork();
const chainIdConnected = connectedNetworkObject.chainId;
return chainIdConnected
}
async function getAccount() {
accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const signer = provider.getSigner();
document.getElementById("enableEthereumButton").innerText = accounts[0].substr(0,5) + "..." + accounts[0].substr(38,4)
}
async function enableMetamaskOnSepolia() {
//Get account details from Metamask wallet.
getAccount();
// Updated chainId request method suggested by Metamask.
let chainIdConnected = await window.ethereum.request({method: 'net_version'});
// // Outdated chainId request method which might get deprecated:
// // https://github.com/MetaMask/metamask-improvement-proposals/discussions/23
// let chainIdConnected = window.ethereum.networkVersion;
console.log("chainIdConnected: " + chainIdConnected)
//Check if user is on the Sepolia testnet. If not, alert them to change to Sepolia.
if(chainIdConnected != baseSepoliaChainId){
// alert("You are not on the Sepolia Testnet! Please switch to Sepolia and refresh page.")
try{
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{
chainId: "0x" + baseSepoliaChainId.toString(16) //Convert decimal to hex string.
}]
})
location.reload();
// alert("Failed to add the network at chainId " + baseSepoliaChainId + " with wallet_addEthereumChain request. Add the network with https://chainlist.org/ or do it manually. Error log: " + error.message)
} catch (error) {
alert("Failed to add the network at chainId " + baseSepoliaChainId + " with wallet_addEthereumChain request. Add the network with https://chainlist.org/ or do it manually. Error log: " + error.message)
}
}
}