Home > database >  Unable to resolve module crypto
Unable to resolve module crypto

Time:01-24

I am attempting to implement WalletConnect V1 in my React-Native Wallet app. However, whenever I use the following import:

import WalletConnect from "@walletconnect/client";

I get the following error:

Unable to resolve module crypto from /Users/<my-name>/<company-name>/<client-name>/<app-name>/node_modules/@walletconnect/randombytes/dist/cjs/node/index.js: crypto could not be found within the project or in these directories:
  node_modules

I tried following some solutions but installing crypto-js and [email protected] both did not fix the issue. I also already have react-native-crypto installed in my application.

Any help figuring out what I need to do to resolve this error would be amazing!

CodePudding user response:

Just add custom resolver to your metro config

// metro.config.js
module.exports = {
  resolver: {
    extraNodeModules: {
      crypto: require('react-native-cyrpto'),
    },
  },
};

Unfortunately crypto depends on other nodejs packages like: net, tls, fs and etc. Recommend using https://github.com/parshap/node-libs-react-native which polyfills node packages inside react-native

Docs

tldr;

nom install node-libs-react-native

// metro.config.js
module.exports = {
  resolver: {
    extraNodeModules: require('node-libs-react-native'),
  },
};

CodePudding user response:

I managed to solve this thanks to this post (https://github.com/parshap/node-libs-react-native/issues/23)

yarn add react-native-get-random-values

const nodelibs = require("node-libs-react-native");

nodelibs.crypto = `${__dirname}/src/crypto.js`;

module.exports = {
  resolver: {
    extraNodeModules: nodelibs,
  },
};

Then created my own crypto.js file

// src/crypto.js
'use strict'
import { Buffer } from 'buffer';
const { NativeModules } = require('react-native');

const randomBytes = (size) => {
  if (NativeModules.RNGetRandomValues) {
    return Buffer(NativeModules.RNGetRandomValues.getRandomBase64(size));
  } else {
    throw new Error('Native module not found')
  }
};

exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = randomBytes;
  • Related