dracoder-web3-package 2.0.1 → 2.0.2

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 (3) hide show
  1. package/README.md +75 -375
  2. package/index.js +64 -63
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,431 +1,131 @@
1
- # Rocketchain-package.
1
+ # web3-integration-package
2
2
 
3
- ## Summary
3
+ ## Resumen
4
4
 
5
- _Package used for web3 provider integration between client side and API._
5
+ _Paquete utilizado para la integración del proveedor web3 entre el lado del cliente y la API._
6
6
 
7
- A repository to integrate required interaction between platform user (on client app) and blockchain actions signatures.
8
- Then the info generated and logs are sent to the related API endpoints.
7
+ Este repositorio proporciona las herramientas necesarias para conectar a los usuarios con el ecosistema blockchain de manera fluida y segura. Facilita la integración de funcionalidades de firma de transacciones blockchain en aplicaciones cliente, permitiendo que la información y los registros generados se comuniquen eficientemente con los endpoints de la API necesarios.
9
8
 
10
- ## Index
9
+ ## Índice
11
10
 
12
- * Installation
13
- * Specification
11
+ - Instalación
12
+ - Funciones
14
13
 
15
- ## Installation
14
+ ## Instalación
16
15
 
17
- ```
18
- npm install rocketchain-package
19
- ```
20
-
21
- #### Dependencies used:
22
-
23
- Axios, web3
24
-
25
- ## Specification
26
-
27
- ### Function: setClientServerUrl
28
-
29
- Sets the client server url received. setClientServerUrl(param1)
30
-
31
- #### Parameters:
32
-
33
- param1: client server url address
34
-
35
- #### Example:
36
-
37
- ```
38
- setClientServerUrl("http://localhost:5000")
39
- ```
40
-
41
- #### Return:
42
-
43
- No return.
44
-
45
- ### Function: metamaskConnect
46
-
47
- Checks if client app user is logged in with Metamask (to be able to receive transaction signature requests) and returns
48
- a promise with the user wallet address. If not, Metamask prompts asking to log in.
49
-
50
- #### Parameters:
51
-
52
- No parameters
53
-
54
- #### Example:
55
-
56
- ```
57
- const someFunctionThatNeedsTheUserWalletAddress = async() => {
58
- const walletAddress = await metamaskConnect()
59
- ...
60
- }
61
- ```
62
-
63
- #### Return:
64
-
65
- Returns a promise.
66
-
67
- Success:
68
-
69
- ```
70
- console.log(walletAddress)
71
- 0xECf8C3205B230a39a71354214561dAA83433Ae3B
72
- ```
73
-
74
- Failure - string with error description if fails (depending on where the problem was)
75
-
76
- ```
77
- console.log(connect)
78
- "There is no account to connect to"
79
- ```
80
-
81
- ```
82
- console.log(connect)
83
- "There was a problem connecting to your Metamask wallet. Do you have Metamask installed?"
84
- ```
85
-
86
- ### Function: clientTokenTransfer
87
-
88
- Transfer -that must be signed- of some amount of token from the user to another receiver
89
-
90
- clientTokenTransfer(param1, param2, param3)
91
-
92
- #### Parameters:
93
-
94
- * param1: address receiver of the tokens
95
- * param2: address of the token contract that will be transferred
96
- * param3: amount of token to be transferred
97
-
98
- #### Example:
99
-
100
- ```
101
- tokenTransfer(0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170, 0xa6c99e129cecf74865f6ed847a62c63cd6e0c045, 17)
102
- ```
103
-
104
- #### Return:
16
+ `npm install dracoder-web3-package`
105
17
 
106
- Returns a promise:
18
+ # Funciones
107
19
 
108
- Success: transaction object from Blockchain
20
+ # `isMetamaskInstalled`
109
21
 
