diff options
author | Sebastian <sebasjm@gmail.com> | 2022-01-16 17:47:43 -0300 |
---|---|---|
committer | Sebastian <sebasjm@gmail.com> | 2022-01-16 17:55:00 -0300 |
commit | f8ae2671c176e293843525c4fc5dd4a33653fd10 (patch) | |
tree | f0c6f3e7e8430f1ed52b6ef5be54d84c18939abb | |
parent | bf0cb6ab135c2a6d58a0684c17a565ed8422d5a4 (diff) |
de-duplicating imports and fixing another typescript minor issues
-rw-r--r-- | packages/taler-wallet-core/src/headless/helpers.ts | 21 | ||||
-rw-r--r-- | packages/taler-wallet-core/src/operations/deposits.ts | 16 | ||||
-rw-r--r-- | packages/taler-wallet-core/src/operations/pay.ts | 87 | ||||
-rw-r--r-- | packages/taler-wallet-core/src/util/coinSelection.ts | 3 | ||||
-rw-r--r-- | packages/taler-wallet-core/src/wallet.ts | 190 |
5 files changed, 116 insertions, 201 deletions
diff --git a/packages/taler-wallet-core/src/headless/helpers.ts b/packages/taler-wallet-core/src/headless/helpers.ts index d8616f716..120c4cd46 100644 --- a/packages/taler-wallet-core/src/headless/helpers.ts +++ b/packages/taler-wallet-core/src/headless/helpers.ts @@ -22,22 +22,20 @@ /** * Imports. */ +import type { IDBFactory } from "@gnu-taler/idb-bridge"; +// eslint-disable-next-line no-duplicate-imports import { - MemoryBackend, - BridgeIDBFactory, - shimIndexedDB, + BridgeIDBFactory, MemoryBackend, shimIndexedDB } from "@gnu-taler/idb-bridge"; +import { AccessStats } from "@gnu-taler/idb-bridge/src/MemoryBackend"; +import { Logger, WalletNotification } from "@gnu-taler/taler-util"; +import * as fs from "fs"; +import { NodeThreadCryptoWorkerFactory } from "../crypto/workers/nodeThreadWorker.js"; +import { SynchronousCryptoWorkerFactory } from "../crypto/workers/synchronousWorkerFactory.js"; import { openTalerDatabase } from "../db-utils.js"; import { HttpRequestLibrary } from "../util/http.js"; -import { NodeThreadCryptoWorkerFactory } from "../crypto/workers/nodeThreadWorker.js"; -import { NodeHttpLib } from "./NodeHttpLib.js"; -import { Logger } from "@gnu-taler/taler-util"; -import { SynchronousCryptoWorkerFactory } from "../crypto/workers/synchronousWorker.js"; -import type { IDBFactory } from "@gnu-taler/idb-bridge"; -import { WalletNotification } from "@gnu-taler/taler-util"; import { Wallet } from "../wallet.js"; -import * as fs from "fs"; -import { AccessStats } from "@gnu-taler/idb-bridge/src/MemoryBackend"; +import { NodeHttpLib } from "./NodeHttpLib.js"; const logger = new Logger("headless/helpers.ts"); @@ -165,6 +163,7 @@ export async function getDefaultNodeWallet2( try { // Try if we have worker threads available, fails in older node versions. const _r = "require"; + // eslint-disable-next-line no-unused-vars const worker_threads = module[_r]("worker_threads"); // require("worker_threads"); workerFactory = new NodeThreadCryptoWorkerFactory(); diff --git a/packages/taler-wallet-core/src/operations/deposits.ts b/packages/taler-wallet-core/src/operations/deposits.ts index 40a0af310..8a5b35732 100644 --- a/packages/taler-wallet-core/src/operations/deposits.ts +++ b/packages/taler-wallet-core/src/operations/deposits.ts @@ -27,9 +27,7 @@ import { CreateDepositGroupRequest, CreateDepositGroupResponse, DenomKeyType, - durationFromSpec, - GetFeeForDepositRequest, - getTimestampNow, + durationFromSpec, encodeCrock, GetFeeForDepositRequest, getRandomBytes, getTimestampNow, Logger, NotificationType, parsePaytoUri, @@ -40,15 +38,9 @@ import { timestampTruncateToSecond, TrackDepositGroupRequest, TrackDepositGroupResponse, - URL, + URL } from "@gnu-taler/taler-util"; import { InternalWalletState } from "../common.js"; -import { kdf } from "@gnu-taler/taler-util"; -import { - encodeCrock, - getRandomBytes, - stringToBytes, -} from "@gnu-taler/taler-util"; import { DepositGroupRecord, OperationStatus } from "../db.js"; import { guardOperationException } from "../errors.js"; import { PayCoinSelection, selectPayCoins } from "../util/coinSelection.js"; @@ -62,7 +54,7 @@ import { getCandidatePayCoins, getTotalPaymentCost, hashWire, - hashWireLegacy, + hashWireLegacy } from "./pay.js"; import { getTotalRefreshCost } from "./refresh.js"; @@ -168,7 +160,7 @@ export async function processDepositGroup( async function processDepositGroupImpl( ws: InternalWalletState, depositGroupId: string, - forceNow: boolean = false, + forceNow = false, ): Promise<void> { if (forceNow) { await resetDepositGroupRetry(ws, depositGroupId); diff --git a/packages/taler-wallet-core/src/operations/pay.ts b/packages/taler-wallet-core/src/operations/pay.ts index 479ab5e1c..8f0727c8b 100644 --- a/packages/taler-wallet-core/src/operations/pay.ts +++ b/packages/taler-wallet-core/src/operations/pay.ts @@ -26,58 +26,14 @@ */ import { AmountJson, - Amounts, - timestampIsBetween, - getTimestampNow, - isTimestampExpired, - Timestamp, - RefreshReason, - CoinDepositPermission, - NotificationType, - TalerErrorDetails, - Duration, + Amounts, codecForContractTerms, codecForMerchantPayResponse, codecForProposal, CoinDepositPermission, ConfirmPayResult, + ConfirmPayResultType, ContractTerms, decodeCrock, DenomKeyType, Duration, durationMax, durationMin, - durationMul, - ContractTerms, - codecForProposal, - TalerErrorCode, - codecForContractTerms, - timestampAddDuration, - ConfirmPayResult, - ConfirmPayResultType, - codecForMerchantPayResponse, - PreparePayResult, - PreparePayResultType, - parsePayUri, - Logger, - URL, - getDurationRemaining, - HttpStatusCode, - DenomKeyType, - kdf, - stringToBytes, - decodeCrock, + durationMul, encodeCrock, getDurationRemaining, getRandomBytes, getTimestampNow, HttpStatusCode, isTimestampExpired, j2s, kdf, Logger, NotificationType, parsePayUri, PreparePayResult, + PreparePayResultType, RefreshReason, stringToBytes, TalerErrorCode, TalerErrorDetails, Timestamp, timestampAddDuration, URL } from "@gnu-taler/taler-util"; -import { encodeCrock, getRandomBytes } from "@gnu-taler/taler-util"; -import { - PayCoinSelection, - CoinCandidateSelection, - AvailableCoinInfo, - selectPayCoins, - PreviousPayCoins, -} from "../util/coinSelection.js"; -import { j2s } from "@gnu-taler/taler-util"; -import { - initRetryInfo, - updateRetryInfoTimeout, - getRetryDuration, -} from "../util/retries.js"; -import { getTotalRefreshCost, createRefreshGroup } from "./refresh.js"; -import { InternalWalletState, EXCHANGE_COINS_LOCK } from "../common.js"; -import { ContractTermsUtil } from "../util/contractTerms.js"; -import { getExchangeDetails } from "./exchanges.js"; -import { GetReadWriteAccess } from "../util/query.js"; +import { EXCHANGE_COINS_LOCK, InternalWalletState } from "../common.js"; import { AbortStatus, AllowedAuditorInfo, @@ -90,22 +46,33 @@ import { ProposalStatus, PurchaseRecord, WalletContractData, - WalletStoresV1, + WalletStoresV1 } from "../db.js"; import { + guardOperationException, + makeErrorDetails, + OperationFailedAndReportedError, + OperationFailedError +} from "../errors.js"; +import { + AvailableCoinInfo, CoinCandidateSelection, PayCoinSelection, PreviousPayCoins, selectPayCoins +} from "../util/coinSelection.js"; +import { ContractTermsUtil } from "../util/contractTerms.js"; +import { getHttpResponseErrorDetails, readSuccessResponseJsonOrErrorCode, readSuccessResponseJsonOrThrow, readTalerErrorResponse, readUnexpectedResponseDetails, - throwUnexpectedRequestError, + throwUnexpectedRequestError } from "../util/http.js"; +import { GetReadWriteAccess } from "../util/query.js"; import { - guardOperationException, - makeErrorDetails, - OperationFailedAndReportedError, - OperationFailedError, -} from "../errors.js"; + getRetryDuration, initRetryInfo, + updateRetryInfoTimeout +} from "../util/retries.js"; +import { getExchangeDetails } from "./exchanges.js"; +import { createRefreshGroup, getTotalRefreshCost } from "./refresh.js"; /** * Logger. @@ -368,7 +335,7 @@ export async function applyCoinSpend( }>, coinSelection: PayCoinSelection, allocationId: string, -) { +): Promise<void> { logger.info(`applying coin spend ${j2s(coinSelection)}`); for (let i = 0; i < coinSelection.coinPubs.length; i++) { const coin = await tx.coins.get(coinSelection.coinPubs[i]); @@ -530,8 +497,7 @@ async function incrementPurchasePayRetry( pr.payRetryInfo.retryCounter++; updateRetryInfoTimeout(pr.payRetryInfo); logger.trace( - `retrying pay in ${ - getDurationRemaining(pr.payRetryInfo.nextRetry).d_ms + `retrying pay in ${getDurationRemaining(pr.payRetryInfo.nextRetry).d_ms } ms`, ); pr.lastPayError = err; @@ -1105,7 +1071,7 @@ async function unblockBackup( await ws.db .mktx((x) => ({ backupProviders: x.backupProviders })) .runReadWrite(async (tx) => { - const bp = await tx.backupProviders.indexes.byPaymentProposalId + await tx.backupProviders.indexes.byPaymentProposalId .iter(proposalId) .forEachAsync(async (bp) => { if (bp.state.tag === BackupProviderStateTag.Retrying) { @@ -1143,6 +1109,7 @@ async function submitPay( logger.trace("paying with session ID", sessionId); + //FIXME: not used, does it expect a side effect? const merchantInfo = await ws.merchantOps.getMerchantInfo( ws, purchase.download.contractData.merchantBaseUrl, diff --git a/packages/taler-wallet-core/src/util/coinSelection.ts b/packages/taler-wallet-core/src/util/coinSelection.ts index bfc481eaf..9a122a8fa 100644 --- a/packages/taler-wallet-core/src/util/coinSelection.ts +++ b/packages/taler-wallet-core/src/util/coinSelection.ts @@ -27,9 +27,8 @@ import { AmountJson, Amounts, DenominationPubKey, - DenomKeyType, + DenomKeyType, Logger, strcmp } from "@gnu-taler/taler-util"; -import { strcmp, Logger } from "@gnu-taler/taler-util"; const logger = new Logger("coinSelection.ts"); diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts index 347a1eb03..7bbbb1ff7 100644 --- a/packages/taler-wallet-core/src/wallet.ts +++ b/packages/taler-wallet-core/src/wallet.ts @@ -23,31 +23,51 @@ * Imports. */ import { - BalancesResponse, - codecForAny, - codecForDeleteTransactionRequest, - codecForRetryTransactionRequest, - codecForSetWalletDeviceIdRequest, - codecForGetExchangeWithdrawalInfo, - durationFromSpec, - durationMin, - getDurationRemaining, - isTimestampExpired, - j2s, - TalerErrorCode, + AcceptManualWithdrawalResult, + AcceptWithdrawalResponse, AmountJson, Amounts, BalancesResponse, codecForAbortPayWithRefundRequest, + codecForAcceptBankIntegratedWithdrawalRequest, + codecForAcceptExchangeTosRequest, + codecForAcceptManualWithdrawalRequet, + codecForAcceptTipRequest, + codecForAddExchangeRequest, codecForAny, codecForApplyRefundRequest, + codecForConfirmPayRequest, + codecForCreateDepositGroupRequest, codecForDeleteTransactionRequest, codecForForceRefreshRequest, + codecForGetExchangeTosRequest, codecForGetExchangeWithdrawalInfo, codecForGetFeeForDeposit, codecForGetWithdrawalDetailsForAmountRequest, + codecForGetWithdrawalDetailsForUri, codecForImportDbRequest, codecForIntegrationTestArgs, codecForListKnownBankAccounts, codecForPreparePayRequest, + codecForPrepareTipRequest, codecForRetryTransactionRequest, codecForSetCoinSuspendedRequest, codecForSetWalletDeviceIdRequest, codecForTestPayArgs, + codecForTrackDepositGroupRequest, codecForTransactionsRequest, codecForWithdrawFakebankRequest, codecForWithdrawTestBalance, CoinDumpJson, CoreApiResponse, durationFromSpec, + durationMin, ExchangeListItem, + ExchangesListRespose, getDurationRemaining, GetExchangeTosResult, isTimestampExpired, + j2s, KnownBankAccounts, Logger, ManualWithdrawalDetails, NotificationType, parsePaytoUri, PaytoUri, RefreshReason, TalerErrorCode, Timestamp, - timestampMin, - WalletNotification, - codecForWithdrawFakebankRequest, - URL, - parsePaytoUri, - KnownBankAccounts, - PaytoUri, - codecForGetFeeForDeposit, - codecForListKnownBankAccounts, - codecForImportDbRequest, + timestampMin, URL, WalletNotification } from "@gnu-taler/taler-util"; import { + DenomInfo, + ExchangeOperations, + InternalWalletState, + MerchantInfo, + MerchantOperations, + NotificationListener, + RecoupOperations, + ReserveOperations +} from "./common.js"; +import { CryptoApi, CryptoWorkerFactory } from "./crypto/workers/cryptoApi.js"; +import { + AuditorTrustRecord, + CoinSourceType, + exportDb, + importDb, + ReserveRecordStatus, + WalletStoresV1 +} from "./db.js"; +import { + makeErrorDetails, + OperationFailedAndReportedError, + OperationFailedError +} from "./errors.js"; +import { exportBackup } from "./operations/backup/export.js"; +import { addBackupProvider, codecForAddBackupProviderRequest, codecForRemoveBackupProvider, @@ -57,142 +77,80 @@ import { loadBackupRecovery, processBackupForProvider, removeBackupProvider, - runBackupCycle, + runBackupCycle } from "./operations/backup/index.js"; -import { exportBackup } from "./operations/backup/export.js"; +import { setWalletDeviceId } from "./operations/backup/state.js"; import { getBalances } from "./operations/balance.js"; import { createDepositGroup, getFeeForDeposit, processDepositGroup, - trackDepositGroup, + trackDepositGroup } from "./operations/deposits.js"; import { - makeErrorDetails, - OperationFailedAndReportedError, - OperationFailedError, -} from "./errors.js"; -import { acceptExchangeTermsOfService, getExchangeDetails, getExchangeTrust, - updateExchangeFromUrl, + updateExchangeFromUrl } from "./operations/exchanges.js"; +import { getMerchantInfo } from "./operations/merchants.js"; import { confirmPay, preparePayForUri, processDownloadProposal, - processPurchasePay, + processPurchasePay } from "./operations/pay.js"; import { getPendingOperations } from "./operations/pending.js"; import { createRecoupGroup, processRecoupGroup } from "./operations/recoup.js"; import { autoRefresh, createRefreshGroup, - processRefreshGroup, + processRefreshGroup } from "./operations/refresh.js"; import { abortFailedPayWithRefund, applyRefund, - processPurchaseQueryRefund, + processPurchaseQueryRefund } from "./operations/refund.js"; import { createReserve, createTalerWithdrawReserve, getFundingPaytoUris, - processReserve, + processReserve } from "./operations/reserves.js"; import { - DenomInfo, - ExchangeOperations, - InternalWalletState, - MerchantInfo, - MerchantOperations, - NotificationListener, - RecoupOperations, - ReserveOperations, -} from "./common.js"; -import { runIntegrationTest, testPay, - withdrawTestBalance, + withdrawTestBalance } from "./operations/testing.js"; import { acceptTip, prepareTip, processTip } from "./operations/tip.js"; import { deleteTransaction, getTransactions, - retryTransaction, + retryTransaction } from "./operations/transactions.js"; import { getExchangeWithdrawalInfo, getWithdrawalDetailsForUri, - processWithdrawGroup, + processWithdrawGroup } from "./operations/withdraw.js"; import { - AuditorTrustRecord, - CoinSourceType, - exportDb, - importDb, - ReserveRecordStatus, - WalletStoresV1, -} from "./db.js"; -import { NotificationType } from "@gnu-taler/taler-util"; -import { - PendingTaskInfo, - PendingOperationsResponse, - PendingTaskType, + PendingOperationsResponse, PendingTaskInfo, PendingTaskType } from "./pending-types.js"; -import { CoinDumpJson } from "@gnu-taler/taler-util"; -import { codecForTransactionsRequest } from "@gnu-taler/taler-util"; -import { - AcceptManualWithdrawalResult, - AcceptWithdrawalResponse, - codecForAbortPayWithRefundRequest, - codecForAcceptBankIntegratedWithdrawalRequest, - codecForAcceptExchangeTosRequest, - codecForAcceptManualWithdrawalRequet, - codecForAcceptTipRequest, - codecForAddExchangeRequest, - codecForApplyRefundRequest, - codecForConfirmPayRequest, - codecForCreateDepositGroupRequest, - codecForForceRefreshRequest, - codecForGetExchangeTosRequest, - codecForGetWithdrawalDetailsForAmountRequest, - codecForGetWithdrawalDetailsForUri, - codecForIntegrationTestArgs, - codecForPreparePayRequest, - codecForPrepareTipRequest, - codecForSetCoinSuspendedRequest, - codecForTestPayArgs, - codecForTrackDepositGroupRequest, - codecForWithdrawTestBalance, - CoreApiResponse, - ExchangeListItem, - ExchangesListRespose, - GetExchangeTosResult, - ManualWithdrawalDetails, - RefreshReason, -} from "@gnu-taler/taler-util"; -import { AmountJson, Amounts } from "@gnu-taler/taler-util"; import { assertUnreachable } from "./util/assertUnreachable.js"; -import { Logger } from "@gnu-taler/taler-util"; -import { setWalletDeviceId } from "./operations/backup/state.js"; -import { WalletCoreApiClient } from "./wallet-api-types.js"; import { AsyncOpMemoMap, AsyncOpMemoSingle } from "./util/asyncMemo.js"; -import { CryptoApi, CryptoWorkerFactory } from "./crypto/workers/cryptoApi.js"; -import { TimerGroup } from "./util/timer.js"; +import { + HttpRequestLibrary, + readSuccessResponseJsonOrThrow +} from "./util/http.js"; import { AsyncCondition, OpenedPromise, - openPromise, + openPromise } from "./util/promiseUtils.js"; import { DbAccess, GetReadWriteAccess } from "./util/query.js"; -import { - HttpRequestLibrary, - readSuccessResponseJsonOrThrow, -} from "./util/http.js"; -import { getMerchantInfo } from "./operations/merchants.js"; +import { TimerGroup } from "./util/timer.js"; +import { WalletCoreApiClient } from "./wallet-api-types.js"; const builtinAuditors: AuditorTrustRecord[] = [ { @@ -1047,7 +1005,7 @@ export async function handleCoreApiRequest( try { logger.error("Caught unexpected exception:"); logger.error(e.stack); - } catch (e) {} + } catch (e) { } return { type: "error", operation, @@ -1077,7 +1035,7 @@ export class Wallet { this.ws = new InternalWalletStateImpl(db, http, cryptoWorkerFactory); } - get client() { + get client(): WalletCoreApiClient { return this._client; } @@ -1085,7 +1043,7 @@ export class Wallet { * Trust the exchange, do not validate signatures. * Only used to benchmark the exchange. */ - setInsecureTrustExchange() { + setInsecureTrustExchange(): void { this.ws.insecureTrustExchange = true; } @@ -1107,11 +1065,11 @@ export class Wallet { this.ws.stop(); } - runPending(forceNow: boolean = false) { + runPending(forceNow = false): Promise<void> { return runPending(this.ws, forceNow); } - runTaskLoop(opts?: RetryLoopOpts) { + runTaskLoop(opts?: RetryLoopOpts): Promise<void> { return runTaskLoop(this.ws, opts); } @@ -1142,7 +1100,7 @@ class InternalWalletStateImpl implements InternalWalletState { merchantInfoCache: Record<string, MerchantInfo> = {}; - insecureTrustExchange: boolean = false; + insecureTrustExchange = false; timerGroup: TimerGroup = new TimerGroup(); latch = new AsyncCondition(); @@ -1150,7 +1108,7 @@ class InternalWalletStateImpl implements InternalWalletState { listeners: NotificationListener[] = []; - initCalled: boolean = false; + initCalled = false; exchangeOps: ExchangeOperations = { getExchangeDetails, @@ -1159,16 +1117,16 @@ class InternalWalletStateImpl implements InternalWalletState { }; recoupOps: RecoupOperations = { - createRecoupGroup: createRecoupGroup, - processRecoupGroup: processRecoupGroup, + createRecoupGroup, + processRecoupGroup, }; merchantOps: MerchantOperations = { - getMerchantInfo: getMerchantInfo, + getMerchantInfo, }; reserveOps: ReserveOperations = { - processReserve: processReserve, + processReserve, }; // FIXME: Use an LRU cache here. @@ -1253,7 +1211,7 @@ class InternalWalletStateImpl implements InternalWalletState { * Run an async function after acquiring a list of locks, identified * by string tokens. */ - async runSequentialized<T>(tokens: string[], f: () => Promise<T>) { + async runSequentialized<T>(tokens: string[], f: () => Promise<T>): Promise<T> { // Make sure locks are always acquired in the same order tokens = [...tokens].sort(); |