Guía definitiva para usar librerías web3 en Angular.
Si has intentado crear un proyecto de web3 o buscado documentación, es muy probable que encontraras que muchas están destinadas a React u otros frameworks afortunadamente el error es común y fácil de arreglar.
Error: Module not found: Error: Can't resolve 'crypto'.
Este es muy común en versiones con Ivy, a partir de la v12 hasta la más actual, así que solo hacemos lo siguiente:
Configuración
Generar un nuevo proyecto.
ng new nombre-app
Instalar web3 y sus dependencias con:
npm i web3 -S
npm i crypto-browserify stream-browserify assert stream-http https-browserify os-browserify browser url os-browserify process -S-
Agrega lo siguiente al polyfills.ts:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport 'zone.js'; import * as process from 'process'; import { Buffer } from 'buffer'; window.process = process; (window as any).global = window; global.Buffer = global.Buffer || Buffer; -
Agrega lo siguiente al tsconfig.json:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters/* To learn more about this file see: https://angular.io/config/tsconfig. */ { "compileOnSave": false, "compilerOptions": { "paths": { "crypto": ["./node_modules/crypto-browserify"], "stream": ["./node_modules/stream-browserify"], "assert": ["./node_modules/assert"], "http": ["./node_modules/stream-http"], "https": ["./node_modules/https-browserify"], "process": ["./node_modules/process/browser"], "url": ["./node_modules/url"], "os": ["./node_modules/os-browserify"] }, "baseUrl": "./", ... // your config options / configuracion de nuestro proyecto }, "angularCompilerOptions": { "types" : ["node"], "allowSyntheticDefaultImports": true, "enableI18nLegacyMessageIdFormat": false, "strictInjectionParameters": true, "strictInputAccessModifiers": true, "noImplicitAny": false, "strictTemplates": true, "strictNullChecks": false } } -
Genera un Web3 service
ng g service web3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; // Web3 Stuff | Dependencias de Web3 import Web3 from 'web3'; import Web3Modal from "web3modal"; import WalletConnectProvider from "@walletconnect/web3-provider"; // this profile wallet handler import { provider } from 'web3-core'; @Injectable({ providedIn: 'root' }) export class Web3Service { public accountsObservable = new Subject<string[]>(); web3Modal; web3js: any; provider: provider | undefined; accounts: string[] | undefined; balance: string | undefined; constructor() { const providerOptions = { walletconnect: { package: WalletConnectProvider, // required | here whe import the package necessary to support wallets|| aqui importamos el paquete que nos ayudara a usar soportar distintas wallets options: { infuraId: 'env', // required change this with your own infura id | cambia esto con tu apikey de infura description: 'Scan the qr code and sign in', // You can change the desciption | Puedes camnbiar los textos descriptivos en la seccion description qrcodeModalOptions: { mobileLinks: [ 'rainbow', 'metamask', 'argent', 'trust', 'imtoken', 'pillar' ] } } }, injected: { display: { logo: 'https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg', name: 'metamask', description: "Connect with the provider in your Browser" }, package: null }, }; this.web3Modal = new Web3Modal({ network: "mainnet", // optional change this with the net you want to use like rinkeby etc | puedes cambiar a una red de pruebas o etc cacheProvider: true, // optional providerOptions, // required theme: { background: "rgb(39, 49, 56)", main: "rgb(199, 199, 199)", secondary: "rgb(136, 136, 136)", border: "rgba(195, 195, 195, 0.14)", hover: "rgb(16, 26, 32)" } }); } async connectAccount() { this.provider = await this.web3Modal.connect(); // set provider if (this.provider) { this.web3js = new Web3(this.provider); } // create web3 instance this.accounts = await this.web3js.eth.getAccounts(); return this.accounts; } async accountInfo(account: any[]){ const initialvalue = await this.web3js.eth.getBalance(account); this.balance = this.web3js.utils.fromWei(initialvalue , 'ether'); return this.balance; } } -
Consume el servicio desde el componente que quieras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport {Component} from '@angular/core'; // Important part | parte importante ↙ import {Web3Service} from "./web3.service"; @Component({ selector: 'app-component', templateUrl: './your.component.html', styleUrls: ['./your.component.css'] }) export class yourComponent { title = 'lastng'; direction: string[] | undefined; // Important part | parte importante ↙ constructor( private web3: Web3Service) { } // Important part | parte importante ↙ Connect() { this.web3.connectAccount().then(response => { console.log(response); this.direction = response; }).catch((error: any) => { console.error(error); }); } } ng serve y ng build no debería mostrar ningún problema
Si aparece un error con @types/node haz:
npm i -S @types/node
Then in tsconfig.json
"angularCompilerOptions": {
"types" : ["node"]
....
}
Extra Si deseas usar un template aqui hice uno:
AntonioCardenas
/
AngularWeb3Boilerplate
Template for Angular and web3 dependencies
Angular Web3 Template.
Now you can easily add crypto dependencies and implement solutions
Using the power of Angular.
This project was generated with Angular CLI version 13.1.3
Development server
Run ng serve
for a dev server. Navigate to http://localhost:4200/
. The app will automatically reload if you change
any of the source files.
Code scaffolding
Run ng generate component component-name
to generate a new component. You can also
use ng generate directive|pipe|service|class|guard|interface|enum|module
.
Build
Run ng build
to build the project. The build artifacts will be stored in the dist/
directory.
Running unit tests
Run ng test
to execute the unit tests via Karma.
Running end-to-end tests
Run ng e2e
to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a
package that implements end-to-end testing capabilities.
Provider
This Dapp use web3modal allow us to…
Top comments (0)