Mobile using Expo

Introduction

This guide demonstrates how to integrate Request Network into a React Native application using Expo. Due to the differences between Node.js and React Native environments, several polyfills and configurations are necessary to make Request Network work properly. Following this guide will set up your Expo project to use Request Network, handle polyfills for missing modules, and ensure smooth integration. A full Github repository with Request Network support can be found here.

Installation

After creating a new Expo project, install the necessary dependencies:

npm install @requestnetwork/request-client.js @requestnetwork/types @requestnetwork/payment-processor @requestnetwork/epk-signature buffer eventemitter3 stream-browserify http-browserify https-browserify react-native-get-random-values tweetnacl node-forge [email protected]

Setup

1- Create a new file named index.js in the root of your project

touch index.js

2- Add the following content to index.js

https://github.com/RequestNetwork/rn-expo-support/blob/5a771c31051ce89c4feee533692028d45e1415ab/index.js
// Buffer polyfill
import { Buffer } from "buffer";
global.Buffer = Buffer;

import "react-native-get-random-values";

// Crypto Polyfill
import cryptoPolyfill from "./cryptoPolyfill";
if (typeof global.crypto !== "object") {
  global.crypto = {};
}
Object.assign(global.crypto, cryptoPolyfill);

// Event Emitter polyfill
import EventEmitter from "eventemitter3";
global.EventEmitter = EventEmitter;

// Stream Polyfill
import { Readable, Writable } from "stream-browserify";
global.Readable = Readable;
global.Writable = Writable;

// HTTP Polyfill
import http from "http-browserify";
global.http = http;

// HTTPS Polyfill
import https from "https-browserify";
global.https = https;

// Starting expo router
import "expo-router/entry";

3- Create a file named cryptoPolyfill.js in the root of your project

touch cryptoPolyfill.js

4- Add the following content to cryptoPolyfill.js

https://github.com/RequestNetwork/rn-expo-support/blob/5a771c31051ce89c4feee533692028d45e1415ab/cryptoPolyfill.js
import nacl from "tweetnacl";
import forge from "node-forge";
import { Buffer } from "buffer";

const randomBytes = (size, callback) => {
  if (typeof size !== "number") {
    throw new TypeError("Expected number");
  }
  const bytes = Buffer.from(nacl.randomBytes(size));
  if (callback) {
    callback(null, bytes);
    return;
  }
  return bytes;
};

const createHash = (algorithm) => {
  const md = forge.md[algorithm.toLowerCase()].create();
  return {
    update: function (data) {
      md.update(
        typeof data === "string" ? data : forge.util.createBuffer(data)
      );
      return this;
    },
    digest: function (encoding) {
      const digest = md.digest().getBytes();
      return encoding === "hex"
        ? forge.util.bytesToHex(digest)
        : Buffer.from(digest, "binary");
    },
  };
};

const createCipheriv = (algorithm, key, iv) => {
  const cipher = forge.cipher.createCipher(
    algorithm,
    forge.util.createBuffer(key)
  );
  cipher.start({ iv: forge.util.createBuffer(iv) });
  let output = forge.util.createBuffer();

  return {
    update: (data) => {
      cipher.update(forge.util.createBuffer(data));
      output.putBuffer(cipher.output);
      return Buffer.from(output.getBytes(), "binary");
    },
    final: () => {
      cipher.finish();
      output.putBuffer(cipher.output);
      const result = Buffer.from(output.getBytes(), "binary");
      output.clear();
      return result;
    },
    getAuthTag: () => {
      if (algorithm.includes("gcm")) {
        return Buffer.from(cipher.mode.tag.getBytes(), "binary");
      }
      throw new Error("getAuthTag is only supported for GCM mode");
    },
  };
};

const createDecipheriv = (algorithm, key, iv) => {
  const decipher = forge.cipher.createDecipher(
    algorithm,
    forge.util.createBuffer(key)
  );
  decipher.start({ iv: forge.util.createBuffer(iv) });
  let output = forge.util.createBuffer();
  let authTag;

  return {
    update: (data) => {
      decipher.update(forge.util.createBuffer(data));
      output.putBuffer(decipher.output);
      return Buffer.from(output.getBytes(), "binary");
    },
    final: () => {
      decipher.finish();
      output.putBuffer(decipher.output);
      const result = Buffer.from(output.getBytes(), "binary");
      output.clear();
      return result;
    },
    setAuthTag: (tag) => {
      if (algorithm.includes("gcm")) {
        authTag = tag;
        decipher.mode.tag = forge.util.createBuffer(tag);
      } else {
        throw new Error("setAuthTag is only supported for GCM mode");
      }
    },
  };
};

const pbkdf2 = (password, salt, iterations, keylen, digest, callback) => {
  try {
    const derivedKey = forge.pkcs5.pbkdf2(
      password,
      salt,
      iterations,
      keylen,
      digest
    );
    const result = Buffer.from(derivedKey, "binary");
    if (callback) {
      callback(null, result);
    } else {
      return result;
    }
  } catch (error) {
    if (callback) {
      callback(error);
    } else {
      throw error;
    }
  }
};

