UNPKG

@mysten/sui

Version:
82 lines (56 loc) 2.6 kB
# Web Crypto Signer > Sign transactions using the Web Crypto API For cases where you need to create keypairs directly within client dapps, we recommend using the Web Crypto Signer. This signer leverages the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) to provide a secure and efficient way to generate and manage cryptographic keys in the browser. The generated keys are `Secp256r1` keys which can be persisted between sessions, and are not extractable by client-side code (including extensions). Common use cases for the Web Crypto Signer include: - zkLogin ephemeral keypairs - Session-based keypairs ## Installation To use the Web Crypto Signer, you need to install the `@mysten/signers` package. ```sh npm2yarn npm i @mysten/signers ``` You can then import the `WebCryptoSigner` class from the package: ```typescript ``` ## Create a new signer To generate a new signer, you can invoke the `generate()` static method on the `WebCryptoSigner` class. ```typescript const keypair = await WebCryptoSigner.generate(); ``` ## Persisting and recovering the keypair The private key for the signer is not extractable, but you can persist the keypair using the browser's IndexedDB storage. To streamline this process, the keypair provides an `export()` method which returns an object containing the public key and a reference to the private key: ```typescript // Get the exported keypair: const exported = keypair.export(); // Write the keypair to IndexedDB. // This method does not exist, you need to implement it yourself. We recommend `idb-keyval` for simplicity. await writeToIndexedDB('keypair', exported); ``` You can then recover the keypair by reading it from IndexedDB and passing it to the `import()` method. ```typescript // Read the keypair from IndexedDB. const exported = await readFromIndexedDB('keypair'); const keypair = await WebCryptoSigner.import(exported); ``` > **Warning:** Ensure that you do not call `JSON.stringify` on the exported keypair before > persisting it to IndexedDB, as it will throw an error and fail to persist. ## Usage The usage for a Web Crypto signer is the same as any other keypair. You can derive the public key, derive the address, sign personal messages, sign transactions and verify signatures. See the [Key pairs](./keypairs) documentation for more details. ```typescript const publicKey = keypair.getPublicKey(); const address = publicKey.toSuiAddress(); const message = new TextEncoder().encode('hello world'); await keypair.signPersonalMessage(message); await keypair.signTransaction(txBytes); ```