110
- ```
111
- {
112
- "blockHash": "0x59ae5fc6af98787806d2733e97bc749e057ef0bf6d1c85d2f42f3eed92b9cba1",
113
- "blockNumber": 9245548,
114
- "contractAddress": null,
115
- "cumulativeGasUsed": 8907523,
116
- "effectiveGasPrice": "0x3b9aca0e",
117
- "from": "0x212f260404a05e954bc9285bfae89d6b2bb45134",
118
- "gasUsed": 34494,
119
- "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000008000000000000010000008000000000000000000000000000000000040000000000000000000000000000000000000010000000000000000000000100000000004000000000004000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000",
120
- "status": true,
121
- "to": "0xa6c99e129cecf74865f6ed847a62c63cd6e0c045",
122
- "transactionHash": "0xe8992e16afc720381390cb54f1bb3a6a0e3a30fc143797dced38417b2a02f99e",
123
- "transactionIndex": 37,
124
- "type": "0x2",
125
- "events": {
126
- "Transfer": {
127
- "address": "0xa6C99E129cecF74865F6eD847a62c63cD6E0C045",
128
- "blockHash": "0x59ae5fc6af98787806d2733e97bc749e057ef0bf6d1c85d2f42f3eed92b9cba1",
129
- "blockNumber": 9245548,
130
- "logIndex": 92,
131
- "removed": false,
132
- "transactionHash": "0xe8992e16afc720381390cb54f1bb3a6a0e3a30fc143797dced38417b2a02f99e",
133
- "transactionIndex": 37,
134
- "id": "log_696ad3a5",
135
- "returnValues": {
136
- "0": "0x212f260404A05E954BC9285BFAe89D6B2bB45134",
137
- "1": "0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170",
138
- "2": "17",
139
- "from": "0x212f260404A05E954BC9285BFAe89D6B2bB45134",
140
- "to": "0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170",
141
- "value": "17"
142
- },
143
- "event": "Transfer",
144
- "signature": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
145
- "raw": {
146
- "data": "0x0000000000000000000000000000000000000000000000000000000000000011",
147
- "topics": [
148
- "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
149
- "0x000000000000000000000000212f260404a05e954bc9285bfae89d6b2bb45134",
150
- "0x000000000000000000000000e4513a7bcd98de50fe7984c82daf5611beba7170"
151
- ]
152
- }
153
- }
154
- }
155
- }
156
- ```
157
-
158
- Error: The log depends on where the error was produced
159
-
160
- ### Function: tokenCreate
161
-
162
- Creates a token using given token parameters and the user wallet address to relate the request
163
-
164
- tokenCreate(param1, param2, param3, param4, param5)
22
+ Verifica si Metamask está instalado en el navegador del usuario.
165
23
 
166
- #### Parameters:
24
+ ### Uso
167
25
 
168
- * param1: Name given to the token by the user
169
- * param2: total amount of tokens that will be created
170
- * param3: Symbol of the token given by the user
171
- * param4: Decimals of the token
172
- * param5: wallet address of the user that requested the token creation
173
-
174
- #### Example:
175
-
176
- ```
177
- const RocketchainPackage = require('rocketchain-package');
178
- const someFunction = async () => {
179
- const createdToken = await RocketchainPackage.tokenCreate(
180
- "Token Doc",
181
- "44",
182
- "TkD",
183
- "0",
184
- "0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170",
185
- );
186
- }
26
+ ```javascript
27
+ const { isMetamaskInstalled } = require("dracoder-web3-package");
28
+ console.log(isMetamaskInstalled());
187
29
  ```
188
30
 
189
- #### Return:
31
+ ### Retorno
190
32
 
191
- Returns a promise.
192
-
193
- Database object with all the creation Blockchain data related
194
-
195
- ```
196
- console.log(createdToken);
197
- {
198
- "data": {
199
- "is_transferred": false,
200
- "_id": "613628fcf7a6782270588ee1",
201
- "token_address": "0x85398185A1CBE64D7f8Bf4aD668AB7352A93F589",
202
- "wallet_address": "0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170",
203
- "amount": "44",
204
- "log_id": "613628fcf7a6782270588edf",
205
- "created_at": "2021-09-06T12:42:55.000Z",
206
- "__v": 0
207
- },
208
- "status": 200,
209
- "statusText": "OK",
210
- "headers": {
211
- "cache-control": "no-cache, private",
212
- "content-length": "278",
213
- "content-type": "text/html; charset=UTF-8"
214
- },
215
- "config": {
216
- "url": "http://rocketchain-server.test/api/token_creation_response",
217
- "method": "post",
218
- "data": "{\"nameOfToken\":\"Token Doc\",\"numberOfToken\":\"44\",\"symbolOfToken\":\"TkD\",\"numberOfDecimals\":\"0\",\"userWalletAddress\":\"0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170\"}",
219
- "headers": {
220
- "Accept": "application/json, text/plain, */*",
221
- "Content-Type": "application/json"
222
- },
223
- "transformRequest": [
224
- null
225
- ],
226
- "transformResponse": [
227
- null
228
- ],
229
- "timeout": 0,
230
- "xsrfCookieName": "XSRF-TOKEN",
231
- "xsrfHeaderName": "X-XSRF-TOKEN",
232
- "maxContentLength": -1,
233
- "maxBodyLength": -1,
234
- "transitional": {
235
- "silentJSONParsing": true,
236
- "forcedJSONParsing": true,
237
- "clarifyTimeoutError": false
238
- }
239
- },
240
- "request": {}
241
- }
242
- ```
243
-
244
- ### Function: tokenTransferWithTokenAddressOnly
245
-
246
- Transfer linked with the token creation (as a second step) process
247
-
248
- tokenTransferWithTokenAddressOnly(param1)
249
-
250
- #### Parameters:
251
-
252
- param1: token smart contract address.
253
-
254
- (Retrieved from tokenCreate method response => data.token_address)
255
-
256
- #### Example:
257
-
258
- ```
259
- const RocketchainPackage = require('rocketchain-package');
260
- const someFunction = async data => {
261
- const tokenTransferred = await RocketchainPackage.tokenTransferWithTokenAddressOnly("0x85398185A1CBE64D7f8Bf4aD668AB7352A93F589");
262
- };
263
- ```
33
+ - `{ "ok": true, "message": "Metamask is installed" }` si Metamask está instalado.
34
+ - `{ "ok": false, "message": "You don't have Metamask installed." }` si Metamask no está instalado.
264
35
 
265
- #### Return:
36
+ # `getMetamaskAccount`
266
37
 
267
- Returns a promise.
38
+ Obtiene la cuenta de Metamask conectada actualmente.
268
39
 
269
- Database object with all the Blockchain transfer data related
40
+ ### Uso
270
41
 
42
+ ```javascript
43
+ const { getMetamaskAccount } = require("dracoder-web3-package");
44
+ getMetamaskAccount().then(console.log).catch(console.error);
271
45
  ```
272
- console.log(tokenTransferred);
273
- {
274
- "blockHash": "0xd5da8d878e62ec7868e80d0df0676fe9f52a21af4a1277c40ab2cb1b7d092b95",
275
- "blockNumber": 9245705,
276
- "contractAddress": null,
277
- "cumulativeGasUsed": 3396087,
278
- "effectiveGasPrice": "0x3b9aca0d",
279
- "from": "0x212f260404a05e954bc9285bfae89d6b2bb45134",
280
- "gasUsed": 46794,
281
- "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000010004008000000000000000000000000000000000040000000000000000000000000000000000000010000000000000000000000100000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000002000000000000000000000000000000000000010000002000000000000000000000000000000000000000000000000000000000000000000000000000",
282
- "status": true,
283
- "to": "0x85398185a1cbe64d7f8bf4ad668ab7352a93f589",
284
- "transactionHash": "0x6cea70d5436e706a659ff339fc7b012576eafc6b28bcf9c93355fd19ad2a800b",
285
- "transactionIndex": 24,
286
- "type": "0x0",
287
- "events": {
288
- "Transfer": {
289
- "address": "0x85398185A1CBE64D7f8Bf4aD668AB7352A93F589",
290
- "blockHash": "0xd5da8d878e62ec7868e80d0df0676fe9f52a21af4a1277c40ab2cb1b7d092b95",
291
- "blockNumber": 9245705,
292
- "logIndex": 30,
293
- "removed": false,
294
- "transactionHash": "0x6cea70d5436e706a659ff339fc7b012576eafc6b28bcf9c93355fd19ad2a800b",
295
- "transactionIndex": 24,
296
- "id": "log_0dd77e89",
297
- "returnValues": {
298
- "0": "0x212f260404A05E954BC9285BFAe89D6B2bB45134",
299
- "1": "0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170",
300
- "2": "44",
301
- "from": "0x212f260404A05E954BC9285BFAe89D6B2bB45134",
302
- "to": "0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170",
303
- "value": "44"
304
- },
305
- "event": "Transfer",
306
- "signature": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
307
- "raw": {
308
- "data": "0x000000000000000000000000000000000000000000000000000000000000002c",
309
- "topics": [
310
- "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
311
- "0x000000000000000000000000212f260404a05e954bc9285bfae89d6b2bb45134",
312
- "0x000000000000000000000000e4513a7bcd98de50fe7984c82daf5611beba7170"
313
- ]
314
- }
315
- }
316
- }
317
- }
318
- ```
319
-
320
- ### Function: getTokenOwnersBalance
321
-
322
- Retrieves all the accounts that have owned (0 balance now) or currently own (positive balance) the token specified by
323
- the token contract address.
324
46
 
