-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebflow-Javascript.js
189 lines (168 loc) · 6.98 KB
/
Webflow-Javascript.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@walletconnect/web3-provider/dist/umd/index.min.js"></script>
<script>
let web3;
const erc20TokenAddress = '0x11FAa53761d30ce3A0D8a62fc05F798657D583Fc';
const erc20TokenDecimals = 18;
const minABI = [
{
"constant": true,
"inputs": [{"name": "_owner", "type": "address"}],
"name": "balanceOf",
"outputs": [{"name": "balance", "type": "uint256"}],
"type": "function"
}
];
const chainData = {
'0x64': {
name: 'Gnosis Chain',
iconUrl: 'gnosis-icon.png'
},
'0x1': {
name: 'Ethereum',
iconUrl: 'ethereum-icon.png'
},
'0x89': {
name: 'Polygon',
iconUrl: 'polygon-icon.png'
},
'0x5': {
name: 'Goerli Testnet',
iconUrl: 'goerli-icon.png'
}
};
function formatNumber(num) {
if (num >= 1e6) {
return (num / 1e6).toFixed(2) + 'M';
} else {
return num.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
}
function truncateAddress(address) {
return address.substring(0, 6) + '...' + address.substring(address.length - 4);
}
async function getENSName(address) {
try {
const ensName = await web3.eth.ens.resolve(address);
return ensName;
} catch (error) {
console.error('Error fetching ENS name:', error);
return null;
}
}
async function connectWallet() {
if (typeof window.ethereum !== 'undefined') {
web3 = new Web3(window.ethereum);
try {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
sessionStorage.setItem('connectedAccount', accounts[0]);
updateUIAfterConnection(accounts[0]);
} catch (error) {
console.error('User denied account access:', error);
}
} else {
const provider = new WalletConnectProvider.default({
rpc: { 100: 'https://rpc.gnosischain.com/' },
qrcodeModalOptions: { mobileLinks: ["rainbow", "metamask", "argent", "trust", "imtoken", "pillar"] },
});
web3 = new Web3(provider);
try {
await provider.enable();
const accounts = await web3.eth.getAccounts();
sessionStorage.setItem('connectedAccount', accounts[0]);
updateUIAfterConnection(accounts[0]);
} catch (error) {
console.error('Could not get accounts via WalletConnect:', error);
}
}
}
function updateUIAfterConnection(account) {
document.getElementById('connectWalletButton').style.display = '';
document.getElementById('disconnectButton').style.display = 'flex';
// Update wallet info text and reset its color
const walletInfoElement = document.getElementById('walletInfo');
walletInfoElement.innerText = truncateAddress(account);
walletInfoElement.style.color = '#FFFFFF'; // Reset color to default
getENSName(account).then(ensName => {
document.getElementById('UserName').innerText = ensName || 'No ENS Name';
});
checkChainId();
getERC20Balance(account);
}
async function checkChainId() {
const chainId = await ethereum.request({ method: 'eth_chainId' });
const chainInfo = chainData[chainId] || { name: 'Unknown Chain', iconUrl: 'default-icon.png' };
document.getElementById('chainName').innerText = chainInfo.name;
document.getElementById('chainIcon').src = chainInfo.iconUrl;
getERC20Balance(sessionStorage.getItem('connectedAccount'));
}
async function switchChain(chainId, rpcUrl, chainName, iconUrl) {
try {
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: chainId }],
});
} catch (switchError) {
if (switchError.code === 4902) {
try {
await ethereum.request({
method: 'wallet_addEthereumChain',
params: [{ chainId: chainId, rpcUrls: [rpcUrl], chainName: chainName }],
});
} catch (addError) {
console.error('Failed to add the chain:', addError);
}
} else {
console.error('Failed to switch the chain:', switchError);
}
}
document.getElementById('chainName').innerText = chainName;
document.getElementById('chainIcon').src = iconUrl;
getERC20Balance(sessionStorage.getItem('connectedAccount'));
}
async function getERC20Balance(account) {
const contract = new web3.eth.Contract(minABI, erc20TokenAddress);
contract.methods.balanceOf(account).call().then((balance) => {
const tokenBalance = balance / Math.pow(10, erc20TokenDecimals);
document.getElementById('tokenBalance').innerText = formatNumber(tokenBalance);
}).catch((err) => {
console.error('Error getting token balance:', err);
});
}
function disconnectWallet() {
// Remove the connected account from session storage
sessionStorage.removeItem('connectedAccount');
// Reset UI elements to their default state
document.getElementById('connectWalletButton').style.display = '';
document.getElementById('disconnectButton').style.display = 'none';
// Update wallet info text and change its color to red
const walletInfoElement = document.getElementById('walletInfo');
walletInfoElement.innerText = 'Wallet Disconnected';
walletInfoElement.style.color = '#EE2424'; // Change text color to red
document.getElementById('tokenBalance').innerText = '0.00';
document.getElementById('chainName').innerText = 'Connect Wallet';
document.getElementById('chainIcon').src = 'default-icon.png';
// Disconnect the web3 provider if it exists and supports disconnection
if (web3 && web3.currentProvider && typeof web3.currentProvider.disconnect === 'function') {
web3.currentProvider.disconnect();
}
// Set web3 to null to signify that there is no active connection
web3 = null;
}
window.addEventListener('DOMContentLoaded', () => {
const storedAccount = sessionStorage.getItem('connectedAccount');
if (storedAccount) {
web3 = new Web3(window.ethereum);
updateUIAfterConnection(storedAccount);
}
document.getElementById('connectWalletButton').addEventListener('click', connectWallet);
document.getElementById('disconnectButton').addEventListener('click', disconnectWallet);
document.querySelector('.gnosis-chain-button').addEventListener('click', () => switchChain('0x64', 'https://rpc.gnosischain.com/', 'Gnosis Chain', 'gnosis-icon.png'));
document.querySelector('.ethereum-button').addEventListener('click', () => switchChain('0x1', 'https://mainnet.infura.io/v3/d97365070ebd437eb4d080bf170ca08f', 'Ethereum', 'ethereum-icon.png'));
document.querySelector('.polygon-button').addEventListener('click', () => switchChain('0x89', 'https://polygon-rpc.com/', 'Polygon', 'polygon-icon.png'));
document.querySelector('.goerli-testnet-button').addEventListener('click', () => switchChain('0x5', 'https://goerli.infura.io/v3/d97365070ebd437eb4d080bf170ca08f', 'Goerli Testnet', 'goerli-icon.png'));
});
</script>