How To Add bitcoinjs-lib To A React Native v0.60+ Project
Add/Link the following dependencies:
yarn add bitcoinjs-lib ecpair @bitcoinerlab/secp256k1 react-native-randombytes buffer readable-stream
yarn add --dev rn-nodeify
cd ios && pod install && cd ..
- Add the following postinstall to your script in package.json:
"postinstall": "rn-nodeify --install buffer,stream,assert,events,crypto,vm,process --hack"
Install any remaining dependencies and run postinstall.
NOTE: (If you receive an error about "shim.js" not existing just run yarn install
again):
-
yarn install
-
Uncomment
require('crypto')
at the bottom of "shim.js". Or addrequire('crypto')
to the bottom of "shim.js" if it doesn't exist. -
And finally,
yarn install && cd ios && pod install && cd ..
one more time.
To test if everything is working as expected place the following in render:
import './shim';
import ECPairFactory from 'ecpair';
import ecc from '@bitcoinerlab/secp256k1';
const bitcoin = require('bitcoinjs-lib');
const ECPair = ECPairFactory(ecc);
const keyPair = ECPair.makeRandom();
const {address} = bitcoin.payments.p2pkh({pubkey: keyPair.publicKey});
console.log(address);
An unedited video walkthrough of this guide can be found here:
- https://youtu.be/pKRM5eAZl8c (outdated)
Thanks for your reply. I thought I could get this running without tiny-secp256k1 which adds more problems. This is what I did now:
yarn add ecpair tiny-secp256k1
which resulted in the error:
error: Error: While trying to resolve module tiny-secp256k1 from file /home/xxx/Dev/tests/MyApp/App.js, the package /home/xxx/Dev/tests/MyApp/node_modules/tiny-secp256k1/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/home/xxx/Dev/tests/MyApp/node_modules/tiny-secp256k1/lib/cjs/index.cjs. Indeed, none of these files exist:
This seems to be a Issue in metro, so I added the following in metro.config.js:
const { getDefaultConfig } = require("metro-config"); const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
and
resolver: { ...defaultResolver, sourceExts: [ ...defaultResolver.sourceExts, "cjs", ], },
inside module.exports = .
This leads to the following error:
Unable to resolve module fs from /home/xxx/Dev/tests/MyApp/node_modules/tiny-secp256k1/lib/cjs/wasm_loader.cjs: fs could not be found within the project or in these directories
So I added fs and path in the postinstall script in package.json:
"postinstall": "rn-nodeify --install buffer,stream,assert,events,crypto,vm,process,fs,path --hack"
now I'm stuck with this error when I run "npm run android".
TypeError: (0, _$$_REQUIRE(_dependencyMap[0], "fs").readFileSync) is not a function. (In '(0, _$$_REQUIRE(_dependencyMap[0], "fs").readFileSync)((0, _$$_REQUIRE(_dependencyMap[1], "./wasm_path_cjs.cjs").path)("secp256k1.wasm"))', '(0, _$$_REQUIRE(_dependencyMap[0], "fs").readFileSync)' is undefined)
Any idea how I can fix that?
Thanks!