1. 程式人生 > >How to build an Ethereum Wallet web app

How to build an Ethereum Wallet web app

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 is a library that aims to make application side effects (i.e., asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.

Saga.js uses Generators to make asynchronous flows easy to read and write. By doing so, these asynchronous flows look like your standard synchronous JavaScript code (kind of like async/await but with more customization options).

In the case of Ethereum wallet, by using Saga we get a comfortable way to handle asynchronous actions such as rest API calls, keystore actions, Ethereum blockchain calls via web3.js, and more. All the requests are cleanly managed in one place, no callback hell, and very intuitive API.

Example usage for redux-saga:

Secure password generator

A seed and a secure password is auto-generated for the user

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: https://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.

locked wallet after loading from local storage

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 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:

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.

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.

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 example chart

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.

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.