diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index a3013c865..6426f18ed 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -441,11 +441,6 @@ "count": 1 } }, - "packages/solana-wallet-snap/src/core/components/Domain/Domain.tsx": { - "typescript/no-unsafe-return": { - "count": 1 - } - }, "packages/solana-wallet-snap/src/core/fees/FeeCalculator.test.ts": { "typescript/no-explicit-any": { "count": 1 @@ -558,24 +553,6 @@ "count": 1 } }, - "packages/solana-wallet-snap/src/core/sdk-extensions/codecs.test.ts": { - "typescript/no-unsafe-argument": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/sdk-extensions/codecs.ts": { - "typescript/no-unsafe-assignment": { - "count": 2 - } - }, - "packages/solana-wallet-snap/src/core/sdk-extensions/transaction-messages.ts": { - "no-unused-vars": { - "count": 1 - }, - "typescript/explicit-function-return-type": { - "count": 3 - } - }, "packages/solana-wallet-snap/src/core/services/__mocks__/mockConnection.ts": { "typescript/explicit-function-return-type": { "count": 9 @@ -1254,28 +1231,9 @@ "count": 1 } }, - "packages/solana-wallet-snap/src/entities/instructions/instructions.test.ts": { - "vitest/no-conditional-in-test": { - "count": 4 - } - }, "packages/solana-wallet-snap/src/entities/instructions/instructions.ts": { - "internal-snaps/no-in-operator": { - "count": 1 - }, - "typescript/explicit-function-return-type": { - "count": 2 - }, "typescript/no-explicit-any": { "count": 1 - }, - "typescript/no-unsafe-assignment": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/entities/instructions/programs/secp256k1-secp256r1.ts": { - "typescript/explicit-function-return-type": { - "count": 4 } }, "packages/solana-wallet-snap/src/features/confirmation/components/Advanced/Advanced.tsx": { @@ -1453,43 +1411,6 @@ "count": 1 } }, - "packages/solana-wallet-snap/src/infrastructure/event-emitter/EventEmitter.ts": { - "typescript/explicit-function-return-type": { - "count": 3 - }, - "typescript/no-explicit-any": { - "count": 2 - } - }, - "packages/solana-wallet-snap/src/polyfills/dom-exception/index.ts": { - "typescript/explicit-function-return-type": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/polyfills/ed25519/polyfill.ts": { - "internal-snaps/no-in-operator": { - "count": 1 - }, - "typescript/explicit-function-return-type": { - "count": 4 - } - }, - "packages/solana-wallet-snap/src/polyfills/index.ts": { - "typescript/explicit-function-return-type": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/polyfills/queue-microtask/index.ts": { - "no-shadow": { - "count": 1 - }, - "promise/no-callback-in-promise": { - "count": 1 - }, - "typescript/explicit-function-return-type": { - "count": 2 - } - }, "packages/solana-wallet-snap/src/snapContext.ts": { "no-unused-vars": { "count": 1 diff --git a/packages/solana-wallet-snap/src/core/components/Domain/Domain.tsx b/packages/solana-wallet-snap/src/core/components/Domain/Domain.tsx index 323926132..dc316eff4 100644 --- a/packages/solana-wallet-snap/src/core/components/Domain/Domain.tsx +++ b/packages/solana-wallet-snap/src/core/components/Domain/Domain.tsx @@ -1,15 +1,21 @@ -import type { SnapComponent } from '@metamask/snaps-sdk/jsx'; +import type { SnapComponent, SnapElement } from '@metamask/snaps-sdk/jsx'; import { Box, Link } from '@metamask/snaps-sdk/jsx'; import type { Network } from '../../constants/solana'; import { getSolanaExplorerUrl } from '../../utils/getSolanaExplorerUrl'; -export const Domain: SnapComponent<{ +type DomainProps = { domain: string; scope: Network; address: string; -}> = ({ domain, scope, address }) => { - return ( +}; + +export const Domain: SnapComponent = ({ + domain, + scope, + address, +}) => + ( {/* TODO: Bring it back when there is a smaller avatar option */} {/* */} @@ -17,5 +23,4 @@ export const Domain: SnapComponent<{ {domain} - ); -}; + ) as SnapElement; diff --git a/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.test.ts b/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.test.ts index f38ca6b76..247d8556e 100644 --- a/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.test.ts +++ b/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.test.ts @@ -3,7 +3,7 @@ import { getCompiledTransactionMessageEncoder, pipe, } from '@solana/kit'; -import type { TransactionMessageBytes } from '@solana/kit'; +import type { Transaction, TransactionMessageBytes } from '@solana/kit'; import type { GetMultipleAccountsApi, Rpc } from '@solana/kit'; import { MOCK_EXECUTION_SCENARIOS } from '../services/signer/mocks/scenarios'; @@ -63,7 +63,9 @@ describe('codecs', () => { describe('fromTransactionToBase64String', () => { it('encodes a transaction to a base64 string', () => { - const result = fromTransactionToBase64String(signedTransaction); + const result = fromTransactionToBase64String( + signedTransaction as Transaction, + ); expect(result).toStrictEqual(signedTransactionBase64Encoded); }); diff --git a/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.ts b/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.ts index 8ad3fd5ed..79b803c27 100644 --- a/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.ts +++ b/packages/solana-wallet-snap/src/core/sdk-extensions/codecs.ts @@ -122,7 +122,7 @@ export const fromBase64StringCompiledMessageToTransaction = async ( const signerAccounts = compiledTransactionMessage.staticAccounts .slice(0, compiledTransactionMessage.header.numSignerAccounts) - .map((address) => [address, null]); + .map((address) => [address, null] as const); const signatures = Object.fromEntries(signerAccounts); diff --git a/packages/solana-wallet-snap/src/core/sdk-extensions/transaction-messages.ts b/packages/solana-wallet-snap/src/core/sdk-extensions/transaction-messages.ts index 085effac1..f0260569d 100644 --- a/packages/solana-wallet-snap/src/core/sdk-extensions/transaction-messages.ts +++ b/packages/solana-wallet-snap/src/core/sdk-extensions/transaction-messages.ts @@ -11,6 +11,7 @@ import { } from '@solana-program/compute-budget'; import type { Address, + ExcludeTransactionMessageLifetime, Instruction, Rpc, SimulateTransactionApi, @@ -80,7 +81,10 @@ export const setTransactionMessageLifetimeUsingBlockhashIfMissing = < >( blockhashLifetimeConstraint: TransactionMessageWithBlockhashLifetime['lifetimeConstraint'], transaction: TTransaction, -) => +): + | (TTransaction & TransactionMessageWithBlockhashLifetime) + | (ExcludeTransactionMessageLifetime & + TransactionMessageWithBlockhashLifetime) => isTransactionMessageWithBlockhashLifetime(transaction) ? transaction : setTransactionMessageLifetimeUsingBlockhash( @@ -94,7 +98,9 @@ export const setTransactionMessageLifetimeUsingBlockhashIfMissing = < * @param instruction - The instruction to check. * @returns A predicate function that checks if an instruction is a compute unit price instruction. */ -export const isComputeUnitPriceInstruction = (instruction: Instruction) => +export const isComputeUnitPriceInstruction = ( + instruction: Instruction, +): boolean => instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS && identifyComputeBudgetInstruction({ data: new Uint8Array(), // Provide a default value for instruction.data it can be undefined @@ -147,7 +153,9 @@ export const setComputeUnitPriceInstructionIfMissing = < * @param instruction - The instruction to check. * @returns A predicate function that checks if an instruction is a compute unit limit instruction. */ -export const isComputeUnitLimitInstruction = (instruction: Instruction) => +export const isComputeUnitLimitInstruction = ( + instruction: Instruction, +): boolean => instruction.programAddress === COMPUTE_BUDGET_PROGRAM_ADDRESS && identifyComputeBudgetInstruction({ data: new Uint8Array(), // Provide a default value for instruction.data it can be undefined @@ -281,7 +289,7 @@ export const estimateAndOverrideComputeUnitLimit = async < ), ], }; - } catch (error) { + } catch { // If the estimate fails, return the original transaction message unchanged. return transactionMessage; } diff --git a/packages/solana-wallet-snap/src/entities/instructions/instructions.test.ts b/packages/solana-wallet-snap/src/entities/instructions/instructions.test.ts index 6872aeb2d..3f460894a 100644 --- a/packages/solana-wallet-snap/src/entities/instructions/instructions.test.ts +++ b/packages/solana-wallet-snap/src/entities/instructions/instructions.test.ts @@ -17,15 +17,48 @@ import { toIInstruction, } from './instructions'; +const ASSOCIATED_TOKEN_PROGRAM_ADDRESS = + 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'; + +/** + * Checks whether an instruction is an associated token account creation that + * uses accounts loaded from an address lookup table. + * + * @param accountKeys - The account keys inlined in the transaction message. + * @param instruction - The instruction to check. + * @returns Whether the instruction creates an associated token account. + */ +const isCreateAssociatedTokenInstruction = ( + accountKeys: readonly string[], + instruction: { programIdIndex: number; accounts: readonly number[] }, +): boolean => + accountKeys[instruction.programIdIndex] === + ASSOCIATED_TOKEN_PROGRAM_ADDRESS && + instruction.accounts.some((index) => index >= accountKeys.length); + describe('toIInstruction', () => { beforeEach(() => { vi.clearAllMocks(); vi.spyOn(Errors, 'trackError').mockResolvedValue('tracked-error-id'); }); - it.each(['legacy', 0, 1] as const)( - 'preserves inline account order for version %s', - (version) => { + it.each([ + { version: 'legacy' as const, messageExtras: {} }, + { version: 0 as const, messageExtras: {} }, + { + version: 1 as const, + messageExtras: { + transactionConfig: { + computeUnitLimit: 30_000, + heapSize: null, + loadedAccountsDataSizeLimit: 200_000, + priorityFee: null, + }, + }, + }, + ])( + 'preserves inline account order for version $version', + ({ version, messageExtras }) => { const feePayer = address('11111111111111111111111111111112'); const readonlySigner = address('11111111111111111111111111111113'); const writableAccount = address('11111111111111111111111111111114'); @@ -60,14 +93,7 @@ describe('toIInstruction', () => { ], instructions: [instruction], recentBlockhash: original.transaction.message.recentBlockhash, - ...(version === 1 && { - transactionConfig: { - computeUnitLimit: 30_000, - heapSize: null, - loadedAccountsDataSizeLimit: 200_000, - priorityFee: null, - }, - }), + ...messageExtras, }, }, }; @@ -95,15 +121,13 @@ describe('toIInstruction', () => { 'parses account creation using lookup table accounts in a %s', (_, transaction) => { const { accountKeys, instructions } = transaction.transaction.message; - const accountCreationInstruction = instructions.find( - (instruction) => - accountKeys[instruction.programIdIndex] === - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' && - instruction.accounts.some((index) => index >= accountKeys.length), + const accountCreationInstruction = instructions.find((instruction) => + isCreateAssociatedTokenInstruction(accountKeys, instruction), + ); + assert( + accountCreationInstruction, + 'Fixture must contain an associated token instruction', ); - if (!accountCreationInstruction) { - throw new Error('Fixture must contain an associated token instruction'); - } const converted = toIInstruction(accountCreationInstruction, transaction); @@ -118,8 +142,9 @@ describe('toIInstruction', () => { it('resolves writable and readonly lookup addresses in account index order', () => { const transaction = EXPECTED_SWAP_SOL_TO_OBRIC_DATA; const { accountKeys } = transaction.transaction.message; - const { writable = [], readonly = [] } = - transaction.meta?.loadedAddresses ?? {}; + const loadedAddresses = transaction.meta?.loadedAddresses; + assert(loadedAddresses, 'Fixture must contain loaded addresses'); + const { writable, readonly } = loadedAddresses; const writableIndex = accountKeys.length; const readonlyIndex = writableIndex + writable.length; const [originalInstruction] = transaction.transaction.message.instructions; diff --git a/packages/solana-wallet-snap/src/entities/instructions/instructions.ts b/packages/solana-wallet-snap/src/entities/instructions/instructions.ts index 8776a285b..5cc482c37 100644 --- a/packages/solana-wallet-snap/src/entities/instructions/instructions.ts +++ b/packages/solana-wallet-snap/src/entities/instructions/instructions.ts @@ -1,4 +1,5 @@ import type { Infer } from '@metamask/superstruct'; +import { hasProperty } from '@metamask/utils'; import { COMPUTE_BUDGET_PROGRAM_ADDRESS, ComputeBudgetInstruction, @@ -163,6 +164,8 @@ import type { InstructionWithData, ReadonlyUint8Array, Address, + Transaction, + TransactionMessage, } from '@solana/kit'; import { @@ -189,7 +192,7 @@ import { * @param data - The instruction data to truncate. * @returns The truncated instruction data. */ -export function truncateInstructionData(data: string) { +export function truncateInstructionData(data: string): string { if (data.length > 12) { return `${data.slice(0, 5)}...${data.slice(-5)}`; } @@ -530,6 +533,25 @@ const programAddressToParsingConfig: Record< }, }; +/** + * Gets the parsing config for a program address, if instructions of that + * program can be parsed. + * + * @param programAddress - The program address to look up. + * @returns The parsing config, or `undefined` if the program is unsupported. + */ +const getParsingConfig = ( + programAddress: Address, +): ParsingConfig | undefined => { + // The config is keyed by branded addresses, which TypeScript cannot use as an + // index signature, so the lookup goes through a plain string map. + const configs: Record< + string, + ParsingConfig + > = programAddressToParsingConfig; + return configs[programAddress]; +}; + /** * Parses a generic instruction, returning the parsed instruction if it's supported, * or the original non-parsed instruction if it's not. @@ -585,9 +607,7 @@ export const parseInstruction = ( }; try { - const parsingConfig: ParsingConfig = - // @ts-expect-error - we check if parsingConfig exists right after - programAddressToParsingConfig[programAddress]; + const parsingConfig = getParsingConfig(programAddress); if (!parsingConfig) { // Unsupported programs are expected, so return Unknown without reporting an error to Sentry. @@ -628,6 +648,18 @@ export const parseInstruction = ( } }; +/** + * Checks whether a decoded base64 string is a full transaction, as opposed to a + * bare transaction message. + * + * @param transactionOrTransactionMessage - The decoded value to check. + * @returns Whether the value is a transaction. + */ +const isTransaction = ( + transactionOrTransactionMessage: Transaction | TransactionMessage, +): transactionOrTransactionMessage is Transaction => + hasProperty(transactionOrTransactionMessage, 'messageBytes'); + /** * Extracts the instructions from a base64 string, adapting the logic depending on whether * the string represents a transaction or a transaction message. @@ -647,13 +679,12 @@ export const extractInstructionsFromUnknownBase64String = async ( rpc, ); - const transactionMessage = - 'instructions' in transactionOrTransactionMessage - ? transactionOrTransactionMessage - : await fromBytesToCompilableTransactionMessage( - transactionOrTransactionMessage.messageBytes, - rpc, - ); + const transactionMessage = isTransaction(transactionOrTransactionMessage) + ? await fromBytesToCompilableTransactionMessage( + transactionOrTransactionMessage.messageBytes, + rpc, + ) + : transactionOrTransactionMessage; const { instructions } = transactionMessage; return instructions.map(parseInstruction); @@ -679,7 +710,7 @@ export const toIInstruction = ( ]; // Keep lookup table accounts so instruction parsers receive the complete account list. - const isInAccountKeys = (accountIndex: number) => + const isInAccountKeys = (accountIndex: number): boolean => accountIndex < accountKeys.length; // Build the accounts array diff --git a/packages/solana-wallet-snap/src/entities/instructions/programs/secp256k1-secp256r1.ts b/packages/solana-wallet-snap/src/entities/instructions/programs/secp256k1-secp256r1.ts index 3c48d4b63..1f062717a 100644 --- a/packages/solana-wallet-snap/src/entities/instructions/programs/secp256k1-secp256r1.ts +++ b/packages/solana-wallet-snap/src/entities/instructions/programs/secp256k1-secp256r1.ts @@ -45,12 +45,12 @@ export const identifySecp256Instruction = ( data: ReadonlyUint8Array; } | ReadonlyUint8Array, -) => Secp256Instruction.Verify; +): Secp256Instruction => Secp256Instruction.Verify; -export const isSecp256k1Instruction = (instruction: Instruction) => +export const isSecp256k1Instruction = (instruction: Instruction): boolean => instruction.programAddress === SECP256K1_PROGRAM_ADDRESS; -export const isSecp256r1Instruction = (instruction: Instruction) => +export const isSecp256r1Instruction = (instruction: Instruction): boolean => instruction.programAddress === SECP256R1_PROGRAM_ADDRESS; type Secp256InstructionData = { @@ -73,7 +73,9 @@ export type ParsedSecp256Instruction = { instructionType: typeof Secp256Instruction.Verify; } & ParsedVerifySecp256Instruction; -export const parseVerifySecp256Instruction = (instruction: Instruction) => { +export const parseVerifySecp256Instruction = ( + instruction: Instruction, +): ParsedVerifySecp256Instruction => { return { programAddress: instruction.programAddress, data: getSecp256InstructionCodec().decode( diff --git a/packages/solana-wallet-snap/src/infrastructure/event-emitter/EventEmitter.ts b/packages/solana-wallet-snap/src/infrastructure/event-emitter/EventEmitter.ts index ccc4c0c92..58fcd3856 100644 --- a/packages/solana-wallet-snap/src/infrastructure/event-emitter/EventEmitter.ts +++ b/packages/solana-wallet-snap/src/infrastructure/event-emitter/EventEmitter.ts @@ -1,6 +1,10 @@ import type { Logger } from '@metamask/snap-networks-utils'; -type Listener = (data?: any) => Promise; +/** + * A listener for an event. The payload type is erased when the listener is + * registered, since listeners are only keyed by event name. + */ +type Listener = (data: Data) => Promise; /** * The EventEmitter class is a simple event emitter that allows to register listeners / callbacks for events and emit events. @@ -30,14 +34,16 @@ export class EventEmitter { * @param event - The event to listen to. * @param listener - The listener to call when the event is emitted. */ - on(event: string, listener: Listener) { + on(event: string, listener: Listener): void { this.#logger.info(`Adding listener for event ${event}`); if (!this.#listeners.has(event)) { this.#listeners.set(event, new Set()); } - this.#listeners.get(event)?.add(listener); + // The payload type is erased here because listeners are stored per event + // name, not per payload type. + this.#listeners.get(event)?.add(listener as Listener); } /** @@ -46,7 +52,7 @@ export class EventEmitter { * @param event - The event to remove the listener for. * @param listener - The listener to remove. */ - off(event: string, listener: Listener) { + off(event: string, listener: Listener): void { this.#logger.info(`Removing listener for event ${event}`); const listeners = this.#listeners.get(event); @@ -68,7 +74,7 @@ export class EventEmitter { * @param event - The event to emit. * @param data - The data to pass to the listeners. */ - async emitSync(event: string, data?: any): Promise { + async emitSync(event: string, data?: unknown): Promise { this.#logger.info(`Emitting event ${event}`); const listeners = this.#listeners.get(event); @@ -85,7 +91,7 @@ export class EventEmitter { * * @param event - The event to remove the listeners for. If not provided, all listeners will be removed. */ - removeAllListeners(event?: string) { + removeAllListeners(event?: string): void { if (event) { this.#logger.info(`Removing all listeners for event ${event}`); this.#listeners.delete(event); diff --git a/packages/solana-wallet-snap/src/polyfills/dom-exception/index.ts b/packages/solana-wallet-snap/src/polyfills/dom-exception/index.ts index 7bf7fbdf0..526266246 100644 --- a/packages/solana-wallet-snap/src/polyfills/dom-exception/index.ts +++ b/packages/solana-wallet-snap/src/polyfills/dom-exception/index.ts @@ -1,7 +1,7 @@ /** * Adds support for the DOMException object. */ -export function install() { +export function install(): void { Object.defineProperty(globalThis, 'DOMException', { value: Error, writable: true, diff --git a/packages/solana-wallet-snap/src/polyfills/ed25519/install.test.ts b/packages/solana-wallet-snap/src/polyfills/ed25519/install.test.ts index 6c844369b..9b4be4265 100644 --- a/packages/solana-wallet-snap/src/polyfills/ed25519/install.test.ts +++ b/packages/solana-wallet-snap/src/polyfills/ed25519/install.test.ts @@ -17,6 +17,8 @@ const PKCS8_KEY = new Uint8Array([ const PUBLIC_KEY_HEX = '0xea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c'; +const PRIVATE_KEY_B64U = 'BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc'; +const PUBLIC_KEY_B64U = '6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw'; const MESSAGE = new TextEncoder().encode('hello solana'); const SIGNATURE_HEX = '0x9091b5d70d7c5b015eef7e8133db6c8aa5460f416024e4fac7bde7f1970a71f8257e2f6b6801f3f659817e6e9fbe013f624b72bd62277a42e4ca309737a0b301'; @@ -178,4 +180,51 @@ describe('install', () => { expect(key).toBeInstanceOf(globalThis.CryptoKey); }); + + it('imports JWK keys with the polyfill', async () => { + Object.defineProperty(globalThis.crypto.subtle, 'importKey', { + configurable: true, + writable: true, + value: async () => { + throw new Error('Unsupported algorithm'); + }, + }); + + install(); + + const privateKey = await globalThis.crypto.subtle.importKey( + 'jwk', + { + kty: 'OKP', + crv: 'Ed25519', + d: PRIVATE_KEY_B64U, + x: PUBLIC_KEY_B64U, + }, + ED25519_ALGORITHM, + false, + ['sign'], + ); + + expect(privateKey).not.toBeInstanceOf(globalThis.CryptoKey); + expect(privateKey.type).toBe('private'); + expect(privateKey.usages).toStrictEqual(['sign']); + + const publicKey = await globalThis.crypto.subtle.importKey( + 'jwk', + { kty: 'OKP', crv: 'Ed25519', x: PUBLIC_KEY_B64U }, + ED25519_ALGORITHM, + true, + ['verify'], + ); + + expect(publicKey).not.toBeInstanceOf(globalThis.CryptoKey); + expect(publicKey.type).toBe('public'); + expect(publicKey.usages).toStrictEqual(['verify']); + + expect( + new Uint8Array( + await globalThis.crypto.subtle.exportKey('raw', publicKey), + ), + ).toStrictEqual(hexToBytes(PUBLIC_KEY_HEX)); + }); }); diff --git a/packages/solana-wallet-snap/src/polyfills/ed25519/polyfill.ts b/packages/solana-wallet-snap/src/polyfills/ed25519/polyfill.ts index 79cc0727d..4a1872a6c 100644 --- a/packages/solana-wallet-snap/src/polyfills/ed25519/polyfill.ts +++ b/packages/solana-wallet-snap/src/polyfills/ed25519/polyfill.ts @@ -1,4 +1,5 @@ /* eslint-disable no-restricted-globals */ +import { hasProperty } from '@metamask/utils'; import * as ed from '@noble/ed25519'; import { bufferSourceAsUint8Array } from './utils/buffer-source-as-uint8-array'; @@ -35,7 +36,7 @@ const ED25519_PKCS8_HEADER = [ * @param input - The Uint8Array to convert. * @returns The base64 string with URL-safe characters. */ -export function toBase64(input: Uint8Array) { +export function toBase64(input: Uint8Array): string { return Buffer.from(input) .toString('base64') .replace(/\+/gu, '-') @@ -49,7 +50,7 @@ export function toBase64(input: Uint8Array) { * @param b64u - The base64 string with URL-safe characters. * @returns The Uint8Array. */ -export function toBuffer(b64u: string) { +export function toBuffer(b64u: string): Uint8Array { const a = b64u.replace(/-/gu, '+').replace(/_/gu, '/'); const b = new Uint8Array(Buffer.from(a, 'base64')); @@ -63,7 +64,10 @@ export function toBuffer(b64u: string) { * @param key - The key to export. * @returns The exported key data. */ -export async function exportKey(format: KeyFormat | string, key: CryptoKey) { +export async function exportKey( + format: KeyFormat | string, + key: CryptoKey, +): Promise { if (!key.extractable) { throw new DOMException('key is not extractable', 'InvalidAccessException'); } @@ -188,7 +192,7 @@ export async function importKey( _algorithm: AlgorithmIdentifier | KeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[], -) { +): Promise { const usages = Array.from(keyUsages); switch (format) { @@ -235,7 +239,7 @@ export async function importKey( throw new DOMException('Invalid Ed25519 JWK', 'DataError'); } - const type = 'd' in jwk ? 'private' : 'public'; + const type = hasProperty(jwk, 'd') ? 'private' : 'public'; if (type === 'public' && !jwk.x) { throw new DOMException( diff --git a/packages/solana-wallet-snap/src/polyfills/index.ts b/packages/solana-wallet-snap/src/polyfills/index.ts index 1f6c79bab..7f8b81325 100644 --- a/packages/solana-wallet-snap/src/polyfills/index.ts +++ b/packages/solana-wallet-snap/src/polyfills/index.ts @@ -5,7 +5,7 @@ import { install as installQueueMicrotaskPolyfill } from './queue-microtask'; /** * Installs all polyfills. */ -export function installPolyfills() { +export function installPolyfills(): void { installDOMExceptionPolyfill(); installEd25519Polyfill(); installQueueMicrotaskPolyfill(); diff --git a/packages/solana-wallet-snap/src/polyfills/queue-microtask/index.ts b/packages/solana-wallet-snap/src/polyfills/queue-microtask/index.ts index c2afba0ce..3eac31f6c 100644 --- a/packages/solana-wallet-snap/src/polyfills/queue-microtask/index.ts +++ b/packages/solana-wallet-snap/src/polyfills/queue-microtask/index.ts @@ -1,14 +1 @@ -const queueMicrotask = async (callback: () => void) => - Promise.resolve().then(callback); - -/** - * Adds support for the window#queueMicrotask() function. - */ -export function install() { - Object.defineProperty(globalThis, 'queueMicrotask', { - value: queueMicrotask, - writable: true, - configurable: true, - enumerable: true, - }); -} +export { install } from './install'; diff --git a/packages/solana-wallet-snap/src/polyfills/queue-microtask/install.test.ts b/packages/solana-wallet-snap/src/polyfills/queue-microtask/install.test.ts new file mode 100644 index 000000000..914f03dae --- /dev/null +++ b/packages/solana-wallet-snap/src/polyfills/queue-microtask/install.test.ts @@ -0,0 +1,56 @@ +import { install } from '.'; + +const originalDescriptor = Object.getOwnPropertyDescriptor( + globalThis, + 'queueMicrotask', +); + +describe('install', () => { + afterEach(() => { + if (originalDescriptor) { + Object.defineProperty(globalThis, 'queueMicrotask', originalDescriptor); + } else { + Reflect.deleteProperty(globalThis, 'queueMicrotask'); + } + }); + + it('adds a global queueMicrotask function', () => { + install(); + + expect(typeof globalThis.queueMicrotask).toBe('function'); + }); + + it('defines the global as writable, configurable and enumerable', () => { + install(); + + expect( + Object.getOwnPropertyDescriptor(globalThis, 'queueMicrotask'), + ).toStrictEqual({ + value: expect.any(Function), + writable: true, + configurable: true, + enumerable: true, + }); + }); + + it('runs the callback asynchronously', async () => { + install(); + + const descriptor = Object.getOwnPropertyDescriptor( + globalThis, + 'queueMicrotask', + ); + + // The installed polyfill resolves before invoking the callback, so awaiting + // it is the documented way to wait for the callback to run. + const queueMicrotaskPolyfill = descriptor?.value as ( + callback: () => void, + ) => Promise; + + const callback = vi.fn(); + + await queueMicrotaskPolyfill(callback); + + expect(callback).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/solana-wallet-snap/src/polyfills/queue-microtask/install.ts b/packages/solana-wallet-snap/src/polyfills/queue-microtask/install.ts new file mode 100644 index 000000000..225ddfe4a --- /dev/null +++ b/packages/solana-wallet-snap/src/polyfills/queue-microtask/install.ts @@ -0,0 +1,16 @@ +const queueMicrotaskPolyfill = async (callback: () => void): Promise => { + await Promise.resolve(); + callback(); +}; + +/** + * Adds support for the window#queueMicrotask() function. + */ +export function install(): void { + Object.defineProperty(globalThis, 'queueMicrotask', { + value: queueMicrotaskPolyfill, + writable: true, + configurable: true, + enumerable: true, + }); +}