325
- getTokenOwnersBalance(param1)
47
+ ### Retorno
326
48
 
327
- #### Parameters:
49
+ - `{ "ok": true, "message": "Connected successfully.", "account": "0x..." }` si se obtiene la cuenta con éxito.
50
+ - `{ "ok": false, "message": "Error message }` en caso de error.
328
51
 
329
- param1: smart contract token address.
52
+ # `clientTokenTransfer`
330
53
 
331
- #### Example:
332
-
333
- ```
334
- const RocketchainPackage = require('rocketchain-package');
335
- const someFunction = async () => {
336
- const ownersArray = await RocketchainPackage.getTokenOwnersBalance(0xa6c99e129cecf74865f6ed847a62c63cd6e0c045);
337
- };
338
- ```
54
+ Realiza una transferencia de tokens desde la cuenta conectada a una dirección específica.
339
55
 
340
- #### Return:
56
+ ### Parametros
341
57
 
342
- Returns a promise.
58
+ - `walletAddressToTransferTo` : Dirección de la billetera receptora.
59
+ - `tokenAddress` : Dirección del contrato del token.
60
+ - `amount` : Cantidad de tokens a transferir.
343
61
 
344
- Array of objects. Each object represents a pair of owner-balance values.
62
+ ### Uso
345
63
 
64
+ ```javascript
65
+ const { clientTokenTransfer } = require("dracoder-web3-package");
66
+ clientTokenTransfer(walletAddressToTransferTo, tokenAddress, amount)
67
+ .then(console.log)
68
+ .catch(console.error);
346
69
  ```
347
- console.log(ownersArray);
348
- [{"owner":"0xe4513a7BCd98dE50Fe7984C82dAf5611beBa7170","balance":"41"},{"owner":"0x212f260404A05E954BC9285BFAe89D6B2bB45134","balance":"5959"}]
349
- ```
350
-
351
- ### Function: isMetamaskInstalled
352
-
353
- Checks if Metamask is installed in order to proceed with the rest of functionalities
354
70
 
355
- isMetamaskInstalled()
71
+ ### Retorno
356
72
 
357
- #### Parameters:
73
+ - `{ "ok": true, "message": "Transfer successful", "transactionHash": "0x..." }` si la transferencia es exitosa.
74
+ - `{ "ok": false, "message": "Transfer failed", "error": error }` si falla la transferencia.
358
75
 
359
- No parameters required.
76
+ # `sendTokenToWallet`
360
77
 
361
- #### Example:
78
+ Intenta añadir un token a Metamask.
362
79
 
363
- ```
364
- const RocketchainPackage = require('rocketchain-package');
365
- const someFunction = async () => {
366
- const checkMetamask = await RocketchainPackage.isMetamaskInstalled();
367
- };
368
- ```
80
+ ### Parametros
369
81
 
370
- #### Return:
82
+ - `tokenAddress` : Dirección del contrato del token.
371
83
 
372
- Returns a response depending on Metamask is/is not installed.
84
+ ### Uso
373
85
 
374
- ```
375
- { ok: false, message: "You don't have Metamask installed." }
86
+ ```javascript
87
+ const { sendTokenToWallet } = require("dracoder-web3-package");
88
+ sendTokenToWallet(tokenAddress).then(console.log).catch(console.error);
376
89
  ```
