Cómo crear una aplicación web Ethereum Wallet

Una revisión de las partes más geniales de eth-hot-wallet

Este artículo es una revisión técnica de las partes interesantes de eth-hot-wallet , una aplicación web de billetera Ethereum con soporte nativo de token erc20. El código fuente se puede encontrar en GitHub (licencia MIT).

Tabla de contenido:

  • Billetera Ethereum como aplicación web
  • La pila
  • Los contenedores de eth-hot-wallet
  • Diseño unificado para Ethereum Wallet
  • Redux y Redux-Saga
  • Generador de contraseñas seguras
  • eth-lightwallet y SignerProvider
  • Almacenamiento sin conexión cifrado
  • Envío de Ethereum mediante Web3.js
  • Envío de tokens erc20 mediante Web3.js
  • Suscripción al ciclo de vida de las transacciones de Ethereum mediante los canales Web3.js V1 y Redux-Saga
  • Sondeo de la cadena de bloques de Ethereum y los datos de precios con Redux-Saga
  • Vigilar el tamaño del paquete
  • Conclusión

Billetera Ethereum como aplicación web

Cuando el software se implementa como una aplicación web, lo primero que me viene a la mente es una amplia accesibilidad. Después de todo, la web es la plataforma multidispositivo más accesible. Eth-hot-wallet es una PWA (aplicación web progresiva) que se puede utilizar desde cualquier navegador web moderno.

Además, las mejoras recientes en la compatibilidad con PWA mejoran significativamente la experiencia del usuario en dispositivos móviles.

Pros:

  • No se requiere software adicional
  • No es necesaria ninguna instalación de ningún tipo
  • Capacidad para utilizar herramientas de desarrollo web modernas.
  • Fácil de implementar y actualizar

Contras:

  • Más propenso a ataques de phishing.
  • Los complementos del navegador pueden inyectar código malicioso en la página.
  • Alto tiempo de carga en conexiones lentas a Internet
  • Acceso limitado al almacenamiento del dispositivo

El hecho de que las extensiones de navegador maliciosas puedan inyectar código JavaScript en un intento de extraer las claves es significativo. Para migrar este riesgo, se debe alentar al usuario a desactivar las extensiones (es decir, mediante el uso en modo incógnito) o integrar la web con un proveedor web3 externo como MetaMask o el navegador Trust. Convertir la aplicación web en una aplicación de escritorio también es una opción viable.

En cuanto al phishing, se debe alentar al usuario a marcar la página y acceder a ella a través de la búsqueda de Google. Es muy poco probable que un sitio de phishing se ubique por encima del sitio real en los resultados de búsqueda.

En pocas palabras: una aplicación web le permitirá llegar a la audiencia más amplia con un mínimo de fricción . En mi opinión, la web es la mejor plataforma de destino para nuevas aplicaciones.

La pila

La mayor parte del código está dedicado al front-end:

El paquete final consta de muchos paquetes como se puede ver en package.json.

Los componentes de nivel superior incluyen:

  • Eth-lightwallet: JS Wallet ligero para Node y el navegador para la gestión del almacén de claves
  • React, Redux, saga.js, immutableJS y reselección envuelto por el primer reaccionar sin conexión
  • Diseño de hormiga: excelente conjunto de componentes de interfaz de usuario para reaccionar
  • Webpack: un paquete para JavaScript y amigos.

Y para el back-end:

El paquete final se implementa directamente en las páginas de GitHub desde una rama dedicada en el repositorio. No hay necesidad de un back-end en la escena tradicional.

Para crear el grifo Testnet Ethereum, usaremos un marco sin servidor. Mejora significativamente la experiencia del desarrollador al utilizar AWS Lambda. Es una solución muy rentable que elimina la necesidad de mantener la infraestructura, especialmente en aplicaciones de bajo volumen.

Los contenedores de eth-hot-wallet

