From f9ac31c1c22a7e1b1fa90570b861a39eb6d96c25 Mon Sep 17 00:00:00 2001 From: William Swanson Date: Tue, 5 Dec 2023 10:25:59 -0800 Subject: [PATCH] Allow some wallet creations to fail --- src/core/account/account-api.ts | 51 ++++++++++++++++++++++++--------- src/types/types.ts | 7 ++++- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/src/core/account/account-api.ts b/src/core/account/account-api.ts index 8e4475feb..2179c098e 100644 --- a/src/core/account/account-api.ts +++ b/src/core/account/account-api.ts @@ -20,10 +20,12 @@ import { EdgePendingVoucher, EdgePluginMap, EdgeRateCache, + EdgeResult, EdgeSwapConfig, EdgeSwapQuote, EdgeSwapRequest, EdgeSwapRequestOptions, + EdgeWalletInfo, EdgeWalletInfoFull, EdgeWalletStates } from '../../types/types' @@ -506,24 +508,38 @@ export function makeAccountApi(ai: ApiInput, accountId: string): EdgeAccount { async createCurrencyWallets( createWallets: EdgeCreateCurrencyWallet[] - ): Promise { + ): Promise>> { const { login, loginTree } = accountState() - const walletInfos = await Promise.all( - createWallets.map(async opts => { - return await makeCurrencyWalletKeys(ai, opts.walletType, opts) - }) + // Create the keys: + const keys = await Promise.all( + createWallets.map( + async opts => + await catchResult(makeCurrencyWalletKeys(ai, opts.walletType, opts)) + ) ) + + // Store the keys on the server: + const walletInfos: EdgeWalletInfo[] = [] + for (const result of keys) { + if (result.ok) walletInfos.push(result.result) + } await applyKit(ai, loginTree, makeKeysKit(ai, login, walletInfos)) + + // Set up options: return await Promise.all( - walletInfos.map(async (info, i) => { - return await finishWalletCreation( - ai, - accountId, - info.id, - createWallets[i] - ) - }) + keys.map(async (info, i) => + info.ok + ? await catchResult( + finishWalletCreation( + ai, + accountId, + info.result.id, + createWallets[i] + ) + ) + : info + ) ) }, @@ -681,3 +697,12 @@ function getRawPrivateKey( } return info } + +async function catchResult(promise: Promise): Promise> { + try { + const result = await promise + return { ok: true, result } + } catch (error) { + return { ok: false, error } + } +} diff --git a/src/types/types.ts b/src/types/types.ts index c3072e1fd..901b8b79c 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -21,6 +21,11 @@ export interface JsonObject { [name: string]: any // TODO: this needs to become `unknown` } +/** When we return errors explicitly instead of throwing them */ +export type EdgeResult = + | { ok: true; result: T } + | { ok: false; error: unknown } + /** A collection of unknown extra methods exposed by a plugin. */ export interface EdgeOtherMethods { readonly [name: string]: any @@ -1580,7 +1585,7 @@ export interface EdgeAccount { ) => Promise readonly createCurrencyWallets: ( createWallets: EdgeCreateCurrencyWallet[] - ) => Promise + ) => Promise>> readonly waitForCurrencyWallet: ( walletId: string ) => Promise