377
90
 
378
- ### Function: checkWalletFormat
91
+ ### Retorno
379
92
 
380
- Checks if the wallet provided has the proper structure and format.
93
+ - `{ true }` si el token se añadió correctamente.
94
+ - `{ [Objeto] de error }` si falla la operación.
381
95
 
382
- checkWalletFormat(param1)
96
+ # `checkWalletFormat`
383
97
 
384
- #### Parameters:
98
+ Verifica si una dirección de billetera tiene el formato correcto.
385
99
 
386
- param1: wallet address.
100
+ ### Parametros
387
101
 
388
- #### Example:
102
+ - `account` : Dirección de la billetera a verificar.
389
103
 
390
- ```
391
- const RocketchainPackage = require('rocketchain-package');
392
- const someFunction = async () => {
393
- const formatVerification = await RocketchainPackage.checkWalletFormat(0xLZf8C3205B230a39a71354214561dAA83433Ae4K);
394
- };
395
- ```
396
-
397
- #### Return
104
+ ### Uso
398
105
 
399
- Returns a response depending on whether the data provided has the right format or not.
400
-
401
- ```
402
- { ok: true, message: "Proper address format" }
106
+ ```javascript
107
+ const { checkWalletFormat } = require("dracoder-web3-package");
108
+ console.log(checkWalletFormat(account));
403
109
  ```
404
110
 
405
- ### Function: selectOrAddPolygonMainNetwork
406
-
407
- Selects or adds the Polygon Matic Mainnet to the Metamask wallet.
111
+ ### Retorno
408
112
 
409
- selectOrAddPolygonMainNetwork()
113
+ - `{ "ok": true, "message": "Proper address format" }` si el formato es correcto.
114
+ - `{ "ok": false, "message": "Wrong address format" }` si el formato es incorrecto.
410
115
 
411
- ### Parameters:
116
+ # `selectOrAddPolygonMainNetwork`
412
117
 
413
- No parameters required.
118
+ Selecciona o añade la red principal de Polygon en Metamask.
414
119
 
415
- ### Example:
120
+ ### Uso
416
121
 
122
+ ```javascript
123
+ const { selectOrAddPolygonMainNetwork } = require("dracoder-web3-package");
124
+ selectOrAddPolygonMainNetwork().then(console.log).catch(console.error);
417
125
  ```
418
- const RocketchainPackage = require('rocketchain-package');
419
- const someFunction = async () => {
420
- const selectOrAddPolygonMainNetwork = await RocketchainPackage.selectOrAddPolygonMainNetwork();
421
- };
422
- ```
423
-
424
- ### Return
425
-
426
- Returns a response depending on whether the Polygon main network was previously added or needs to be added.
427
126
 
428
- ```
429
- { ok: true, message: "Matic Mainnet added successfully", response: ... }
430
- ```
127
+ ### Retorno
431
128
 
129
+ - `{ "ok": true, "message": "Already on polygon main network" }` si ya está en la red principal de Polygon.
130
+ - `{ "ok": true, "message": "Matic MainNet added successfully", "response": response }` si se añade la red de Polygon con éxito.
131
+ - `{ "ok": false, "message": "Matic MainNet cannot be added", "response": error }` si no se puede añadir la red.
package/index.js CHANGED
@@ -1,29 +1,29 @@
1
1
  "use strict";
2
2
 
3
- const {Web3} = require("web3");
4
- const {abiToken} = require("./helpers/factory_data");
3
+ const { Web3 } = require("web3");
4
+ const { abiToken } = require("./helpers/factory_data");
5
5
 
