Skip to content

Commit

Permalink
chore: add snap caching
Browse files Browse the repository at this point in the history
making multiple calls to snaps can cause an internal 429 too many requests as snap requests are queued.
This adds simple in-mem caching to prevent calling the snap with the same values
  • Loading branch information
Prithpal-Sooriya committed Jul 17, 2024
1 parent 2d4a255 commit 3dee719
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -311,28 +311,48 @@ export default class AuthenticationController extends BaseController<
return THIRTY_MIN_MS > diffMs;
}

#_snapPublicKeyCache: string | undefined;

/**
* Returns the auth snap public key.
*
* @returns The snap public key.
*/
#snapGetPublicKey(): Promise<string> {
return this.messagingSystem.call(
async #snapGetPublicKey(): Promise<string> {
if (this.#_snapPublicKeyCache) {
return this.#_snapPublicKeyCache;
}

const result = (await this.messagingSystem.call(
'SnapController:handleRequest',
createSnapPublicKeyRequest(),
) as Promise<string>;
)) as string;

this.#_snapPublicKeyCache = result;

return result;
}

#_snapSignMessageCache: Record<`metamask:${string}`, string> = {};

/**
* Signs a specific message using an underlying auth snap.
*
* @param message - A specific tagged message to sign.
* @returns A Signature created by the snap.
*/
#snapSignMessage(message: `metamask:${string}`): Promise<string> {
return this.messagingSystem.call(
async #snapSignMessage(message: `metamask:${string}`): Promise<string> {
if (this.#_snapSignMessageCache[message]) {
return this.#_snapSignMessageCache[message];
}

const result = (await this.messagingSystem.call(
'SnapController:handleRequest',
createSnapSignMessageRequest(message),
) as Promise<string>;
)) as string;

this.#_snapSignMessageCache[message] = result;

return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -373,17 +373,27 @@ export default class UserStorageController extends BaseController<
return storageKey;
}

#_snapSignMessageCache: Record<`metamask:${string}`, string> = {};

/**
* Signs a specific message using an underlying auth snap.
*
* @param message - A specific tagged message to sign.
* @returns A Signature created by the snap.
*/
#snapSignMessage(message: `metamask:${string}`): Promise<string> {
return this.messagingSystem.call(
async #snapSignMessage(message: `metamask:${string}`): Promise<string> {
if (this.#_snapSignMessageCache[message]) {
return this.#_snapSignMessageCache[message];
}

const result = (await this.messagingSystem.call(
'SnapController:handleRequest',
createSnapSignMessageRequest(message),
) as Promise<string>;
)) as string;

this.#_snapSignMessageCache[message] = result;

return result;
}

#setIsProfileSyncingUpdateLoading(
Expand Down

0 comments on commit 3dee719

Please sign in to comment.