-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethers.js
406 lines (331 loc) · 11 KB
/
ethers.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import { ethers } from "https://cdn.jsdelivr.net/npm/ethers@5/dist/ethers.esm.js";
import web3State, { chains } from "./services/web3State.js";
import { smartContractABI } from "./data/abi.js";
import { uint16 } from "./utils/utils";
import { adminService } from "./services/adminService";
export const CHAIN_CODES = {
ETH: "0x1",
MATIC: "0x89",
POLYGON: "0x89",
GO: "0x3C",
};
const METAMASK_STATUS = {
REJECTED: 4001,
};
export const checkMetamaskForInstallation = () => {
if (!window.ethereum) {
throw new Error("WEB3_WALLET_IS_NOT_INSTALLED");
}
return true;
};
export async function switchChain(chainId) {
try {
const isHex = ethers.utils.isHexString(chainId);
if (!isHex) chainId = CHAIN_CODES[chainId];
console.log("ethers: switchChain: ", chainId);
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId }],
});
} catch (switchError) {
console.error("Switch chain error", switchError);
console.log(chains);
console.log(chains[chainId]);
try {
await ethereum.request({
method: "wallet_addEthereumChain",
params: [chains[chainId]],
});
} catch (addError) {
console.error("Error adding chain to MetaMask", addError);
}
}
}
export const getSmartContractInstance = (contractAddress, signer) => {
if (!contractAddress) return null;
const contract = new ethers.Contract(
contractAddress,
smartContractABI,
signer
);
return contract;
};
/**
* nuqtahAdminAddress - NUQTAH operator address
* @returns if the operator(Nuqtah) is allowed to manage all of the assets of owner.
*/
export const isNuqtahApprovedForAll = async (
contractAddress,
network,
nuqtahAdminAddress
) => {
checkMetamaskForInstallation();
await switchChain(network);
const { signer, from } = await getSignerAndAddress();
const contract = getSmartContractInstance(contractAddress, signer);
const isApproved = await contract.isApprovedForAll(from, nuqtahAdminAddress);
return isApproved;
};
/**
* nuqtahAdminAddress - NUQTAH operator address
* @returns if the operator(Nuqtah) is allowed to manage all of the assets of owner.
*/
export const isApprovedForAll = async (
contractAddress,
ownerAddress,
operatorAddress
) => {
checkMetamaskForInstallation();
if (!ownerAddress || !contractAddress || !operatorAddress)
return "Missing required fields: ownerAddress(collection owner address) or contractAddress. Please recreate a collection with your metamask or set value manually for collection.ownerAddress!";
const { signer } = await getSignerAndAddress();
const contract = getSmartContractInstance(contractAddress, signer);
console.log("Contract: ", contract);
const isApproved = await contract.isApprovedForAll(
ownerAddress,
operatorAddress
);
console.log("isApproved: ", isApproved);
return isApproved;
};
export const setNuqtahAsApprover = async (
operatorAddress,
contractAddress,
approved,
network
) => {
checkMetamaskForInstallation();
await switchChain(network);
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
// Signer
const signer = provider.getSigner();
let from = await signer.getAddress();
const contract = getSmartContractInstance(contractAddress, signer);
const gasPrice = await signer.getGasPrice();
const tx = await contract.setApprovalForAll(operatorAddress, approved, {
from,
gasPrice,
});
const receipt = await tx.wait();
console.log("result: ", tx, receipt);
return tx;
};
const getSignerAndAddress = async () => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
// Signer
const signer = provider.getSigner();
let from = await signer.getAddress();
return { signer, from, provider };
};
export const burn = async (network, contractAddress, tokenID) => {
checkMetamaskForInstallation();
await switchChain(network);
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
// Signer
const signer = provider.getSigner();
let from = await signer.getAddress();
console.log("Your metamask wallet: ", from);
const gasPrice = await signer.getGasPrice();
console.log("Ethers: Signer gas price: ", gasPrice);
// Getting contract
const contract = getSmartContractInstance(contractAddress, signer);
console.log("ethers: contract: ", contract);
const tx = await contract.burn(tokenID, {
from,
gasPrice,
gasLimit: 400000,
});
const receipt = await tx.wait();
console.log("result: ", tx, receipt);
};
// Used for transfering NFT to another account
export const web3MintWithMetamask = async (nft, toAddress, contractAddress) => {
console.log("web3MintWithMetamask: ", { nft, toAddress, contractAddress });
await switchChain(nft.network);
const { signer } = await getSignerAndAddress();
const contract = getSmartContractInstance(contractAddress, signer);
const gasPrice = await signer.getGasPrice();
const tokenId = nft?.tokenID || uint16(new Date().getTime());
console.log("TokenID", tokenId);
const tx = await contract.safeMint(toAddress, tokenId, {
from: toAddress,
gasPrice,
gasLimit: 400000,
});
const receipt = await tx.wait();
return { details: tx, receipt, tokenId };
};
export const signMessage = async (message, network) => {
if (network) {
await switchChain(network);
}
const { signer } = await getSignerAndAddress();
// const contract = getSmartContractInstance(contractAddress, signer)
// const signture = await web3.eth.personal.sign(message, address)
let messageHash = ethers.utils.id(message);
let messageHashBytes = ethers.utils.arrayify(messageHash);
const flatSig = await signer.signMessage(messageHashBytes);
let signture = ethers.utils.splitSignature(flatSig);
console.log("signMessage: ", { message, signture });
return {
message,
signture,
};
};
export const sendTransaction = async (toAddress, amountInEther, network) => {
console.log("sendTransaction: ", {
toAddress,
amountInEther,
network,
});
checkMetamaskForInstallation();
await switchChain(network);
const { signer, from, provider } = await getSignerAndAddress();
const gasPrice = await signer.getGasPrice();
console.log("gasPrice: ", gasPrice);
const txnOptions = {
from,
to: toAddress,
value: ethers.utils.parseEther(String(amountInEther), "ether"),
gasPrice,
};
console.log("Options: ", txnOptions);
console.log("RPC");
const tx = await signer.sendTransaction(txnOptions);
console.log("Transaction hash: ", tx);
const receipt = await tx.wait();
console.log("receipt: ", receipt);
return { details: tx, receipt };
};
export const web3TransferNFT = async (nft, toAddress, contractAddress) => {
console.log("web3TransferNFT: ", { nft, toAddress, contractAddress });
await switchChain(nft.network);
const { signer, from } = await getSignerAndAddress();
const contract = getSmartContractInstance(contractAddress, signer);
const tx = await contract["safeTransferFrom(address,address,uint256)"](
nft.ownerAddress,
toAddress,
nft.tokenID
);
console.log("ethers transfer tx: ", tx);
const receipt = await tx.wait();
return { details: tx, receipt };
};
export const deployToken = async (
name,
symbol,
baseURI,
postActionOnFailure,
network
) => {
try {
checkMetamaskForInstallation();
await switchChain(network);
let response = await fetch(
"https://raw.githubusercontent.com/nuqtah/contracts/main/contracts/ERC721v1.bin"
);
let content = await response.text();
const adminAddressR = await adminService.fetchAdminAddress();
const extraMinter = adminAddressR.address;
const { signer, from } = await getSignerAndAddress();
const abi = ethers.utils.defaultAbiCoder;
let encodedParameters = abi
.encode(
["string", "string", "string", "address"],
[name, symbol, baseURI, extraMinter]
)
.slice(2);
console.log("encodedParameters: ", encodedParameters);
const newContract = new ethers.ContractFactory(
smartContractABI,
content,
signer
);
console.log("new contract instance: ", newContract);
const contract = await newContract.deploy(
name,
symbol,
baseURI,
extraMinter
);
const txReceipt = await contract.deployTransaction.wait();
console.log("txReceipt: ", txReceipt);
const explorerUrl = chains[CHAIN_CODES[network]].blockExplorerUrls[0];
const transactionHashOnBlockExplorerURL = `${explorerUrl}/tx/${txReceipt.transactionHash}`;
return {
txHash: txReceipt.transactionHash,
contractAddress: txReceipt.contractAddress,
blockExplorerURL: transactionHashOnBlockExplorerURL,
ownerAddress: txReceipt.from,
};
} catch (error) {
/**
* 4001 - rejected status
*/
if (error.code === METAMASK_STATUS.REJECTED) {
typeof postActionOnFailure === "function" && postActionOnFailure();
throw new Error(error?.message);
}
console.log("Error while deploying contract: ", error);
throw new Error("COLLECTION_IS_NOT_CREATED");
}
};
export const connectWallet = async (params) => {
//receive params
const noMetamaskCallback = params?.noMetamaskCallback;
if (typeof window.ethereum !== "undefined") {
const { from } = await getSignerAndAddress();
if (from) {
web3State.setAccount(from);
}
} else {
if (noMetamaskCallback) {
noMetamaskCallback();
} else {
alert(
"No web3 wallet was detected. Please, install MetaMask from https://metamask.io, App Stores, or refresh the page."
);
}
}
};
export const getBalance = async (_address, _network) => {
_network = normalizeNetwork(_network);
const rpcUrl = chains[_network]?.rpcUrls
? chains[_network]?.rpcUrls[0]
: "https://mainnet.infura.io/v3/96136349e5e4402eb5cc039210bc6d5e";
const provider = new ethers.getDefaultProvider(rpcUrl);
const balanceInWei = await provider.getBalance(_address);
const balance = ethers.utils.formatEther(balanceInWei);
return parseFloat(balance).toFixed(3);
};
const normalizeNetwork = (_network) => {
const isHex = ethers.utils.isHexString(_network);
if (!isHex) _network = CHAIN_CODES[String(_network).toUpperCase()];
return _network;
};
const handleChainChanged = (network) => {
console.log("ethers: network: ", network);
web3State.setChain(network);
};
const handleAccountChanged = (accounts) => {
console.log("ethers: accounts: ", accounts[0]);
const account = accounts[0];
web3State.setAccount(account);
};
const bootstrap = () => {
if (window.ethereum) {
ethereum.on("accountsChanged", handleAccountChanged);
ethereum.on("chainChanged", handleChainChanged);
window.ethereum
.request({ method: "eth_accounts" })
.then(handleAccountChanged)
.catch((err) => {
console.error(err);
});
window.ethereum.request({ method: "eth_accounts" });
}
};
bootstrap();