solana-labs / solana-web3.js

Solana JavaScript SDK
https://solana-labs.github.io/solana-web3.js
MIT License
1.97k stars 791 forks source link

You should be able to time when to polyfill Ed25519 crypto methods #2898

Closed steveluscher closed 2 days ago

steveluscher commented 4 days ago

Motivation

Presently, for environments that don't support Ed25519 natively (React Native, old browsers) we need a polyfill. We would benefit from being able to time when that polyfill installs.

Example use case

Our current implementation of that is to do a raw require of this:

import '@solana/webcrypto-ed25519-polyfill';

There comes a problem when you're building a React Native application. RN applications themselves need a polyfill of the entire SubtleCrypto API because it doesn't exist to begin with.

One example of this is https://github.com/margelo/react-native-quick-crypto. This doesn't work with our solution because doing this:

import { install } from 'react-native-quick-crypto';
install();
import '@solana/webcrypto-ed25519-polyfill';

Results in this sequence of events:

  1. Our polyfill's module factory runs first and creates globalThis.crypto.subtle
  2. The install() method of react-native-quick-crypto runs second and overwrites globalThis.crypto

And you're left without the Ed25519 polyfill. Womp womp.

Details

Either

  1. Stop polyfilling in the module factory and instead export an install() method that people have to call. Update all the docs and example apps, or
  2. Export two versions of @solana/webcrypto-ed25519-polyfill (eg. export a @solana/webcrypto-ed25519-polyfill/installer) so that you can either bare-import the automatic-install version or import an install() method that you can call at the right time.

The second would be elegant, but subpackage exports might be a huge pain in the ass so don't kill yourself trying to make it work.