6
6
  const METAMASK_NOT_INSTALLED_MESSAGE = {
7
7
  ok: false,
8
8
  message: "You don't have Metamask installed.",
9
- }
9
+ };
10
10
 
11
- const Metamask = window.ethereum
11
+ const Metamask = window.ethereum;
12
12
 
13
13
  const checkIfMetamaskIsAvailable = () => {
14
- return typeof Metamask !== "undefined"
15
- }
14
+ return typeof Metamask !== "undefined";
15
+ };
16
16
 
17
17
  const getMetamaskAccount = async () => {
18
- const [account] = await Metamask
19
- .request({method: "eth_requestAccounts"})
20
- .catch(async (error) => {
21
- throw {
22
- ok: false,
23
- message: "Something went wrong connecting to Metamask.",
24
- metamaskMessage: error,
25
- };
26
- });
18
+ const [account] = await Metamask.request({
19
+ method: "eth_requestAccounts",
20
+ }).catch(async (error) => {
21
+ throw {
22
+ ok: false,
23
+ message: "Something went wrong connecting to Metamask.",
24
+ metamaskMessage: error?.message,
25
+ };
26
+ });
27
27
  if (!account) {
28
28
  throw {
29
29
  ok: false,
@@ -38,16 +38,18 @@ const getMetamaskAccount = async () => {
38
38
  };
39
39
 
40
40
  const clientTokenTransfer = async ({
41
- walletAddressToTransferTo,
42
- tokenAddress,
43
- amount,
44
- }) => {
41
+ walletAddressToTransferTo,
42
+ tokenAddress,
43
+ amount,
44
+ }) => {
45
45
  if (!checkIfMetamaskIsAvailable()) {
46
- return METAMASK_NOT_INSTALLED_MESSAGE
46
+ return METAMASK_NOT_INSTALLED_MESSAGE;
47
47
  }
48
+
48
49
  const response = await getMetamaskAccount().catch((error) => {
49
50
  throw error;
50
51
  });
52
+
51
53
  const account = response.account;
52
54
  let web3;
53
55
 
@@ -60,12 +62,15 @@ const clientTokenTransfer = async ({
60
62
  if (!web3.utils.isAddress(account)) {
61
63
  throw new Error("Not valid account");
62
64
  }
65
+
63
66
  if (!web3.utils.isAddress(tokenAddress)) {
64
67
  throw new Error("Is not a Token Address");
65
68
  }
69
+
66
70
  if (!web3.utils.isAddress(walletAddressToTransferTo)) {
67
71
  throw new Error("Is not a Wallet Address to transfer to");
68
72
  }
73
+
69
74
  if (amount <= 0) {
70
75
  throw new Error("Amount must be greater than 0.");
71
76
  }
@@ -98,30 +103,27 @@ const clientTokenTransfer = async ({
98
103
  }
99
104
  };
100
105
 
101
- const sendTokenToWallet = async ({tokenAddress}) => {
102
- if (!checkIfMetamaskIsAvailable()) {
103
- return METAMASK_NOT_INSTALLED_MESSAGE
106
+ const sendTokenToWallet = async ({ tokenAddress }) => {
107
+ // Cambiar a red Polygon
108
+ const polygonResponse = await selectOrAddPolygonMainNetwork();
109
+ if (!polygonResponse.ok) {
110
+ throw polygonResponse;
104
111
  }
105
112
 
106
- await getMetamaskAccount().catch((error) => {
107
- throw error;
108
- });
109
-
110
113
  let web3 = new Web3(Metamask);
111
114
  let tokenAdded = false;
112
115
 
113
- const MyTokenContractInstance = new web3.eth.Contract(
114
- abiToken,
115
- tokenAddress
116
- );
116
+ const MyTokenContractInstance = new web3.eth.Contract(abiToken, tokenAddress);
117
117
 
118
118
  try {
119
119
  const symbol = await MyTokenContractInstance.methods.symbol().call();
120
- const decimals = web3.utils.toNumber(await MyTokenContractInstance.methods.decimals().call())
120
+ const decimals = web3.utils.toNumber(
121
+ await MyTokenContractInstance.methods.decimals().call()
122
+ );
121
123
  const response = await Metamask.request({
122
- method: 'wallet_watchAsset',
124
+ method: "wallet_watchAsset",
123
125
  params: {
124
- type: 'ERC20',
126
+ type: "ERC20",
125
127
  options: {
126
128
  address: tokenAddress,
127
129
  symbol: symbol,
@@ -131,27 +133,25 @@ const sendTokenToWallet = async ({tokenAddress}) => {
131
133
  });
132
134
  tokenAdded = !!response;
133
135
  } catch (error) {
134
- return error
136
+ return error;
135
137
  }
136
138
  return tokenAdded;
137
-
138
139
  };
139
140
 
140
141
  const isMetamaskInstalled = () => {
141
142
  if (!checkIfMetamaskIsAvailable()) {
142
- return METAMASK_NOT_INSTALLED_MESSAGE
143
+ return METAMASK_NOT_INSTALLED_MESSAGE;
143
144
  }
144
145
  return {
145
146
  ok: true,
146
147
  message: "Metamask is installed",
147
148
  };
148
-
149
149
  };
150
150
 
151
151
  const checkWalletFormat = (account) => {
152
152
  let web3;
153
153
  if (!checkIfMetamaskIsAvailable()) {
154
- return METAMASK_NOT_INSTALLED_MESSAGE
154
+ return METAMASK_NOT_INSTALLED_MESSAGE;
155
155
  }
156
156
  try {
157
157
  web3 = new Web3(Metamask);
@@ -178,57 +178,58 @@ const checkWalletFormat = (account) => {
178
178
 
179
179
  const selectOrAddPolygonMainNetwork = async () => {
180
180
  if (!checkIfMetamaskIsAvailable()) {
181
- return METAMASK_NOT_INSTALLED_MESSAGE
181
+ return METAMASK_NOT_INSTALLED_MESSAGE;
182
182
  }
183
183
  await getMetamaskAccount().catch((error) => {
184
184
  throw error;
185
185
  });
186
186
  try {
187
+ // Primero intentar cambiar a la red de Polygon si ya existe
187
188
  await Metamask.request({
188
189
  method: "wallet_switchEthereumChain",
189
- params: [{chainId: "0x89"}],
190
+ params: [{ chainId: "0x89" }], // ChainId de Polygon Mainnet en hexadecimal
190
191
  });
191
192
  return {
192
193
  ok: true,
193
194
  message: "Already on polygon main network",
194
195
  };
195
196
  } catch (switchError) {
197
+ // Si el error es 4902, significa que la red no está añadida
196
198
  if (switchError.code === 4902) {
197
- const params = [
198
- {
199
- chainId: "0x89",
200
- chainName: "Matic MainNet",
201
- nativeCurrency: {
202
- name: "MATIC",
203
- symbol: "MATIC",
204
- decimals: 18,
205
- },
206
- rpcUrls: [
207
- "https://polygon-rpc.com/",
208
- "https://rpc-mainnet.maticvigil.com/",
209
- ],
210
- blockExplorerUrls: ["https://polygonscan.com/"],
211
- },
212
- ];
213
199
  try {
214
200
  const response = await Metamask.request({
215
201
  method: "wallet_addEthereumChain",
216
- params: params,
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
+ ],
217
218
  });
218
219
  return {
219
220
  ok: true,
220
- message: "Matic MainNet added successfully",
221
+ message: "Polygon MainNet added successfully",
221
222
  response: response,
222
223
  };
223
224
  } catch (error) {
224
225
  return {
225
226
  ok: false,
226
- message: "Matic MainNet can not be added",
227
- response: error,
227
+ message: error.message,
228
+ code: error.code,
228
229
  };
229
230
  }
230
- }else{
231
- throw switchError
231
+ } else {
232
+ throw switchError;
232
233
  }
233
234
  }
234
235
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dracoder-web3-package",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Dracoder package used for web3 provider integration.",
5
5
  "main": "index.js",
6
6
  "keywords": [