const randomFillSync = (buffer, offset, size) => {
  const randomBytes = nacl.randomBytes(size);
  buffer.set(randomBytes, offset);
  return buffer;
};

const timingSafeEqual = (a, b) => {
  if (a.length !== b.length) {
    return false;
  }
  let result = 0;
  for (let i = 0; i < a.length; i++) {
    result |= a[i] ^ b[i];
  }
  return result === 0;
};

const cryptoPolyfill = {
  randomBytes,
  createHash,
  createCipheriv,
  createDecipheriv,
  pbkdf2,
  randomFillSync,
  timingSafeEqual,
};

cryptoPolyfill.default = cryptoPolyfill;

module.exports = {
  randomBytes,
  createHash,
  createCipheriv,
  createDecipheriv,
  pbkdf2,
  randomFillSync,
  timingSafeEqual,
};

export default cryptoPolyfill;

5- Create / Update metro.config.js to use the custom polyfills

https://github.com/RequestNetwork/rn-expo-support/blob/5a771c31051ce89c4feee533692028d45e1415ab/metro.config.js
const { getDefaultConfig } = require("expo/metro-config");

const defaultConfig = getDefaultConfig(__dirname);

defaultConfig.resolver.extraNodeModules = {
  ...defaultConfig.resolver.extraNodeModules,
  crypto: require.resolve("./cryptoPolyfill"),
  stream: require.resolve("stream-browserify"),
  buffer: require.resolve("buffer"),
  http: require.resolve("http-browserify"),
  https: require.resolve("https-browserify"),
};

module.exports = defaultConfig;

6- Update package.json to set the main entry point to index.js

https://github.com/RequestNetwork/rn-expo-support/blob/5a771c31051ce89c4feee533692028d45e1415ab/package.json
{
  "name": "rn-expo-support",
  "main": "./index.js",
  "version": "1.0.0",
  "scripts": {
    "start": "expo start",
    "reset-project": "node ./scripts/reset-project.js",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "test": "jest --watchAll",
    "lint": "expo lint"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/vector-icons": "^14.0.0",
    "@react-navigation/native": "^6.0.2",
    "@requestnetwork/epk-signature": "^0.6.0",
    "@requestnetwork/payment-processor": "^0.44.0",
    "@requestnetwork/request-client.js": "^0.45.0",
    "@requestnetwork/types": "^0.42.0",
    "@requestnetwork/web3-signature": "^0.5.0",
    "ethers": "^5.5.1",
    "eventemitter3": "^5.0.1",
    "expo": "~51.0.14",
    "expo-constants": "~16.0.2",
    "expo-crypto": "~13.0.2",
    "expo-font": "~12.0.7",
    "expo-linking": "~6.3.1",
    "expo-router": "~3.5.16",
    "expo-splash-screen": "~0.27.5",
    "expo-status-bar": "~1.12.1",
    "expo-system-ui": "~3.0.6",
    "expo-web-browser": "~13.0.3",
    "http-browserify": "^1.7.0",
    "https-browserify": "^1.0.0",
    "node-forge": "^1.3.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.74.2",
    "react-native-crypto": "^2.2.0",
    "react-native-gesture-handler": "~2.16.1",
    "react-native-get-random-values": "^1.11.0",
    "react-native-quick-crypto": "^0.6.1",
    "react-native-randombytes": "^3.6.1",
    "react-native-reanimated": "~3.10.1",
    "react-native-safe-area-context": "4.10.1",
    "react-native-screens": "3.31.1",
    "react-native-web": "~0.19.10",
    "stream-browserify": "^3.0.0",
    "tweetnacl": "^1.0.3"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@types/jest": "^29.5.12",
    "@types/react": "~18.2.45",
    "@types/react-test-renderer": "^18.0.7",
    "jest": "^29.2.1",
    "jest-expo": "~51.0.1",
    "react-test-renderer": "18.2.0",
    "typescript": "~5.3.3"
  }
}

7- Ensure that app.json file includes the correct entry point

{
  "expo": {
    "entryPoint": "./index.js",
    ...
  }
}

Polyfills and Configurations

Crypto Polyfills

We've created a custom crypto polyfill (cryptoPolyfill.js) to provide the necessary cryptographic functions. This polyfill uses tweetnacl and node-forge libraries to implement various cryptographic operations.

Why tweetnacl and node-forge?

  1. tweetnacl: It's a fast, secure, and easy-to-use cryptography library. It provides a pure JavaScript implementation of the NaCl cryptography library, which is particularly useful for generating random bytes, essential for cryptographic operations.

  2. node-forge: It provides a comprehensive set of cryptographic tools and utilities. It implements various cryptographic algorithms and protocols that are not natively available in React Native. It's used in our polyfill for operations like hashing, cipher creation, and PBKDF2 key derivation.

Using these libraries allows us to implement a more complete set of cryptographic functions that closely mimic the Node.js crypto module, which is not available in React Native.

Important Notes

  1. Ensure you're using compatible versions of React Native and Expo.

  2. The crypto polyfill may not cover all use cases. Test thoroughly and adjust as needed.

  3. Be cautious when handling private keys. Never expose them in your code or version control.

  4. The example code uses environment variables for private keys. Ensure you set these up correctly and securely.

Last updated

Was this helpful?