Skip to content

Instantly share code, notes, and snippets.

@generalpiston
Created February 21, 2018 16:55
Show Gist options
  • Save generalpiston/ea5521fa788a98f81dad4ab90ebc234e to your computer and use it in GitHub Desktop.
Save generalpiston/ea5521fa788a98f81dad4ab90ebc234e to your computer and use it in GitHub Desktop.

Web3 + 0x + Connect In React Native

tl;dr

  • Use web3@0.20.x instead of web3@1.0.
  • Install github:abec/node-libs-react-native to get around vm errors.
  • Add the following config to your package.json under the scripts section:

https://gist.github.com/08b5309b1996b1eac80364f155ae3700

Why is Web3 and 0x.js and 0x Connect So Hard in React Native

Web3 and 0x libraries were designed to work in a browser or node.js environment. React Native does not include a couple of libraries necessary for including web3, 0x.js, and 0x Connect. To make things worse, React Native dependency management [1] is different enough to make building them a pain.

First Blood: Web3 Version 1.x vs. 0.20.x

Version 1.0.x of Web3 is the latest and greatest. Unfortunately, the way it manages dependencies has changed. It splits itself up into several packages and ties them together using . React Native's dependency builder/bundler, Metro, has trouble with this. I wasn't able to find a way around this without patching every dependency at runtime, so I opted to use 0.20.x of web3.

Second Blood: unable to resolve module crypto

If you try to use web3 in React Native, the first error you'll encounter is:

https://gist.github.com/405844cf235f1a7442452525e039c230

React Native doesn't include a crypto library [2].

Solution 1. Use web3 Compiled For Browser (Failure)

Solution 2. Include react-native-crypto (Failure)

Solution 3. Include github:abec/node-libs-react-native (Success)

Third Blood: Cannot find variable: self

0x connect has a dependency on isomorphic-fetch, which does not work in React Native. When included, it throws this error:

https://gist.github.com/109c1a15028623b6945528bbc37d8a87

React Native loads main scripts in this order:

  • browser
  • main

isomorphic-fetch includes implementations for browser and fetch. The browser implementation looks like this:

https://gist.github.com/47f056d56799a94b0eb8fbacf012a4f0

React Native has no sense of self and will not be able to include this library.

Solution 1. Replace isomorphic-fetch With Own Implementation (Failure)

Solution 2. Edit The File Before Running (Success)

Add the following config to your package.json under the scripts section:

https://gist.github.com/7aad53ea2e5d7225ab18ca04eb98b0c6

References

  1. Metro Bundler
  2. React Native crypto
  3. node-libs-react-native original blog post
  4. 0x connect issue for isomorphic fetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment