dracoder-web3-package 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +95 -40
  2. package/package.json +3 -2
package/index.js CHANGED
@@ -1,8 +1,29 @@
1
1
  "use strict";
2
2
 
3
3
  const { Web3 } = require("web3");
4
+ const { isAddress } = require("web3-validator");
4
5
  const { abiToken } = require("./helpers/factory_data");
5
6
 
7
+ // Variable para guardar
8
+ // la configuración de red
9
+ let networkConfig = null;
10
+
11
+ // Configuración por defecto
12
+ const defaultNetworkConfig = {
13
+ chainId: "0x89",
14
+ chainName: "Polygon Mainnet",
15
+ nativeCurrency: {
16
+ name: "POL",
17
+ symbol: "POL",
18
+ decimals: 18,
19
+ },
20
+ rpcUrls: ["https://polygon-rpc.com/"],
21
+ blockExplorerUrls: ["https://polygonscan.com/"],
22
+ iconUrls: [
23
+ "https://polygonscan.com/assets/poly/images/svg/logos/chain-light.svg",
24
+ ],
25
+ };
26
+
6
27
  const METAMASK_NOT_INSTALLED_MESSAGE = {
7
28
  ok: false,
8
29
  message: "You don't have Metamask installed.",
@@ -59,15 +80,15 @@ const clientTokenTransfer = async ({
59
80
  throw error;
60
81
  }
61
82
 
62
- if (!web3.utils.isAddress(account)) {
83
+ if (!isAddress(account)) {
63
84
  throw new Error("Not valid account");
64
85
  }
65
86
 
66
- if (!web3.utils.isAddress(tokenAddress)) {
87
+ if (!isAddress(tokenAddress)) {
67
88
  throw new Error("Is not a Token Address");
68
89
  }
69
90
 
70
- if (!web3.utils.isAddress(walletAddressToTransferTo)) {
91
+ if (!isAddress(walletAddressToTransferTo)) {
71
92
  throw new Error("Is not a Wallet Address to transfer to");
72
93
  }
73
94
 
@@ -149,21 +170,7 @@ const isMetamaskInstalled = () => {
149
170
  };
150
171
 
151
172
  const checkWalletFormat = (account) => {
152
- let web3;
153
- if (!checkIfMetamaskIsAvailable()) {
154
- return METAMASK_NOT_INSTALLED_MESSAGE;
155
- }
156
- try {
157
- web3 = new Web3(Metamask);
158
- } catch (error) {
159
- return {
160
- ok: false,
161
- message: "Web3 can not be loaded. Metamask must be installed",
162
- error: error,
163
- };
164
- }
165
-
166
- if (!web3.utils.isAddress(account)) {
173
+ if (!isAddress(account)) {
167
174
  return {
168
175
  ok: false,
169
176
  message: "Wrong address format",
@@ -180,18 +187,25 @@ const selectOrAddPolygonMainNetwork = async () => {
180
187
  if (!checkIfMetamaskIsAvailable()) {
181
188
  return METAMASK_NOT_INSTALLED_MESSAGE;
182
189
  }
190
+
183
191
  await getMetamaskAccount().catch((error) => {
184
192
  throw error;
185
193
  });
194
+
195
+ const pickedNetworkConfig = getNetworkConfig();
196
+ const addedSuccessMsg = `${pickedNetworkConfig.chainName} added successfully`;
197
+ const switchedSuccessMsg = `${pickedNetworkConfig.chainName} established successfully`;
198
+
186
199
  try {
187
200
  // Primero intentar cambiar a la red de Polygon si ya existe
188
201
  await Metamask.request({
189
202
  method: "wallet_switchEthereumChain",
190
- params: [{ chainId: "0x89" }], // ChainId de Polygon Mainnet en hexadecimal
203
+ params: [{ chainId: pickedNetworkConfig.chainId }],
191
204
  });
205
+
192
206
  return {
193
207
  ok: true,
194
- message: "Already on polygon main network",
208
+ message: switchedSuccessMsg,
195
209
  };
196
210
  } catch (switchError) {
197
211
  // Si el error es 4902, significa que la red no está añadida
@@ -199,33 +213,31 @@ const selectOrAddPolygonMainNetwork = async () => {
199
213
  try {
200
214
  const response = await Metamask.request({
201
215
  method: "wallet_addEthereumChain",
202
- params: [
203
- {
204
- chainId: "0x89",
205
- chainName: "Polygon",
206
- nativeCurrency: {
207
- name: "POL",
208
- symbol: "POL",
209
- decimals: 18,
210
- },
211
- rpcUrls: ["https://polygon.llamarpc.com"],
212
- blockExplorerUrls: ["https://polygonscan.com/"],
213
- iconUrls: [
214
- "https://polygonscan.com/assets/poly/images/svg/logos/chain-light.svg",
215
- ],
216
- },
217
- ],
216
+ params: [pickedNetworkConfig],
218
217
  });
219
218
  return {
220
219
  ok: true,
221
- message: "Polygon MainNet added successfully",
220
+ message: addedSuccessMsg,
222
221
  response: response,
223
222
  };
224
223
  } catch (error) {
224
+ const errorCode = error.code;
225
+
226
+ if (errorCode === -32603) {
227
+ // El código -32603 es un bug de Metamask
228
+ // https://github.com/MetaMask/metamask-extension/issues/33213
229
+ // https://github.com/MetaMask/metamask-extension/issues/32165
230
+ // La red realmente se ha añadido correctamente
231
+ return {
232
+ ok: true,
233
+ message: addedSuccessMsg,
234
+ };
235
+ }
236
+
225
237
  return {
226
238
  ok: false,
227
239
  message: error.message,
228
- code: error.code,
240
+ code: errorCode,
229
241
  };
230
242
  }
231
243
  } else {
@@ -234,10 +246,53 @@ const selectOrAddPolygonMainNetwork = async () => {
234
246
  }
235
247
  };
236
248
 
249
+ // Función para obtener la configuración actual
250
+ const getNetworkConfig = () => {
251
+ return networkConfig || defaultNetworkConfig;
252
+ };
253
+
254
+ // Función para configurar la red desde el proyecto
255
+ const setNetworkConfig = (config) => {
256
+ if (!config || typeof config !== "object") {
257
+ console.warn(
258
+ "Configuración de red inválida, usando configuración por defecto"
259
+ );
260
+
261
+ networkConfig = { ...defaultNetworkConfig };
262
+
263
+ return false;
264
+ }
265
+
266
+ // Validar que tenga los campos requeridos
267
+ const requiredFields = ["chainId", "chainName", "rpcUrls"];
268
+ const missingFields = requiredFields.filter((field) => !config[field]);
269
+
270
+ if (missingFields.length > 0) {
271
+ console.warn(
272
+ `Faltan campos requeridos en la configuración: ${missingFields.join(
273
+ ", "
274
+ )}`
275
+ );
276
+
277
+ networkConfig = { ...defaultNetworkConfig };
278
+
279
+ return false;
280
+ }
281
+
282
+ // Fusionar con configuración por defecto para campos opcionales
283
+ networkConfig = {
284
+ ...defaultNetworkConfig,
285
+ ...config,
286
+ };
287
+
288
+ return true;
289
+ };
290
+
237
291
  module.exports = {
238
- clientTokenTransfer,
292
+ setNetworkConfig,
293
+ checkWalletFormat,
239
294
  sendTokenToWallet,
295
+ clientTokenTransfer,
240
296
  isMetamaskInstalled,
241
- checkWalletFormat,
242
297
  selectOrAddPolygonMainNetwork,
243
298
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dracoder-web3-package",
3
- "version": "2.0.2",
3
+ "version": "2.0.4",
4
4
  "description": "Dracoder package used for web3 provider integration.",
5
5
  "main": "index.js",
6
6
  "keywords": [
@@ -16,7 +16,8 @@
16
16
  "author": "Dracoder S.L.",
17
17
  "license": "MIT",
18
18
  "dependencies": {
19
- "web3": "^4.4.0"
19
+ "web3": "^4.4.0",
20
+ "web3-validator": "^2.0.6"
20
21
  },
21
22
  "devDependencies": {
22
23
  "@babel/core": "^7.15.0",