Cuando se usa la combinación de React, Redux, Saga.js y Reselect, cada contenedor (puede) constar de los siguientes ingredientes:

  • index.js - para renderizar la GUI
  • actions.js
  • reducer.js
  • saga.js
  • selectors.js
  • constants.js

Como dijo Dan Abramov, hay más de un enfoque sobre si usar un componente o un contenedor. Según mi experiencia, si un componente tiene más de ~ 8 atributos dentro del estado de la aplicación, debe separarse en un nuevo contenedor. Esta es solo una regla general. La cantidad de atributos puede aumentar con el tiempo. Con componentes complejos, es mejor tener un contenedor único que agrupar el estado del contenedor principal.

No todos los envases necesitan tener todos los ingredientes. En eth-hot-wallet, el sendTokencontenedor no usa su propio Saga.js. Lo separamos para no sobrecargar el estado del componente de la página de inicio.

El contenedor de la página de inicio

El contenedor principal, donde tiene lugar la mayor parte de la acción, es el contenedor de la página de inicio. En el contenedor de la página de inicio, Saga.js es responsable de lidiar con los efectos secundarios. Además de la GUI, su principal responsabilidad se ocupará de las operaciones del almacén de claves .

El paquete ETH-Lightwallet proporciona el almacén de claves. Todas las operaciones relacionadas, incluidas las claves, las semillas, el cifrado, la importación y la exportación, se realizan en esta sección.

El contenedor de encabezado

El encabezado demuestra el hecho de que un contenedor es mucho más que un componente GUI:

This container might look simple at first with only a logo and a network selector. Does it even need to be in its own container? The answer is that in eth-hot-wallet every network communication-related action and state management is done inside the header container. More than enough for any container.

The SendToken container

SendToken is a modal that appears while the user selects to send Ether/ tokens.

The modal includes some basic input verification, like amount and Ethereum address check. It does not use Saga.js to initiate side effects, but instead uses actions provided by the homepage and header containers.

We separated it into a new container to reduce clustering the state of the homepage container.

TokenChooser container

Token Chooser appears when the user wants to select what token the wallet will manage.

The TokenChooser name was selected in order not to be confused with the term “selector” which appears many times through the wallet code in a different context (reduxjs/reselect: Selector library for Redux).

Same as with the SendToken container, TokenChooser does not use its own Saga.js file but calls actions from the homepage container when needed.

A Unified design for Ethereum Wallet

Since the appearance of the ERC20 standard (EIP20), it was obvious that tokens were going to be an important part of the Ethereum ecosystem. The Ethereum wallet was designed with a unified design approach in mind. Ether and token should be treated equally from the user’s perspective.

Under the hood, the API for sending Ether and sending tokens is quite different. So is checking the balance, but they will appear the same on the GUI.

To send Ether, we need to use native functions provided by the web3.js library, while sending tokens and checking balances involves interaction with a smart contract. More on this issue later.

Redux and Redux-Saga

Using Redux store as a single source of truth greatly benefits the wallet. GUI actions and user-triggered flows can be relatively easily managed by actions and reducers provided by Redux.

Aside from keeping the UI state, the Redux store also holds the key-store object (a partially encrypted JavaScript object supplied by eth-lightwallet). This makes the keystore accessible throughout the app by using a selector.

Redux-Saga is what makes the entire setup shine.

redux-saga es una biblioteca que tiene como objetivo hacer que los efectos secundarios de la aplicación (es decir, cosas asincrónicas como la búsqueda de datos y cosas impuras como acceder al caché del navegador) sean más fáciles de administrar, más eficientes de ejecutar, fáciles de probar y mejores en el manejo de fallas.

Saga.js usa generadores para hacer que los flujos asincrónicos sean fáciles de leer y escribir . Al hacerlo, estos flujos asíncronos se parecen a su código JavaScript síncrono estándar (algo así como async/ awaitpero con más opciones de personalización).

En el caso de la billetera Ethereum, al usar Saga obtenemos una forma cómoda de manejar acciones asincrónicas como llamadas de API de descanso, acciones de almacén de claves, llamadas de blockchain de Ethereum a través de web3.js y más. Todas las solicitudes se gestionan de forma limpia en un solo lugar, no hay un infierno de devolución de llamada y una API muy intuitiva.

Ejemplo de uso para redux-saga:

Secure password generator

To adequately secure the user’s keystore, we need to encrypt it with a strong password. When using eth-lightwallet, the password needs to be provided during the initiation of the hd-wallet.

Let’s assume that we have a function called generateString, which can provide genuinely random strings at any length.

If the user wants to generate a new wallet, we will produce the following parameters:

We can ask the user to confirm the password and the seed or generate a new set on its behalf. Alternatively, we can ask the user for their own existing seed and password.

generateString implementation: We will use the relatively new window.crypto API to get random values (currently supported by all major browsers).

Eth-hot-wallet implementation is based on the following code to generate random but human-readable strings:

After the user has accepted the password and the seed, we can use the values and generate the new wallet.

eth-lightwallet and SignerProvider

  1. LightWallet is intended to be a signing provider for the Hooked Web3 provider.
  2. Hooked Web3 provider has been deprecated, and currently the author recommends the package ethjs-provider-signer as an alternative.
  3. At the moment of writing, there is a bug in ethjs-provider-signer that prevents the display of error messages. The bug was fixed but didn’t merge back into the main branch. Those error messages are critical for this setup to function correctly.

Bottom line: Use eth-lightwallet with this version of ethjs-provider-signer: //github.com/ethjs/ethjs-provider-signer/pull/3 to save time on trial and error.

Encrypted offline storage

The lightwallet keystore vault JSON object is encrypted, and it requires from us an external passwordProvider to safely keep the encryption key. The keystrore object is always encrypted. The app is responsible for safekeeping the password and provides it with any action.

eth-hot-wallet uses Store.js — Cross-browser storage for all use cases, used across the web. Store.js allows us to store the encrypted keystore easily and extract it back from storage when the webpage is accessed.

When the wallet is loaded for the first time, it will check if there is a keystore in local storage and will auto load it to Redux state if so.

At this point, we can read the public data of the keystore but not the keys. To display public data before the user enters the encryption password, we need an additional operation mode: loaded and locked. In this mode, the wallet will display the addresses and fetch the balances but will not be able to perform operations such as sending transactions or even generating new addresses. Triggering any of those actions will prompt for the user’s password.

Sending Ethereum using Web3.js

When using [email protected], the function sendTransaction is provided in the following form:

web3.eth.sendTransaction(transactionObject [, callback])

The callback will return the TX as a result in case of success.

However, to properly integrate it into our saga.js flow, we need to wrap sendTransaction function with a promise:

This way we continue regular Saga.js execution after sendTransaction is called.

Sending erc20 tokens using Web3.js

The Ethereum blockchain does not provide primitives that encapsulate token functionality, nor should it. Every token deployed on Ethereum is, in fact, a program that corresponds to the eip20 specification. Since the Ethereum virtual machine (EVM) is Turing complete (with some restrictions), every token might have a different implementation (even for the same functionality). What unifies all those programs under the term “token” is that they provide the same API as defined by the specification.

When we are sending a token on Ethereum, we are interacting with a smart contract. To communicate with a smart contract we need to know its API, the format for sharing contract’s API called Ethereum Contract ABI.

We will store the erc20 ABI as part of our JavaScript bundle and instantiate a contract during the program run-time:

const erc20Contract = web3.eth.contract(erc20Abi);

After contract setup, we can easily interact with it programmatically using the Web3.js contract API.

For each token we will need a dedicated contract instance:

const tokenContract = erc20Contract.at(tokenContractAddress);

After the creation of contract instance, we can access the contract functions by calling the desired function straight from JavaScript:

See Web3.js contract API for the full details.

We will promisify the tokenContract.transfer.sendTransaction to use it with our redux-saga flow:

It is possible to use es6-promisify or similar instead of writing the promise directly, but I prefer the direct approach in this case.

Subscribing to Ethereum transaction life-cycle using Web3.js V1 and redux-saga channels

eth-hot-wallet uses web3.js v0.2.x and does not support this feature at the moment. The example is provided by another project. It is an important feature and should be used extensively.

The new version of Web3.js (V1.0.0) is shipped with a new contract API that can inform us about transaction life-cycle changes.

Enter the PromiEvent: A promise combined event emitter.

web3.eth.sendTransaction({...}).once('transactionHash', function(hash){ ... }).once('receipt', function(receipt){ ... }).on('confirmation', function(number, receipt){ ... }).on('error', function(error){ ... }).then(function(receipt){ //fired once the receipt is mined});

web3.eth.sendTransaction() will return an object (a promise) that will resolve once the transaction is mined. The same object will allow us to subscribe to ‘transactionHash’, ‘receipt’, ‘confirmation’ and ‘error’ events.

This API is far more informative and elegant than the one provided with 0.2.x version of Web3.js. We will see how we can integrate it into our web app with the help of Saga.js channels. The motivation is to update the application state (Redux store) once a change to the transaction state is detected.

In the following example, we will create a ‘commit’ transaction to an arbitrary smart contract and update app state when we get ‘transactionHash’, ‘receipt’ and ‘error’ events.

We need to initialize the new channel and fork a handler:

The handler will catch all channel events and will call the appropriate Redux action creator.

Once the channel and the handler are both ready and the user initiates the transaction, we need to register to the generated events:

In fact, we don't need a new channel for each transaction and can use the same channel for all types of transactions.

The full source code of this example can be found here.

Polling Ethereum blockchain and price data using redux-saga

There are several ways to watch for blockchain changes. It is possible to use Web3.js to subscribe to events or we can poll the blockchain by ourselves and have more control over some aspects of polling.

In eth-hot-wallet, the wallet is polling the blockchain periodically for balance changes and Coinmarketcap API for price changes.

This redux-saga pattern will allow us to poll any data source or API:

After the CHECK_BALANCES action is seen by the default saga, the checkAllBalances function is called. It can end with one of two possible outcomes: CHECK_BALANCES_SUCCESS or CHECK_BALANCES_ERROR . Each one of them will be caught by watchPollData() to wait X seconds and call checkAllBalance again. This routine will continue until STOP_POLL_BALANCES is caught by watchPollData . After that, it is possible to resume the polling by submitting CHECK_BALANCES action again.

Keeping an eye on the bundle size

When building web apps using JavaScript and npm, it might be tempting to add new packages without analyzing the footprint increase. Eth-hot-wallet uses webpack-monitor to display a chart of all the dependencies and the differences between each build. It allows the developer to see the bundle size change clearly after each new package is added.

Webpack monitor also can help in finding the most demanding dependencies and might even surprise the developer by highlighting the dependencies that do little for the app but contribute a lot to the bundle size.

Webpack-monitor is easy to integrate and is definitely worth including in any webpack based web app.

Conclusion

The issues presented in this article are only part of the challenges that need to be solved when building an Ethereum wallet. However, overcoming those issues will create a solid foundation and will allow us to continue and create a successful wallet.

Building a wallet can also be a great introduction to the world of Ethereum since most distributed applications (DApps) require a similar set of capabilities both from the front-end and blockchain perspective.

ETH Hot Wallet - Ethereum Wallet with ERC20 support

ETH Hot wallet is an Ethereum wallet with ERC20 Support. The keys are generated inside the browser and never sent…eth-hot-wallet.com

In case you have any questions regarding eth-hot-wallet or any related subject, feel free to contact me via Twitter or open an issue on GitHub.