From ee0a86b5b772c4f39201e8946968eb5e54d6e05e Mon Sep 17 00:00:00 2001 From: yanguoyu <841185308@qq.com> Date: Fri, 27 Oct 2023 14:13:25 +0800 Subject: [PATCH] feat: Split full node and light client db file. --- .../sync/indexer-cache-service.ts | 3 +- .../sync/tx-address-finder.ts | 2 +- .../block-sync-renderer/tx-status-listener.ts | 2 +- .../src/controllers/app/index.ts | 4 ++ .../src/database/chain/connection.ts | 17 ++++++ .../chain/entities/multisig-config.ts | 14 +++++ .../neuron-wallet/src/database/chain/index.ts | 2 +- .../src/database/chain/ormconfig.ts | 56 +++++++++++++++--- .../chain/subscriber/address-subscriber.ts | 10 ++++ .../subscriber/asset-account-subscriber.ts | 26 +++++++++ .../subscriber/multisig-config-subscriber.ts | 19 ++++++ .../subscriber/sudt-token-info-subscriber.ts | 32 ++++++++++ .../subscriber/tx-description-subscriber.ts | 10 ++++ .../subscriber/user-setting-subscriber.ts | 58 +++++++++++++++++++ .../src/models/synced-block-number.ts | 2 +- .../neuron-wallet/src/services/addresses.ts | 2 +- .../src/services/anyone-can-pay.ts | 2 +- .../src/services/asset-account-service.ts | 3 +- .../src/services/cell-local-info.ts | 2 +- packages/neuron-wallet/src/services/cells.ts | 3 +- .../neuron-wallet/src/services/multisig.ts | 3 +- .../src/services/sudt-token-info.ts | 3 +- .../src/services/sync-progress.ts | 3 +- .../src/services/tx/failed-transaction.ts | 3 +- .../services/tx/transaction-description.ts | 2 +- .../src/services/tx/transaction-persistor.ts | 3 +- .../src/services/tx/transaction-service.ts | 2 +- .../neuron-wallet/src/services/wallets.ts | 3 +- .../index/createBlockSyncTask.test.ts | 5 +- .../index/killBlockSyncTask.test.ts | 4 +- .../index/queryIndexer.test.ts | 8 ++- .../indexer-cache-service.intg.test.ts | 7 +-- .../tx-status-listener.intg.test.ts | 7 +-- .../tests/controllers/export-debug.test.ts | 2 + .../tests/controllers/multisig.test.ts | 4 ++ .../models/keys/hd-public-key-info.test.ts | 4 ++ .../models/synced-block-number.intg.test.ts | 12 ++-- .../tests/services/address.test.ts | 9 ++- .../tests/services/anyone-can-pay.test.ts | 3 +- .../services/asset-account-service.test.ts | 6 +- .../tests/services/cell-local-info.test.ts | 3 +- .../tests/services/cells.test.ts | 5 +- .../tests/services/multisig.test.ts | 14 ++++- .../tests/services/sudt-token-info.test.ts | 3 +- .../tests/services/transactions.test.ts | 5 +- .../services/tx/transaction-generator.test.ts | 5 +- .../services/tx/transaction-persistor.test.ts | 5 +- .../services/tx/transaction-service.test.ts | 3 +- .../tx/transaction.description.intg.test.ts | 7 +-- .../tests/services/wallets.test.ts | 16 ++--- .../tests/setupAndTeardown/index.ts | 12 ++-- .../tests/utils/export-history/index.test.ts | 3 +- 52 files changed, 348 insertions(+), 95 deletions(-) create mode 100644 packages/neuron-wallet/src/database/chain/connection.ts create mode 100644 packages/neuron-wallet/src/database/chain/subscriber/address-subscriber.ts create mode 100644 packages/neuron-wallet/src/database/chain/subscriber/asset-account-subscriber.ts create mode 100644 packages/neuron-wallet/src/database/chain/subscriber/multisig-config-subscriber.ts create mode 100644 packages/neuron-wallet/src/database/chain/subscriber/sudt-token-info-subscriber.ts create mode 100644 packages/neuron-wallet/src/database/chain/subscriber/tx-description-subscriber.ts create mode 100644 packages/neuron-wallet/src/database/chain/subscriber/user-setting-subscriber.ts diff --git a/packages/neuron-wallet/src/block-sync-renderer/sync/indexer-cache-service.ts b/packages/neuron-wallet/src/block-sync-renderer/sync/indexer-cache-service.ts index 4775f70a67..f223174e80 100644 --- a/packages/neuron-wallet/src/block-sync-renderer/sync/indexer-cache-service.ts +++ b/packages/neuron-wallet/src/block-sync-renderer/sync/indexer-cache-service.ts @@ -1,10 +1,11 @@ -import { In, getConnection } from 'typeorm' +import { In } from 'typeorm' import { queue } from 'async' import AddressMeta from '../../database/address/meta' import IndexerTxHashCache from '../../database/chain/entities/indexer-tx-hash-cache' import RpcService from '../../services/rpc-service' import TransactionWithStatus from '../../models/chain/transaction-with-status' import SyncInfoEntity from '../../database/chain/entities/sync-info' +import { getConnection } from '../../database/chain/connection' import { TransactionCollector, CellCollector, Indexer as CkbIndexer } from '@ckb-lumos/ckb-indexer' export default class IndexerCacheService { diff --git a/packages/neuron-wallet/src/block-sync-renderer/sync/tx-address-finder.ts b/packages/neuron-wallet/src/block-sync-renderer/sync/tx-address-finder.ts index d857dbee1e..f8d1a9d295 100644 --- a/packages/neuron-wallet/src/block-sync-renderer/sync/tx-address-finder.ts +++ b/packages/neuron-wallet/src/block-sync-renderer/sync/tx-address-finder.ts @@ -1,4 +1,3 @@ -import { getConnection } from 'typeorm' import { scriptToAddress } from '../../utils/scriptAndAddress' import OutputEntity from '../../database/chain/entities/output' import NetworksService from '../../services/networks' @@ -6,6 +5,7 @@ import Output from '../../models/chain/output' import OutPoint from '../../models/chain/out-point' import Transaction from '../../models/chain/transaction' import SystemScriptInfo from '../../models/system-script-info' +import { getConnection } from '../../database/chain/connection' export interface AnyoneCanPayInfo { tokenID: string diff --git a/packages/neuron-wallet/src/block-sync-renderer/tx-status-listener.ts b/packages/neuron-wallet/src/block-sync-renderer/tx-status-listener.ts index 039c2d1d68..1fbba05c50 100644 --- a/packages/neuron-wallet/src/block-sync-renderer/tx-status-listener.ts +++ b/packages/neuron-wallet/src/block-sync-renderer/tx-status-listener.ts @@ -1,4 +1,3 @@ -import { getConnection } from 'typeorm' import { CONNECTION_NOT_FOUND_NAME } from '../database/chain/ormconfig' import { FailedTransaction, TransactionPersistor } from '../services/tx' import RpcService from '../services/rpc-service' @@ -6,6 +5,7 @@ import NetworksService from '../services/networks' import Transaction, { TransactionStatus } from '../models/chain/transaction' import TransactionWithStatus from '../models/chain/transaction-with-status' import logger from '../utils/logger' +import { getConnection } from '../database/chain/connection' import { interval } from 'rxjs' type TransactionDetail = { diff --git a/packages/neuron-wallet/src/controllers/app/index.ts b/packages/neuron-wallet/src/controllers/app/index.ts index 888e087d19..07f9d8dba7 100644 --- a/packages/neuron-wallet/src/controllers/app/index.ts +++ b/packages/neuron-wallet/src/controllers/app/index.ts @@ -15,6 +15,8 @@ import SyncApiController from '../../controllers/sync-api' import { SETTINGS_WINDOW_TITLE } from '../../utils/const' import { stopCkbNode } from '../../services/ckb-runner' import { CKBLightRunner } from '../../services/light-runner' +import { migrateDBFile } from '../../database/chain/ormconfig' +import { MAINNET_GENESIS_HASH, TESTNET_GENESIS_HASH } from '../../models/network' const app = electronApp @@ -37,6 +39,8 @@ export default class AppController { } public start = async () => { + migrateDBFile(TESTNET_GENESIS_HASH) + migrateDBFile(MAINNET_GENESIS_HASH) registerListeners() if (!env.isTestMode) { diff --git a/packages/neuron-wallet/src/database/chain/connection.ts b/packages/neuron-wallet/src/database/chain/connection.ts new file mode 100644 index 0000000000..a65452b356 --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/connection.ts @@ -0,0 +1,17 @@ +import { getConnection as originGetConnection } from 'typeorm' +import { NetworkType } from '../../models/network' +import NetworksService from '../../services/networks' + +export type ConnectionName = 'light' | 'full' + +export function getCurrentConnectionName(): ConnectionName { + return NetworksService.getInstance().getCurrent()?.type === NetworkType.Light ? 'light' : 'full' +} + +export function getConnection(connectionName: ConnectionName = getCurrentConnectionName()) { + const connection = originGetConnection(connectionName) + if (!connection) { + throw new Error(`The connection ${connectionName} should be initialized before use`) + } + return connection +} diff --git a/packages/neuron-wallet/src/database/chain/entities/multisig-config.ts b/packages/neuron-wallet/src/database/chain/entities/multisig-config.ts index 30128092ae..2c0b2d8f6a 100644 --- a/packages/neuron-wallet/src/database/chain/entities/multisig-config.ts +++ b/packages/neuron-wallet/src/database/chain/entities/multisig-config.ts @@ -43,6 +43,20 @@ export default class MultisigConfig { return multisigConfig } + public cloneIgnoreBlockNumber(): MultisigConfig { + const multisigConfig = new MultisigConfig() + + multisigConfig.walletId = this.walletId + multisigConfig.r = this.r + multisigConfig.m = this.m + multisigConfig.n = this.n + multisigConfig.blake160s = this.blake160s + if (this.alias) { + multisigConfig.alias = this.alias + } + return multisigConfig + } + @AfterInsert() emitInsert() { this.changed('AfterInsert') diff --git a/packages/neuron-wallet/src/database/chain/index.ts b/packages/neuron-wallet/src/database/chain/index.ts index bfa5492391..fcb13996e9 100644 --- a/packages/neuron-wallet/src/database/chain/index.ts +++ b/packages/neuron-wallet/src/database/chain/index.ts @@ -1,4 +1,3 @@ -import { getConnection } from 'typeorm' import MultisigOutputChangedSubject from '../../models/subjects/multisig-output-db-changed-subject' import SyncProgressService from '../../services/sync-progress' import InputEntity from './entities/input' @@ -9,6 +8,7 @@ import IndexerTxHashCache from './entities/indexer-tx-hash-cache' import MultisigOutput from './entities/multisig-output' import SyncProgress from './entities/sync-progress' import TxLock from './entities/tx-lock' +import { getConnection } from '../../database/chain/connection' /* * Clean local sqlite storage diff --git a/packages/neuron-wallet/src/database/chain/ormconfig.ts b/packages/neuron-wallet/src/database/chain/ormconfig.ts index d87ac1cbd0..36c136f5af 100644 --- a/packages/neuron-wallet/src/database/chain/ormconfig.ts +++ b/packages/neuron-wallet/src/database/chain/ormconfig.ts @@ -1,6 +1,7 @@ import { createConnection, getConnectionOptions, getConnection } from 'typeorm' import { SqliteConnectionOptions } from 'typeorm/driver/sqlite/SqliteConnectionOptions' import path from 'path' +import fs from 'fs' import logger from '../../utils/logger' import env from '../../env' @@ -58,23 +59,33 @@ import { ResetSyncProgressPrimaryKey1690361215400 } from './migrations/169036121 import { TxLockAddArgs1694746034975 } from './migrations/1694746034975-TxLockAddArgs' import { IndexerTxHashCacheRemoveField1701234043431 } from './migrations/1701234043431-IndexerTxHashCacheRemoveField' import { CreateCellLocalInfo1701234043432 } from './migrations/1701234043432-CreateCellLocalInfo' +import { ConnectionName } from './connection' +import AddressSubscribe from './subscriber/address-subscriber' +import MultisigConfigSubscribe from './subscriber/multisig-config-subscriber' +import TxDescriptionSubscribe from './subscriber/tx-description-subscriber' +import SudtTokenInfoSubscribe from './subscriber/sudt-token-info-subscriber' +import AssetAccountSubscribe from './subscriber/asset-account-subscriber' export const CONNECTION_NOT_FOUND_NAME = 'ConnectionNotFoundError' -const dbPath = (name: string): string => { - const filename = `cell-${name}.sqlite` +const dbPath = (name: string, connectionName: string): string => { + const filename = `${connectionName}-${name}.sqlite` return path.join(env.fileBasePath, 'cells', filename) } -const connectOptions = async (genesisBlockHash: string): Promise => { +const connectOptions = async ( + genesisBlockHash: string, + connectionName: ConnectionName +): Promise => { const connectionOptions = await getConnectionOptions() - const database = env.isTestMode ? ':memory:' : dbPath(genesisBlockHash) + const database = env.isTestMode ? ':memory:' : dbPath(genesisBlockHash, connectionName) const logging: boolean | ('query' | 'schema' | 'error' | 'warn' | 'info' | 'log' | 'migration')[] = ['warn', 'error'] // (env.isDevMode) ? ['warn', 'error', 'log', 'info', 'schema', 'migration'] : ['warn', 'error'] return { ...connectionOptions, + name: connectionName, type: 'sqlite', database, entities: [ @@ -133,28 +144,55 @@ const connectOptions = async (genesisBlockHash: string): Promise { +const initConnectionWithType = async (genesisBlockHash: string, connectionName: ConnectionName) => { // try to close connection, if not exist, will throw ConnectionNotFoundError when call getConnection() try { - await getConnection().close() + await getConnection(connectionName).close() } catch (err) { // do nothing } - const connectionOptions = await connectOptions(genesisBlockHash) + const connectionOptions = await connectOptions(genesisBlockHash, connectionName) try { await createConnection(connectionOptions) - await getConnection().manager.query(`PRAGMA busy_timeout = 3000;`) - await getConnection().manager.query(`PRAGMA temp_store = MEMORY;`) + await getConnection(connectionName).manager.query(`PRAGMA busy_timeout = 3000;`) + await getConnection(connectionName).manager.query(`PRAGMA temp_store = MEMORY;`) } catch (err) { logger.error(err.message) } } +export async function initConnection(genesisBlockHash: string) { + await initConnectionWithType(genesisBlockHash, 'full') + await initConnectionWithType(genesisBlockHash, 'light') +} + +export function migrateDBFile(genesisBlockHash: string) { + const originDBFile = dbPath(genesisBlockHash, 'cell') + const currentFullDBFile = dbPath(genesisBlockHash, 'full') + const currentLightDBFile = dbPath(genesisBlockHash, 'light') + if (fs.existsSync(originDBFile) && (!fs.existsSync(currentLightDBFile) || !fs.existsSync(currentFullDBFile))) { + if (!fs.existsSync(currentFullDBFile)) { + fs.copyFileSync(originDBFile, currentFullDBFile) + } + if (!fs.existsSync(currentLightDBFile)) { + fs.copyFileSync(originDBFile, currentLightDBFile) + } + fs.rmSync(originDBFile) + } +} + export default initConnection diff --git a/packages/neuron-wallet/src/database/chain/subscriber/address-subscriber.ts b/packages/neuron-wallet/src/database/chain/subscriber/address-subscriber.ts new file mode 100644 index 0000000000..3ab39095ed --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/subscriber/address-subscriber.ts @@ -0,0 +1,10 @@ +import { EventSubscriber } from 'typeorm' +import UserSettingSubscriber from './user-setting-subscriber' +import AddressDescription from '../entities/address-description' + +@EventSubscriber() +export default class AddressSubscribe extends UserSettingSubscriber { + listenTo() { + return AddressDescription + } +} diff --git a/packages/neuron-wallet/src/database/chain/subscriber/asset-account-subscriber.ts b/packages/neuron-wallet/src/database/chain/subscriber/asset-account-subscriber.ts new file mode 100644 index 0000000000..7e06e8db0d --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/subscriber/asset-account-subscriber.ts @@ -0,0 +1,26 @@ +import { EventSubscriber, InsertEvent } from 'typeorm' +import UserSettingSubscriber from './user-setting-subscriber' +import AssetAccount from '../entities/asset-account' + +@EventSubscriber() +export default class AssetAccountSubscribe extends UserSettingSubscriber { + unionKeys: string[] = ['tokenID', 'blake160'] + + ignoreUpdateKeys: string[] = ['sudtTokenInfo'] + + listenTo() { + return AssetAccount + } + + async afterInsert(event: InsertEvent): Promise { + const repo = this.getNeedSyncConnection(event.connection.name)?.getRepository(AssetAccount) + if (repo && event.entity) { + const exist = await repo.findOne({ tokenID: event.entity.tokenID, blake160: event.entity.blake160 }) + if (exist) { + await repo.upsert(AssetAccount.fromModel(event.entity.toModel()), this.unionKeys) + } else { + await repo.save(event.entity) + } + } + } +} diff --git a/packages/neuron-wallet/src/database/chain/subscriber/multisig-config-subscriber.ts b/packages/neuron-wallet/src/database/chain/subscriber/multisig-config-subscriber.ts new file mode 100644 index 0000000000..ba7d54c2e6 --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/subscriber/multisig-config-subscriber.ts @@ -0,0 +1,19 @@ +import { EventSubscriber, InsertEvent } from 'typeorm' +import UserSettingSubscriber from './user-setting-subscriber' +import MultisigConfig from '../entities/multisig-config' + +@EventSubscriber() +export default class MultisigConfigSubscribe extends UserSettingSubscriber { + ignoreUpdateKeys = ['lastestBlockNumber'] + + listenTo() { + return MultisigConfig + } + + async afterInsert(event: InsertEvent): Promise { + const repo = this.getNeedSyncConnection(event.connection.name)?.getRepository(MultisigConfig) + if (repo && event.entity) { + await repo.upsert(event.entity.cloneIgnoreBlockNumber(), this.unionKeys) + } + } +} diff --git a/packages/neuron-wallet/src/database/chain/subscriber/sudt-token-info-subscriber.ts b/packages/neuron-wallet/src/database/chain/subscriber/sudt-token-info-subscriber.ts new file mode 100644 index 0000000000..5682bb5fa6 --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/subscriber/sudt-token-info-subscriber.ts @@ -0,0 +1,32 @@ +import { EventSubscriber, InsertEvent } from 'typeorm' +import UserSettingSubscriber from './user-setting-subscriber' +import SudtTokenInfo from '../entities/sudt-token-info' + +@EventSubscriber() +export default class SudtTokenInfoSubscribe extends UserSettingSubscriber { + unionKeys: string[] = ['tokenID'] + + entityKeyName: string = 'tokenID' + + ignoreUpdateKeys: string[] = ['assetAccounts'] + + listenTo() { + return SudtTokenInfo + } + + async afterInsert(event: InsertEvent): Promise { + const repo = this.getNeedSyncConnection(event.connection.name)?.getRepository(SudtTokenInfo) + if (repo && event.entity) { + let mergeEntity: SudtTokenInfo | undefined = undefined + const existEntity = await event.connection.getRepository(SudtTokenInfo).findOne(event.entity.tokenID) + if (existEntity) { + mergeEntity = new SudtTokenInfo() + mergeEntity.tokenID = event.entity.tokenID || existEntity.tokenID + mergeEntity.symbol = event.entity.symbol || existEntity.symbol + mergeEntity.tokenName = event.entity.tokenName || existEntity.tokenName + mergeEntity.decimal = event.entity.decimal || existEntity.decimal + } + await repo.upsert(mergeEntity ?? event.entity, this.unionKeys) + } + } +} diff --git a/packages/neuron-wallet/src/database/chain/subscriber/tx-description-subscriber.ts b/packages/neuron-wallet/src/database/chain/subscriber/tx-description-subscriber.ts new file mode 100644 index 0000000000..61f392b7be --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/subscriber/tx-description-subscriber.ts @@ -0,0 +1,10 @@ +import { EventSubscriber } from 'typeorm' +import UserSettingSubscriber from './user-setting-subscriber' +import TxDescription from '../entities/tx-description' + +@EventSubscriber() +export default class TxDescriptionSubscribe extends UserSettingSubscriber { + listenTo() { + return TxDescription + } +} diff --git a/packages/neuron-wallet/src/database/chain/subscriber/user-setting-subscriber.ts b/packages/neuron-wallet/src/database/chain/subscriber/user-setting-subscriber.ts new file mode 100644 index 0000000000..10d3d8e1eb --- /dev/null +++ b/packages/neuron-wallet/src/database/chain/subscriber/user-setting-subscriber.ts @@ -0,0 +1,58 @@ +import { EntitySubscriberInterface, InsertEvent, RemoveEvent, UpdateEvent } from 'typeorm' +import { ConnectionName, getConnection, getCurrentConnectionName } from '../connection' + +type Constructor = new (...args: unknown[]) => T + +// Trigger relative updating through subscribing the changes from corresponding entities +export default abstract class UserSettingSubscriber + implements EntitySubscriberInterface +{ + abstract listenTo(): string | Constructor + + unionKeys: string[] = ['id'] + + entityKeyName: string = 'id' + + ignoreUpdateKeys: string[] = [] + + getNeedSyncConnection(connectionName: string) { + const currentConnectionName = getCurrentConnectionName() + if (connectionName === currentConnectionName) { + const otherConnectionName: ConnectionName = currentConnectionName === 'full' ? 'light' : 'full' + return getConnection(otherConnectionName) + } + return + } + + async afterInsert(event: InsertEvent): Promise { + const repo = this.getNeedSyncConnection(event.connection.name)?.getRepository(this.listenTo()) + if (repo && event.entity) { + await repo.upsert(event.entity, this.unionKeys) + } + } + + async afterUpdate(event: UpdateEvent): Promise { + const repo = this.getNeedSyncConnection(event.connection.name)?.getRepository(this.listenTo()) + const updatedColumns = event.updatedColumns.filter(v => !this.ignoreUpdateKeys.includes(v.propertyName)) + if (repo && event.entity && event.databaseEntity && updatedColumns.length) { + const updateEntity = updatedColumns.reduce( + (pre, cur) => ({ + ...pre, + [cur.propertyName]: event.entity![cur.propertyName], + }), + {} + ) + const key = (event.databaseEntity as any)[this.entityKeyName] + if (key !== undefined && key !== null) { + await repo.update(key, updateEntity) + } + } + } + + async afterRemove(event: RemoveEvent): Promise { + const repo = this.getNeedSyncConnection(event.connection.name)?.getRepository(this.listenTo()) + if (repo && event.databaseEntity) { + await repo.remove(event.databaseEntity) + } + } +} diff --git a/packages/neuron-wallet/src/models/synced-block-number.ts b/packages/neuron-wallet/src/models/synced-block-number.ts index 50d9145611..35f98e9e0a 100644 --- a/packages/neuron-wallet/src/models/synced-block-number.ts +++ b/packages/neuron-wallet/src/models/synced-block-number.ts @@ -1,4 +1,4 @@ -import { getConnection } from 'typeorm' +import { getConnection } from '../database/chain/connection' import SyncInfoEntity from '../database/chain/entities/sync-info' import logger from '../utils/logger' diff --git a/packages/neuron-wallet/src/services/addresses.ts b/packages/neuron-wallet/src/services/addresses.ts index 866df7c80c..91647a04e7 100644 --- a/packages/neuron-wallet/src/services/addresses.ts +++ b/packages/neuron-wallet/src/services/addresses.ts @@ -4,7 +4,7 @@ import { Address as AddressInterface } from '../models/address' import AddressCreatedSubject from '../models/subjects/address-created-subject' import NetworksService from '../services/networks' import AddressParser from '../models/address-parser' -import { getConnection } from 'typeorm' +import { getConnection } from '../database/chain/connection' import { TransactionsService } from '../services/tx' import CellsService from './cells' import SystemScriptInfo from '../models/system-script-info' diff --git a/packages/neuron-wallet/src/services/anyone-can-pay.ts b/packages/neuron-wallet/src/services/anyone-can-pay.ts index 639e406aa7..bfe9b8af33 100644 --- a/packages/neuron-wallet/src/services/anyone-can-pay.ts +++ b/packages/neuron-wallet/src/services/anyone-can-pay.ts @@ -1,7 +1,7 @@ import AssetAccountInfo from '../models/asset-account-info' import AddressParser from '../models/address-parser' import { TransactionGenerator } from './tx' -import { getConnection } from 'typeorm' +import { getConnection } from '../database/chain/connection' import Output from '../models/chain/output' import LiveCell from '../models/chain/live-cell' import Transaction from '../models/chain/transaction' diff --git a/packages/neuron-wallet/src/services/asset-account-service.ts b/packages/neuron-wallet/src/services/asset-account-service.ts index 7e076a4310..be00ae7bf7 100644 --- a/packages/neuron-wallet/src/services/asset-account-service.ts +++ b/packages/neuron-wallet/src/services/asset-account-service.ts @@ -1,4 +1,5 @@ -import { getConnection, In } from 'typeorm' +import { In } from 'typeorm' +import { getConnection } from '../database/chain/connection' import BufferUtils from '../utils/buffer' import OutputEntity from '../database/chain/entities/output' import Transaction, { TransactionStatus } from '../models/chain/transaction' diff --git a/packages/neuron-wallet/src/services/cell-local-info.ts b/packages/neuron-wallet/src/services/cell-local-info.ts index 8ce44ad5fe..545f82ebfb 100644 --- a/packages/neuron-wallet/src/services/cell-local-info.ts +++ b/packages/neuron-wallet/src/services/cell-local-info.ts @@ -1,4 +1,4 @@ -import { getConnection } from 'typeorm' +import { getConnection } from '../database/chain/connection' import CellLocalInfo, { UpdateCellLocalInfo } from '../database/chain/entities/cell-local-info' import CellsService from './cells' diff --git a/packages/neuron-wallet/src/services/cells.ts b/packages/neuron-wallet/src/services/cells.ts index 3959c4137a..375c4a61ce 100644 --- a/packages/neuron-wallet/src/services/cells.ts +++ b/packages/neuron-wallet/src/services/cells.ts @@ -1,5 +1,6 @@ -import { Brackets, getConnection, In, IsNull, type ObjectLiteral } from 'typeorm' +import { Brackets, In, IsNull, type ObjectLiteral } from 'typeorm' import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils' +import { getConnection } from '../database/chain/connection' import { scriptToAddress, addressToScript } from '../utils/scriptAndAddress' import { CapacityNotEnough, diff --git a/packages/neuron-wallet/src/services/multisig.ts b/packages/neuron-wallet/src/services/multisig.ts index 922fbf7161..0f5695f547 100644 --- a/packages/neuron-wallet/src/services/multisig.ts +++ b/packages/neuron-wallet/src/services/multisig.ts @@ -1,4 +1,5 @@ -import { getConnection, In, Not } from 'typeorm' +import { In, Not } from 'typeorm' +import { getConnection } from '../database/chain/connection' import MultisigConfig from '../database/chain/entities/multisig-config' import MultisigOutput from '../database/chain/entities/multisig-output' import { MultisigConfigNotExistError, MultisigConfigExistError } from '../exceptions/multisig' diff --git a/packages/neuron-wallet/src/services/sudt-token-info.ts b/packages/neuron-wallet/src/services/sudt-token-info.ts index 1f9e31ef3f..c24f06ad79 100644 --- a/packages/neuron-wallet/src/services/sudt-token-info.ts +++ b/packages/neuron-wallet/src/services/sudt-token-info.ts @@ -1,5 +1,6 @@ -import { In, Not, getConnection } from 'typeorm' +import { In, Not } from 'typeorm' import SudtTokenInfoEntity from '../database/chain/entities/sudt-token-info' +import { getConnection } from '../database/chain/connection' export default class SudtTokenInfoService { static async findSudtTokenInfoByArgs(typeArgsList: string[]) { diff --git a/packages/neuron-wallet/src/services/sync-progress.ts b/packages/neuron-wallet/src/services/sync-progress.ts index 962f5ad287..6bcdd83220 100644 --- a/packages/neuron-wallet/src/services/sync-progress.ts +++ b/packages/neuron-wallet/src/services/sync-progress.ts @@ -1,7 +1,8 @@ -import { getConnection, In, LessThan, Not } from 'typeorm' +import { In, LessThan, Not } from 'typeorm' import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils' import SyncProgress, { SyncAddressType } from '../database/chain/entities/sync-progress' import WalletService from './wallets' +import { getConnection } from '../database/chain/connection' export default class SyncProgressService { static async resetSyncProgress( diff --git a/packages/neuron-wallet/src/services/tx/failed-transaction.ts b/packages/neuron-wallet/src/services/tx/failed-transaction.ts index dc3c89cfb4..6841cedca1 100644 --- a/packages/neuron-wallet/src/services/tx/failed-transaction.ts +++ b/packages/neuron-wallet/src/services/tx/failed-transaction.ts @@ -1,4 +1,5 @@ -import { getConnection, In } from 'typeorm' +import { In } from 'typeorm' +import { getConnection } from '../../database/chain/connection' import OutputEntity from '../../database/chain/entities/output' import TransactionEntity from '../../database/chain/entities/transaction' import { OutputStatus } from '../../models/chain/output' diff --git a/packages/neuron-wallet/src/services/tx/transaction-description.ts b/packages/neuron-wallet/src/services/tx/transaction-description.ts index 3d6d06a6a4..a7466a9580 100644 --- a/packages/neuron-wallet/src/services/tx/transaction-description.ts +++ b/packages/neuron-wallet/src/services/tx/transaction-description.ts @@ -1,5 +1,5 @@ -import { getConnection } from 'typeorm' import TxDescription from '../../database/chain/entities/tx-description' +import { getConnection } from '../../database/chain/connection' const getEntity = async (walletId: string, txHash: string) => { return await getConnection().getRepository(TxDescription).createQueryBuilder().where({ walletId, txHash }).getOne() diff --git a/packages/neuron-wallet/src/services/tx/transaction-persistor.ts b/packages/neuron-wallet/src/services/tx/transaction-persistor.ts index 05a2d8203c..7298ded15f 100644 --- a/packages/neuron-wallet/src/services/tx/transaction-persistor.ts +++ b/packages/neuron-wallet/src/services/tx/transaction-persistor.ts @@ -1,4 +1,5 @@ -import { getConnection, In, QueryRunner } from 'typeorm' +import { In, QueryRunner } from 'typeorm' +import { getConnection } from '../../database/chain/connection' import InputEntity from '../../database/chain/entities/input' import OutputEntity from '../../database/chain/entities/output' import TransactionEntity from '../../database/chain/entities/transaction' diff --git a/packages/neuron-wallet/src/services/tx/transaction-service.ts b/packages/neuron-wallet/src/services/tx/transaction-service.ts index ce2701eb57..e58a36e84f 100644 --- a/packages/neuron-wallet/src/services/tx/transaction-service.ts +++ b/packages/neuron-wallet/src/services/tx/transaction-service.ts @@ -1,7 +1,7 @@ -import { getConnection } from 'typeorm' import { CKBRPC } from '@ckb-lumos/rpc' import TransactionEntity from '../../database/chain/entities/transaction' import OutputEntity from '../../database/chain/entities/output' +import { getConnection } from '../../database/chain/connection' import Transaction, { TransactionStatus, SudtInfo, diff --git a/packages/neuron-wallet/src/services/wallets.ts b/packages/neuron-wallet/src/services/wallets.ts index ac993ce4d0..021bc3202c 100644 --- a/packages/neuron-wallet/src/services/wallets.ts +++ b/packages/neuron-wallet/src/services/wallets.ts @@ -11,7 +11,8 @@ import FileService from './file' import AddressService from './addresses' import { DeviceInfo } from './hardware/common' import HdPublicKeyInfo from '../database/chain/entities/hd-public-key-info' -import { getConnection, In, Not } from 'typeorm' +import { In, Not } from 'typeorm' +import { getConnection } from '../database/chain/connection' import NetworksService from './networks' import { NetworkType } from '../models/network' import { resetSyncTaskQueue } from '../block-sync-renderer' diff --git a/packages/neuron-wallet/tests/block-sync-renderer/index/createBlockSyncTask.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/index/createBlockSyncTask.test.ts index 9fda25fbc2..61da50c476 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/index/createBlockSyncTask.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/index/createBlockSyncTask.test.ts @@ -1,6 +1,8 @@ +import { NetworkType } from '../../../src/models/network' + describe(`Create block sync task`, () => { const STUB_ADDRESS_METAS = 'address metas' - const STUB_NETWORK = { id: 'id', genesisHash: '0x1', remote: 'stub_network_url' } + const STUB_NETWORK = { id: 'id', genesisHash: '0x1', remote: 'stub_network_url', type: NetworkType.Normal } const stubbedLoggerInfo = jest.fn() const stubbedChildProcessOn = jest.fn() const stubbedChildProcessSend = jest.fn() @@ -74,6 +76,7 @@ describe(`Create block sync task`, () => { addressMetas: STUB_ADDRESS_METAS, genesisHash: STUB_NETWORK.genesisHash, indexerUrl: STUB_NETWORK.remote, + nodeType: NetworkType.Normal, url: STUB_NETWORK.remote, }, }) diff --git a/packages/neuron-wallet/tests/block-sync-renderer/index/killBlockSyncTask.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/index/killBlockSyncTask.test.ts index 9e103f5d62..e529dbf91f 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/index/killBlockSyncTask.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/index/killBlockSyncTask.test.ts @@ -1,3 +1,5 @@ +import { NetworkType } from '../../../src/models/network' + describe(`Kill block sync task`, () => { const stubbedQueryIndexer = jest.fn() const stubbedLoggerInfo = jest.fn() @@ -8,7 +10,7 @@ describe(`Kill block sync task`, () => { throw new Error() }) const stubbedChildProcessOnce = jest.fn() - const stubbedGetCurrentNetwork = jest.fn().mockReturnValue({ id: 'id', genesisHash: '0x' }) + const stubbedGetCurrentNetwork = jest.fn().mockReturnValue({ id: 'id', genesisHash: '0x', type: NetworkType.Normal }) const stubbedSyncTaskCtor = jest.fn().mockImplementation(() => ({ queryIndexer: stubbedQueryIndexer })) // jest.doMock('electron', () => ({ BrowserWindow: jest.fn() })) diff --git a/packages/neuron-wallet/tests/block-sync-renderer/index/queryIndexer.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/index/queryIndexer.test.ts index f12bb96a55..4830687e43 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/index/queryIndexer.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/index/queryIndexer.test.ts @@ -1,3 +1,5 @@ +import { NetworkType } from '../../../src/models/network' + const STUB_QUERY = 'stub query' const stubbedIndexerServiceStart = jest.fn() const stubbedLoggerInfo = jest.fn() @@ -33,9 +35,9 @@ jest.doMock('services/indexer', () => ({ })) jest.doMock('services/addresses', () => ({ getAddressesByAllWallets: stubbedGetAddressesByAllWallets })) jest.doMock('services/networks', () => ({ - getInstance: jest - .fn() - .mockReturnValue({ getCurrent: () => ({ id: 'id', genesisHash: '0x1', remote: 'stub_network_url' }) }), + getInstance: jest.fn().mockReturnValue({ + getCurrent: () => ({ id: 'id', genesisHash: '0x1', remote: 'stub_network_url', type: NetworkType.Normal }), + }), })) const blockSyncRenderer = require('block-sync-renderer') diff --git a/packages/neuron-wallet/tests/block-sync-renderer/indexer-cache-service.intg.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/indexer-cache-service.intg.test.ts index 21e922ff1f..507934f31e 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/indexer-cache-service.intg.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/indexer-cache-service.intg.test.ts @@ -1,11 +1,10 @@ import { when } from 'jest-when' -import { getConnection } from 'typeorm' -import { initConnection } from '../../src/database/chain/ormconfig' import AddressMeta from '../../src/database/address/meta' import { AddressType } from '../../src/models/keys/address' import { AddressVersion } from '../../src/models/address' import IndexerTxHashCache from '../../src/database/chain/entities/indexer-tx-hash-cache' import RpcService from '../../src/services/rpc-service' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' const stubbedGetTransactionFn = jest.fn() const stubbedGetHeaderFn = jest.fn() @@ -129,11 +128,11 @@ const fakeTx3 = { describe('indexer cache service', () => { beforeAll(async () => { - await initConnection('') + await initConnection() }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/block-sync-renderer/tx-status-listener.intg.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/tx-status-listener.intg.test.ts index 9178b1a4ea..430ced19fa 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/tx-status-listener.intg.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/tx-status-listener.intg.test.ts @@ -1,11 +1,10 @@ -import { getConnection } from 'typeorm' -import { initConnection } from '../../src/database/chain/ormconfig' import mockedTransactions from '../setupAndTeardown/transactions.fixture' import { TransactionStatus } from '../../src/models/chain/transaction' import TransactionPersistor from '../../src/services/tx/transaction-persistor' import { OutputStatus } from '../../src/models/chain/output' import TxStatus, { TxStatusType } from '../../src/models/chain/tx-status' import TransactionEntity from '../../src/database/chain/entities/transaction' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' const stubbedRPCServiceConstructor = jest.fn() const stubbedGetTransactionFn = jest.fn() @@ -48,11 +47,11 @@ const { register } = require('../../src/block-sync-renderer/tx-status-listener') describe('', () => { beforeAll(async () => { - await initConnection('') + await initConnection() }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/controllers/export-debug.test.ts b/packages/neuron-wallet/tests/controllers/export-debug.test.ts index 1bbfbac015..5fbe40e45a 100644 --- a/packages/neuron-wallet/tests/controllers/export-debug.test.ts +++ b/packages/neuron-wallet/tests/controllers/export-debug.test.ts @@ -56,6 +56,7 @@ jest.mock('../../src/services/networks', () => { getCurrent() { return { remote: 'http://127.0.0.1:8114', + type: NetworkType.Normal, } }, } @@ -90,6 +91,7 @@ jest.mock('../../src/services/light-runner', () => { import { dialog } from 'electron' import logger from '../../src/utils/logger' import ExportDebugController from '../../src/controllers/export-debug' +import { NetworkType } from '../../src/models/network' describe('Test ExportDebugController', () => { const exportDebugController: any = new ExportDebugController() diff --git a/packages/neuron-wallet/tests/controllers/multisig.test.ts b/packages/neuron-wallet/tests/controllers/multisig.test.ts index cd8eedc507..2ff98cbda6 100644 --- a/packages/neuron-wallet/tests/controllers/multisig.test.ts +++ b/packages/neuron-wallet/tests/controllers/multisig.test.ts @@ -4,6 +4,7 @@ import MultisigController from '../../src/controllers/multisig' import CellsService from '../../src/services/cells' import { scriptToAddress } from '../../src/utils/scriptAndAddress' import { systemScripts } from '../../src/utils/systemScripts' +import { NetworkType } from '../../src/models/network' let response = 0 let dialogRes = { canceled: false, filePaths: ['./'], filePath: './' } @@ -64,6 +65,9 @@ const isMainnetMock = jest.fn().mockReturnValue(false) jest.mock('../../src/services/networks', () => ({ getInstance: () => ({ isMainnet: () => isMainnetMock(), + getCurrent: () => ({ + type: NetworkType.Normal, + }), }), })) diff --git a/packages/neuron-wallet/tests/models/keys/hd-public-key-info.test.ts b/packages/neuron-wallet/tests/models/keys/hd-public-key-info.test.ts index d02d054440..68c397e1bd 100644 --- a/packages/neuron-wallet/tests/models/keys/hd-public-key-info.test.ts +++ b/packages/neuron-wallet/tests/models/keys/hd-public-key-info.test.ts @@ -2,6 +2,7 @@ import { scriptToAddress } from '../../../src/utils/scriptAndAddress' import { AddressType } from '../../../src/models/keys/address' import KeyInfos from '../../setupAndTeardown/public-key-info.fixture' import { systemScripts } from '../../../src/utils/systemScripts' +import { NetworkType } from '../../../src/models/network' const stubbedIsMainnet = jest.fn() @@ -9,6 +10,9 @@ jest.mock('services/networks', () => { return { getInstance: () => ({ isMainnet: stubbedIsMainnet, + getCurrent: () => ({ + type: NetworkType.Normal, + }), }), } }) diff --git a/packages/neuron-wallet/tests/models/synced-block-number.intg.test.ts b/packages/neuron-wallet/tests/models/synced-block-number.intg.test.ts index 1e66938a94..c4a7855960 100644 --- a/packages/neuron-wallet/tests/models/synced-block-number.intg.test.ts +++ b/packages/neuron-wallet/tests/models/synced-block-number.intg.test.ts @@ -1,4 +1,4 @@ -import { getConnection } from 'typeorm' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' const stubbedSyncedBlockNumberSubjectNext = jest.fn() const stubbedLoggerInfo = jest.fn() @@ -8,22 +8,20 @@ const resetMocks = () => { stubbedLoggerInfo.mockReset() } -jest.doMock('utils/logger', () => { +jest.mock('utils/logger', () => { return { - info: stubbedLoggerInfo, + info: () => stubbedLoggerInfo(), } }) -import { initConnection } from '../../src/database/chain/ormconfig' - describe('SyncedBlockNumber model', () => { let SyncedBlockNumber: any beforeAll(async () => { - await initConnection('') + await initConnection() }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/address.test.ts b/packages/neuron-wallet/tests/services/address.test.ts index 5467f85fa3..98bbf90d12 100644 --- a/packages/neuron-wallet/tests/services/address.test.ts +++ b/packages/neuron-wallet/tests/services/address.test.ts @@ -1,6 +1,4 @@ import { AccountExtendedPublicKey } from '../../src/models/keys/key' -import initConnection from '../../src/database/chain/ormconfig' -import { getConnection } from 'typeorm' import SystemScriptInfo from '../../src/models/system-script-info' import { OutputStatus } from '../../src/models/chain/output' import OutputEntity from '../../src/database/chain/entities/output' @@ -11,6 +9,8 @@ import { TransactionStatus } from '../../src/models/chain/transaction' import AddressParser from '../../src/models/address-parser' import { when } from 'jest-when' import HdPublicKeyInfo from '../../src/database/chain/entities/hd-public-key-info' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' +import { NetworkType } from '../../src/models/network' const walletId = '1' const extendedKey = new AccountExtendedPublicKey( @@ -71,6 +71,9 @@ jest.mock('services/networks', () => ({ getInstance() { return { isMainnet: () => true, + getCurrent: () => ({ + type: NetworkType.Normal, + }), } }, })) @@ -124,7 +127,7 @@ describe('integration tests for AddressService', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/anyone-can-pay.test.ts b/packages/neuron-wallet/tests/services/anyone-can-pay.test.ts index 07d6fb0f7e..4f259b2a8e 100644 --- a/packages/neuron-wallet/tests/services/anyone-can-pay.test.ts +++ b/packages/neuron-wallet/tests/services/anyone-can-pay.test.ts @@ -1,8 +1,7 @@ -import { getConnection } from 'typeorm' import AnyoneCanPayService from '../../src/services/anyone-can-pay' import AssetAccountEntity from '../../src/database/chain/entities/asset-account' import AssetAccount from '../../src/models/asset-account' -import { initConnection, closeConnection } from '../setupAndTeardown' +import { initConnection, closeConnection, getConnection } from '../setupAndTeardown' import { AcpSendSameAccountError, TargetLockError, TargetOutputNotFoundError } from '../../src/exceptions' import AssetAccountInfo from '../../src/models/asset-account-info' import SystemScriptInfo from '../../src/models/system-script-info' diff --git a/packages/neuron-wallet/tests/services/asset-account-service.test.ts b/packages/neuron-wallet/tests/services/asset-account-service.test.ts index 14da05c9ba..39842abbbe 100644 --- a/packages/neuron-wallet/tests/services/asset-account-service.test.ts +++ b/packages/neuron-wallet/tests/services/asset-account-service.test.ts @@ -1,5 +1,3 @@ -import { getConnection } from 'typeorm' -import { initConnection } from '../../src/database/chain/ormconfig' import AssetAccount from '../../src/models/asset-account' import AssetAccountEntity from '../../src/database/chain/entities/asset-account' import SudtTokenInfo from '../../src/database/chain/entities/sudt-token-info' @@ -10,7 +8,7 @@ import { OutputStatus } from '../../src/models/chain/output' import SudtTokenInfoEntity from '../../src/database/chain/entities/sudt-token-info' import TransactionEntity from '../../src/database/chain/entities/transaction' import { TransactionStatus } from '../../src/models/chain/transaction' -import { createAccounts } from '../setupAndTeardown' +import { closeConnection, createAccounts, getConnection, initConnection } from '../setupAndTeardown' import accounts from '../setupAndTeardown/accounts.fixture' import HdPublicKeyInfo from '../../src/database/chain/entities/hd-public-key-info' import { AddressType } from '../../src/models/keys/address' @@ -138,7 +136,7 @@ describe('AssetAccountService', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/cell-local-info.test.ts b/packages/neuron-wallet/tests/services/cell-local-info.test.ts index 0fc67685ca..188d4f6ac7 100644 --- a/packages/neuron-wallet/tests/services/cell-local-info.test.ts +++ b/packages/neuron-wallet/tests/services/cell-local-info.test.ts @@ -1,7 +1,6 @@ import type { OutPoint } from '@ckb-lumos/base' -import { getConnection } from 'typeorm' import CellLocalInfoService from '../../src/services/cell-local-info' -import { closeConnection, initConnection } from '../setupAndTeardown' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' import CellLocalInfo from '../../src/database/chain/entities/cell-local-info' const outPoints = [ diff --git a/packages/neuron-wallet/tests/services/cells.test.ts b/packages/neuron-wallet/tests/services/cells.test.ts index e8afb1bf48..3a506ac556 100644 --- a/packages/neuron-wallet/tests/services/cells.test.ts +++ b/packages/neuron-wallet/tests/services/cells.test.ts @@ -1,8 +1,6 @@ -import { getConnection } from 'typeorm' import type { OutPoint as OutPointSDK } from '@ckb-lumos/base' import { scriptToAddress } from '../../src/utils/scriptAndAddress' import { bytes } from '@ckb-lumos/codec' -import { initConnection } from '../../src/database/chain/ormconfig' import OutputEntity from '../../src/database/chain/entities/output' import { OutputStatus } from '../../src/models/chain/output' import CellsService, { @@ -31,6 +29,7 @@ import { MultisigConfigNeedError, TransactionInputParameterMiss } from '../../sr import LiveCell from '../../src/models/chain/live-cell' import BufferUtils from '../../src/utils/buffer' import CellLocalInfo from '../../src/database/chain/entities/cell-local-info' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' const randomHex = (length: number = 64): string => { const str: string = Array.from({ length }) @@ -101,7 +100,7 @@ describe('CellsService', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/multisig.test.ts b/packages/neuron-wallet/tests/services/multisig.test.ts index 67c459c820..2b2df349f8 100644 --- a/packages/neuron-wallet/tests/services/multisig.test.ts +++ b/packages/neuron-wallet/tests/services/multisig.test.ts @@ -1,5 +1,3 @@ -import { getConnection } from 'typeorm' -import { initConnection } from '../../src/database/chain/ormconfig' import MultisigConfig from '../../src/database/chain/entities/multisig-config' import MultisigConfigModel from '../../src/models/multisig-config' import MultisigService from '../../src/services/multisig' @@ -9,6 +7,8 @@ import { keyInfos } from '../setupAndTeardown/public-key-info.fixture' import Multisig from '../../src/models/multisig' import SystemScriptInfo from '../../src/models/system-script-info' import { computeScriptHash as scriptToHash } from '@ckb-lumos/base/lib/utils' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' +import { NetworkType } from '../../src/models/network' const [alice, bob, charlie] = keyInfos @@ -25,6 +25,14 @@ jest.mock('../../src/models/subjects/multisig-output-db-changed-subject', () => }, })) +jest.mock('../../src/services/networks', () => ({ + getInstance: () => ({ + getCurrent: () => ({ + type: NetworkType.Normal, + }), + }), +})) + describe('multisig service', () => { const multisigService = new MultisigService() const multisigConfigModel = new MultisigConfigModel( @@ -66,7 +74,7 @@ describe('multisig service', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/sudt-token-info.test.ts b/packages/neuron-wallet/tests/services/sudt-token-info.test.ts index f2021694c6..88e6d96d66 100644 --- a/packages/neuron-wallet/tests/services/sudt-token-info.test.ts +++ b/packages/neuron-wallet/tests/services/sudt-token-info.test.ts @@ -1,7 +1,6 @@ -import { getConnection } from 'typeorm' import SudtTokenInfoEntity from '../../src/database/chain/entities/sudt-token-info' import SudtTokenInfoService from '../../src/services/sudt-token-info' -import { closeConnection, initConnection } from '../setupAndTeardown' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' import HdPublicKeyInfo from '../../src/database/chain/entities/hd-public-key-info' import AssetAccountEntity from '../../src/database/chain/entities/asset-account' import accounts from '../setupAndTeardown/accounts.fixture' diff --git a/packages/neuron-wallet/tests/services/transactions.test.ts b/packages/neuron-wallet/tests/services/transactions.test.ts index 37df1c55b7..8abca504b8 100644 --- a/packages/neuron-wallet/tests/services/transactions.test.ts +++ b/packages/neuron-wallet/tests/services/transactions.test.ts @@ -1,8 +1,7 @@ -import { getConnection } from 'typeorm' -import { initConnection } from '../../src/database/chain/ormconfig' import TransactionsService, { SearchType } from '../../src/services/tx/transaction-service' import TransactionEntity from '../../src/database/chain/entities/transaction' import { TransactionStatus } from '../../src/models/chain/transaction' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' const generateTx = (hash: string, timestamp: string) => { const tx = new TransactionEntity() @@ -69,7 +68,7 @@ describe('transactions service', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts b/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts index 46551c7a02..3f6cae1d95 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts @@ -1,7 +1,5 @@ import { when } from 'jest-when' -import { getConnection } from 'typeorm' import { bytes } from '@ckb-lumos/codec' -import { initConnection } from '../../../src/database/chain/ormconfig' import OutputEntity from '../../../src/database/chain/entities/output' import InputEntity from '../../../src/database/chain/entities/input' import TransactionEntity from '../../../src/database/chain/entities/transaction' @@ -88,6 +86,7 @@ import AssetAccount from '../../../src/models/asset-account' import MultisigConfigModel from '../../../src/models/multisig-config' import MultisigOutput from '../../../src/database/chain/entities/multisig-output' import { LumosCell } from '../../../src/block-sync-renderer/sync/connector' +import { closeConnection, getConnection, initConnection } from '../../setupAndTeardown' describe('TransactionGenerator', () => { beforeAll(async () => { @@ -124,7 +123,7 @@ describe('TransactionGenerator', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) const generateCell = ( diff --git a/packages/neuron-wallet/tests/services/tx/transaction-persistor.test.ts b/packages/neuron-wallet/tests/services/tx/transaction-persistor.test.ts index 0dab3e8f9b..78c3ac4f91 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-persistor.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-persistor.test.ts @@ -1,8 +1,6 @@ import Transaction, { TransactionStatus } from '../../../src/models/chain/transaction' import { TransactionPersistor, TxSaveType } from '../../../src/services/tx' -import initConnection from '../../../src/database/chain/ormconfig' import TransactionEntity from '../../../src/database/chain/entities/transaction' -import { getConnection } from 'typeorm' import transactions from '../../setupAndTeardown/transactions.fixture' import AssetAccountInfo from '../../../src/models/asset-account-info' import SystemScriptInfo from '../../../src/models/system-script-info' @@ -12,6 +10,7 @@ import { OutputStatus } from '../../../src/models/chain/output' import OutputEntity from '../../../src/database/chain/entities/output' import HdPublicKeyInfo from '../../../src/database/chain/entities/hd-public-key-info' import InputEntity from '../../../src/database/chain/entities/input' +import { closeConnection, getConnection, initConnection } from '../../setupAndTeardown' const [tx, tx2] = transactions @@ -21,7 +20,7 @@ describe('TransactionPersistor', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/tx/transaction-service.test.ts b/packages/neuron-wallet/tests/services/tx/transaction-service.test.ts index 3d34af281d..6b5f9165a8 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-service.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-service.test.ts @@ -3,11 +3,10 @@ import fs from 'fs' import path from 'path' import TransactionService, { SearchType } from '../../../src/services/tx/transaction-service' import Transaction, { TransactionStatus } from '../../../src/models/chain/transaction' -import { initConnection, saveTransactions, closeConnection, saveAccounts } from '../../setupAndTeardown' +import { initConnection, saveTransactions, closeConnection, saveAccounts, getConnection } from '../../setupAndTeardown' import { keyInfos } from '../../setupAndTeardown/public-key-info.fixture' import accounts from '../../setupAndTeardown/accounts.fixture' import transactions from '../../setupAndTeardown/transactions.fixture' -import { getConnection } from 'typeorm' import HdPublicKeyInfo from '../../../src/database/chain/entities/hd-public-key-info' import TransactionPersistor, { TxSaveType } from '../../../src/services/tx/transaction-persistor' import SystemScriptInfo from '../../../src/models/system-script-info' diff --git a/packages/neuron-wallet/tests/services/tx/transaction.description.intg.test.ts b/packages/neuron-wallet/tests/services/tx/transaction.description.intg.test.ts index 6e3e3bc849..fa70123a14 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction.description.intg.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction.description.intg.test.ts @@ -1,7 +1,6 @@ -import initConnection from '../../../src/database/chain/ormconfig' -import { getConnection } from 'typeorm' import TxDescription from '../../../src/database/chain/entities/tx-description' import { get, set } from '../../../src/services/tx/transaction-description' +import { closeConnection, getConnection, initConnection } from '../../setupAndTeardown' describe('transaction description service', () => { const txs = [ @@ -10,11 +9,11 @@ describe('transaction description service', () => { { walletId: 'w3', txHash: 'hash3', description: 'desc3' }, ] beforeAll(async () => { - await initConnection('') + await initConnection() }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/services/wallets.test.ts b/packages/neuron-wallet/tests/services/wallets.test.ts index 73600bbcf5..e43a8f7c56 100644 --- a/packages/neuron-wallet/tests/services/wallets.test.ts +++ b/packages/neuron-wallet/tests/services/wallets.test.ts @@ -1,3 +1,9 @@ +import Keystore from '../../src/models/keys/keystore' +import { when } from 'jest-when' +import { WalletFunctionNotSupported } from '../../src/exceptions/wallet' +import { AddressType } from '../../src/models/keys/address' +import { Manufacturer } from '../../src/services/hardware/common' + const stubbedDeletedByWalletIdFn = jest.fn() const stubbedGenerateAndSaveForExtendedKeyQueue = jest.fn() const stubbedGenerateAndSaveForPublicKeyQueueAsyncPush = jest.fn() @@ -25,16 +31,10 @@ jest.doMock('../../src/services/addresses', () => { getAddressesByWalletId: stubbedGetAddressesByWalletId, } }) -import Keystore from '../../src/models/keys/keystore' -import initConnection from '../../src/database/chain/ormconfig' -import { getConnection } from 'typeorm' -import { when } from 'jest-when' -import { WalletFunctionNotSupported } from '../../src/exceptions/wallet' -import { AddressType } from '../../src/models/keys/address' -import { Manufacturer } from '../../src/services/hardware/common' import WalletService, { WalletProperties, Wallet } from '../../src/services/wallets' import { AccountExtendedPublicKey } from '../../src/models/keys/key' import HdPublicKeyInfo from '../../src/database/chain/entities/hd-public-key-info' +import { closeConnection, getConnection, initConnection } from '../setupAndTeardown' const resetMocks = () => { stubbedDeletedByWalletIdFn.mockReset() @@ -61,7 +61,7 @@ describe('wallet service', () => { }) afterAll(async () => { - await getConnection().close() + await closeConnection() }) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/setupAndTeardown/index.ts b/packages/neuron-wallet/tests/setupAndTeardown/index.ts index 24d2cec210..b2fd2ff5d6 100644 --- a/packages/neuron-wallet/tests/setupAndTeardown/index.ts +++ b/packages/neuron-wallet/tests/setupAndTeardown/index.ts @@ -1,16 +1,20 @@ import initDB from '../../src/database/chain/ormconfig' -import { getConnection } from 'typeorm' +import { getConnection as originGetConnection } from 'typeorm' import { TransactionPersistor } from '../../src/services/tx' import AssetAccount from '../../src/models/asset-account' import OutputEntity from '../../src/database/chain/entities/output' import AssetAccountEntity from '../../src/database/chain/entities/asset-account' -export const initConnection = () => { - return initDB(':memory:') +export const initConnection = (genesisBlockHash?: string) => { + return initDB(genesisBlockHash ?? ':memory:') } export const closeConnection = () => { - return getConnection().close() + return originGetConnection('full').close() +} + +export const getConnection = () => { + return originGetConnection('full') } export const saveTransactions = async (txs: any) => { diff --git a/packages/neuron-wallet/tests/utils/export-history/index.test.ts b/packages/neuron-wallet/tests/utils/export-history/index.test.ts index e6e2e2734b..3d6b252c33 100644 --- a/packages/neuron-wallet/tests/utils/export-history/index.test.ts +++ b/packages/neuron-wallet/tests/utils/export-history/index.test.ts @@ -1,12 +1,11 @@ import os from 'os' import fs from 'fs' import path from 'path' -import { initConnection, closeConnection, saveTransactions } from '../../setupAndTeardown/index' +import { initConnection, closeConnection, saveTransactions, getConnection } from '../../setupAndTeardown/index' import transactions from '../../setupAndTeardown/transactions.fixture' import { keyInfos } from '../../setupAndTeardown/public-key-info.fixture' import i18n from '../../../src/locales/i18n' import exportHistory from '../../../src/utils/export-history' -import { getConnection } from 'typeorm' import HdPublicKeyInfo from '../../../src/database/chain/entities/hd-public-key-info' describe('Test exporting history', () => {