-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
240 lines (205 loc) · 7.92 KB
/
utils.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import { ethers } from 'ethers';
import { apePolygonAmoyAddress } from './contractAddresses';
import ApeNotReal from './hardhat-contract/artifacts/contracts/ApeNotReal.sol/ApeNotReal.json';
// Function to initialize ethers provider
export async function initializeProvider() {
try {
if (typeof window.ethereum === 'undefined') {
throw new Error('MetaMask is not installed. Please consider installing it: https://metamask.io/download.html');
}
const provider = new ethers.BrowserProvider(window.ethereum);
await window.ethereum.request({ method: 'eth_requestAccounts' });
return provider;
} catch (error) {
console.error('Error initializing provider:', error);
throw error;
}
}
// Function to connect wallet
export async function connectWallet() {
try {
const provider = await initializeProvider();
const network = await provider.getNetwork();
if (network.name !== 'matic-amoy') {
alert('Unsupported network. Please switch to Polygon Amoy Testnet');
return null;
}
const [currentWalletAddress] = await window.ethereum.request({
method: 'eth_requestAccounts',
});
const ethBalance = await provider.getBalance(currentWalletAddress);
const formattedEthBalance = ethers.formatEther(ethBalance);
const nft = await checkNFTBalanceAndFetchMetadata(provider, currentWalletAddress)
return {
currentWalletAddress,
provider,
networkName: network.name,
ethBalance: parseFloat(formattedEthBalance),
apeNotRealAvs: nft.apeNotRealAvs,
itemBalance: nft.itemBalance
};
} catch (error) {
console.error('Error connecting wallet:', error);
throw error;
}
}
// Function to check NFT balance and fetch metadata
export async function checkNFTBalanceAndFetchMetadata(provider, currentWalletAddress) {
try {
const apeNotReal = new ethers.Contract(apePolygonAmoyAddress, ApeNotReal.abi, provider);
const itemBalance = await apeNotReal.balanceOf(currentWalletAddress);
const avs = [];
if (itemBalance > 0) {
const tokensId = await apeNotReal.tokensOfOwner(currentWalletAddress);
for (let i = 0; i < tokensId.length; i++) {
const metaURI = 'https://ipfs.io/ipfs/' + (await apeNotReal.tokenURI(tokensId[i])).replace('ipfs://', '');
const metaResponse = await fetch(metaURI);
const metajson = await metaResponse.json();
avs.push(metajson.image);
}
} else {
console.log('You do not have NFTs yet');
}
return {
itemBalance: parseInt(itemBalance.toString()),
apeNotRealAvs: avs
};
} catch (error) {
console.error('Error checking NFT balance and fetching metadata:', error);
throw error;
}
}
// Function to mint NFT
export async function mint() {
try {
const provider = await initializeProvider();
const network = await provider.getNetwork();
if (network.name !== 'matic-amoy') {
alert('Unsupported network. Please switch to Polygon Amoy Testnet');
return;
}
const signer = await provider.getSigner();
const apeNotReal = new ethers.Contract(apePolygonAmoyAddress, ApeNotReal.abi, signer);
console.log('Initialize payment');
const nftItem = await apeNotReal.mintNFTs(1, {
value: ethers.parseEther('0.1'),
gasLimit: 300000,
gasPrice: ethers.parseUnits('50', 'gwei'),
});
console.log('Minting... please wait');
const receipt = await nftItem.wait();
console.log(`Minted, see transaction: https://amoy.polygonscan.com/tx/${receipt.transactionHash}`);
console.log('NFT Item:', nftItem);
} catch (error) {
console.error('Error minting NFT:', error);
throw error;
}
}
// export async function connectWallet() {
// if (typeof window.ethereum !== 'undefined') {
// try {
// const provider = new ethers.BrowserProvider(window.ethereum);
// // await window.ethereum.request({ method: 'eth_requestAccounts' });
// const [currentWalletAddress] = await window.ethereum.request({
// method: 'eth_requestAccounts',
// });
// const network = await provider.getNetwork();
// if (network.name !== 'matic-amoy') {
// alert('Unsupported network. Please switch to Polygon Amoy Testnet');
// return null;
// }
// // Get ETH balance
// const ethBalance = await provider.getBalance(currentWalletAddress);
// const formattedEthBalance = ethers.formatEther(ethBalance);
// let apeNotReal = new ethers.Contract(
// apePolygonAmoyAddress,
// ApeNotReal.abi,
// provider
// );
// // Get NFT balance
// let itemBalance = await apeNotReal.balanceOf(currentWalletAddress);
// // Check if this account has a apeNotReal NFTs
// if (itemBalance > 0) {
// let avs = [];
// // Get tokens array of owner
// const tokensId = await apeNotReal.tokensOfOwner(currentWalletAddress);
// for (let i = 0; i < tokensId.length; i++) {
// // Get token metadata
// const metaURI = 'https://ipfs.io/ipfs/' +
// (await apeNotReal.tokenURI(tokensId[i])).replace('ipfs://', '');
// // load metadata
// // const [meta] = await Promise.all([fetch(metaURI)]);
// const meta = await fetch(metaURI);
// const metajson = await meta.json();
// // get attributes
// avs.push(metajson.image);
// }
// return {
// currentWalletAddress,
// provider,
// networkName: network.name,
// ethBalance: parseFloat(formattedEthBalance),
// itemBalance: parseInt(itemBalance.toString()),
// apeNotRealAvs: avs,
// networkDotIndicator: 'my-auto w-2.5 h-2.5 bg-teal-500 rounded-full'
// };
// } else {
// alert('You do not have NFTs yet');
// return {
// currentWalletAddress,
// provider,
// networkName: network.name,
// ethBalance: parseFloat(formattedEthBalance),
// itemBalance: parseInt(itemBalance.toString()),
// apeNotRealAvs: [],
// networkDotIndicator: 'my-auto w-2.5 h-2.5 bg-teal-500 rounded-full'
// };
// }
// } catch (error) {
// console.error('Error connecting wallet:', error);
// return null;
// }
// } else {
// alert('MetaMask is not installed. Please consider installing it: https://metamask.io/download.html');
// return null;
// }
// }
// export async function mint() {
// if (typeof window.ethereum !== 'undefined') {
// try {
// // Initialize the Web3 provider
// const provider = new ethers.BrowserProvider(window.ethereum);
// // Request accounts access
// await provider.send('eth_requestAccounts', []);
// // Get network details
// const network = await provider.getNetwork();
// if (network.name !== 'matic-amoy') {
// alert('Unsupported network. Please switch to Polygon Amoy Testnet');
// return;
// }
// // Get the signer
// const signer = await provider.getSigner();
// // Initialize the contract with the signer
// const apeNotReal = new ethers.Contract(
// apePolygonAmoyAddress,
// ApeNotReal.abi,
// signer
// );
// // Mint an NFT
// console.log('Initialize payment');
// const nftItem = await apeNotReal.mintNFTs(1, {
// value: ethers.parseEther('0.1'),
// gasLimit: 300000,
// gasPrice: ethers.parseUnits('50', 'gwei'),
// });
// console.log('Minting... please wait');
// const receipt = await nftItem.wait();
// console.log(`Minted, see transaction: https://amoy.polygonscan.com/tx/${receipt.transactionHash}`);
// console.log('NFT Item:', nftItem);
// } catch (error) {
// console.error('Error minting NFT:', error);
// }
// } else {
// console.error('MetaMask is not installed. Please consider installing it: https://metamask.io/download.html');
// }
// }