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

Change the webcrypto polyfill to require calling an `install` function #2902

Closed mcintyre94 closed 2 days ago

mcintyre94 commented 3 days ago

This PR refactors the webcrypto polyfill so that all its functionality is in an install function. This must be called to enable the polyfill and it is no longer automatically installed by just importing. This gives apps more control over when the polyfill is called.

Example:

import { install } from '@solana/webcrypto-ed25519-polyfill';

async function main() {
    try {
        await crypto.subtle.generateKey('Ed25519', false, ['sign']);
    } catch (e) {
        console.log('unable to create keypair first time');
    }
    install();
    const keyPair = await crypto.subtle.generateKey('Ed25519', false, ['sign']); 
    console.log(keyPair);
}

main().then(() => console.log('done!'));

This will first log "unable to create keypair first time", as the polyfill is not yet installed. It will then log an Ed25519 keypair object created after installing the polyfill.

Fixes #2898

changeset-bot[bot] commented 3 days ago

⚠️ No Changeset found

Latest commit: bfc86aa1e75380d040828bd1f347131f3ab62ce4

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

lorisleiva commented 3 days ago

Nice!

nit: Since that's all we're exporting, how would feel about exporting the install function as the default export?

mcintyre94 commented 3 days ago

Actually that's probably a nice idea because in the case of Steve's example in the issue, another library has a named install export. Letting callers name ours themselves probably makes it a bit nicer to use.