Skip to content

Commit

Permalink
chore: Update typeorm to v3
Browse files Browse the repository at this point in the history
  • Loading branch information
yanguoyu committed Jan 10, 2024
1 parent 8c0d834 commit 5a4a3d2
Show file tree
Hide file tree
Showing 38 changed files with 150 additions and 172 deletions.
2 changes: 1 addition & 1 deletion packages/neuron-wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
"sqlite3": "5.1.6",
"subleveldown": "4.1.4",
"tslib": "2.6.2",
"typeorm": "0.2.45",
"typeorm": "0.3.17",
"undici": "5.28.2",
"uuid": "8.3.2"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
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 { TransactionCollector, CellCollector, Indexer as CkbIndexer } from '@ckb-lumos/ckb-indexer'
import { getConnection } from '../../database/chain/ormconfig'

export default class IndexerCacheService {
private addressMetas: AddressMeta[]
Expand Down Expand Up @@ -148,7 +149,7 @@ export default class IndexerCacheService {
cacheBlockNumberEntity =
(await getConnection()
.getRepository(SyncInfoEntity)
.findOne({ name: SyncInfoEntity.getLastCachedKey(blake160) })) ??
.findOneBy({ name: SyncInfoEntity.getLastCachedKey(blake160) })) ??
SyncInfoEntity.fromObject({
name: SyncInfoEntity.getLastCachedKey(blake160),
value: '0x0',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { getConnection } from 'typeorm'
import { scriptToAddress } from '../../utils/scriptAndAddress'
import OutputEntity from '../../database/chain/entities/output'
import NetworksService from '../../services/networks'
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/ormconfig'

export interface AnyoneCanPayInfo {
tokenID: string
Expand Down Expand Up @@ -90,7 +90,7 @@ export default class TxAddressFinder {
let shouldSync = false
for (const input of inputs) {
const outPoint: OutPoint = input.previousOutput!
const output = await getConnection().getRepository(OutputEntity).findOne({
const output = await getConnection().getRepository(OutputEntity).findOneBy({
outPointTxHash: outPoint.txHash,
outPointIndex: outPoint.index,
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { getConnection } from 'typeorm'
import { CONNECTION_NOT_FOUND_NAME } from '../database/chain/ormconfig'
import { CONNECTION_NOT_FOUND_NAME, getConnection } from '../database/chain/ormconfig'
import { FailedTransaction, TransactionPersistor } from '../services/tx'
import RpcService from '../services/rpc-service'
import NetworksService from '../services/networks'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ export default class MultisigConfig {
blake160s!: string[]

@Column()
alias!: string
alias: string = ''

@Column()
lastestBlockNumber!: string
lastestBlockNumber: string = ''

public static fromModel(model: MultisigConfigModel): MultisigConfig {
const multisigConfig = new MultisigConfig()
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/database/chain/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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 './ormconfig'

/*
* Clean local sqlite storage
Expand Down
28 changes: 19 additions & 9 deletions packages/neuron-wallet/src/database/chain/ormconfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createConnection, getConnectionOptions, getConnection } from 'typeorm'
import { DataSource } from 'typeorm'
import { SqliteConnectionOptions } from 'typeorm/driver/sqlite/SqliteConnectionOptions'
import path from 'path'

Expand Down Expand Up @@ -67,15 +67,13 @@ const dbPath = (name: string): string => {
return path.join(env.fileBasePath, 'cells', filename)
}

const connectOptions = async (genesisBlockHash: string): Promise<SqliteConnectionOptions> => {
const connectionOptions = await getConnectionOptions()
const getConnectionOptions = (genesisBlockHash: string): SqliteConnectionOptions => {
const database = env.isTestMode ? ':memory:' : dbPath(genesisBlockHash)

const logging: boolean | ('query' | 'schema' | 'error' | 'warn' | 'info' | 'log' | 'migration')[] = ['warn', 'error']
// (env.isDevMode) ? ['warn', 'error', 'log', 'info', 'schema', 'migration'] : ['warn', 'error']

return {
...connectionOptions,
type: 'sqlite',
database,
entities: [
Expand Down Expand Up @@ -137,26 +135,38 @@ const connectOptions = async (genesisBlockHash: string): Promise<SqliteConnectio
],
logger: 'simple-console',
logging,
synchronize: true,
maxQueryExecutionTime: 30,
}
}

let dataSource: DataSource | null = null

export const initConnection = async (genesisBlockHash: string) => {
// try to close connection, if not exist, will throw ConnectionNotFoundError when call getConnection()
try {
await getConnection().close()
await dataSource?.destroy()
} catch (err) {
dataSource = null
// do nothing
}
const connectionOptions = await connectOptions(genesisBlockHash)
const connectionOptions = getConnectionOptions(genesisBlockHash)
dataSource = new DataSource(connectionOptions)

try {
await createConnection(connectionOptions)
await getConnection().manager.query(`PRAGMA busy_timeout = 3000;`)
await getConnection().manager.query(`PRAGMA temp_store = MEMORY;`)
await dataSource.initialize()
await dataSource.manager.query(`PRAGMA busy_timeout = 3000;`)
await dataSource.manager.query(`PRAGMA temp_store = MEMORY;`)
} catch (err) {
logger.error(err.message)
}
}

export const getConnection = () => {
if (!dataSource) {
throw new Error('Should be initialize before using datasource')
}
return dataSource
}

export default initConnection
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/models/synced-block-number.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getConnection } from 'typeorm'
import { getConnection } from '../database/chain/ormconfig'
import SyncInfoEntity from '../database/chain/entities/sync-info'
import logger from '../utils/logger'

Expand Down Expand Up @@ -28,7 +28,7 @@ export default class SyncedBlockNumber {
if (!this.#blockNumberEntity) {
let blockNumber = await getConnection()
.getRepository(SyncInfoEntity)
.findOne({ name: SyncInfoEntity.CURRENT_BLOCK_NUMBER })
.findOneBy({ name: SyncInfoEntity.CURRENT_BLOCK_NUMBER })

if (!blockNumber) {
blockNumber = new SyncInfoEntity()
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/services/addresses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ 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 { TransactionsService } from '../services/tx'
import CellsService from './cells'
import SystemScriptInfo from '../models/system-script-info'
Expand All @@ -14,6 +13,7 @@ import AddressDescription from '../database/chain/entities/address-description'
import AddressDbChangedSubject from '../models/subjects/address-db-changed-subject'
import AddressMeta from '../database/address/meta'
import queueWrapper from '../utils/queue'
import { getConnection } from '../database/chain/ormconfig'

const MAX_ADDRESS_COUNT = 100

Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/services/anyone-can-pay.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import AssetAccountInfo from '../models/asset-account-info'
import AddressParser from '../models/address-parser'
import { TransactionGenerator } from './tx'
import { getConnection } from 'typeorm'
import Output from '../models/chain/output'
import LiveCell from '../models/chain/live-cell'
import Transaction from '../models/chain/transaction'
Expand All @@ -21,6 +20,7 @@ import CellsService from './cells'
import { MIN_SUDT_CAPACITY } from '../utils/const'
import NetworksService from './networks'
import { NetworkType } from '../models/network'
import { getConnection } from '../database/chain/ormconfig'

export default class AnyoneCanPayService {
public static async generateAnyoneCanPayTx(
Expand Down
13 changes: 4 additions & 9 deletions packages/neuron-wallet/src/services/asset-account-service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getConnection, In } from 'typeorm'
import { In, IsNull } from 'typeorm'
import BufferUtils from '../utils/buffer'
import OutputEntity from '../database/chain/entities/output'
import Transaction, { TransactionStatus } from '../models/chain/transaction'
Expand All @@ -16,24 +16,19 @@ import SystemScriptInfo from '../models/system-script-info'
import Input from '../models/chain/input'
import { MIN_CELL_CAPACITY } from '../utils/const'
import SudtTokenInfoService from './sudt-token-info'
import { getConnection } from '../database/chain/ormconfig'

export default class AssetAccountService {
private static async getACPCells(publicKeyHash: string, tokenId: string = 'CKBytes') {
const assetAccountInfo = new AssetAccountInfo()
const anyoneCanPayLockHash = assetAccountInfo.generateAnyoneCanPayScript(publicKeyHash).computeHash()
let typeHash = null
if (tokenId !== 'CKBytes') {
typeHash = assetAccountInfo.generateSudtScript(tokenId).computeHash()
}
const outputs = await getConnection()
.getRepository(OutputEntity)
.createQueryBuilder('output')
.where({
.findBy({
status: In([OutputStatus.Live, OutputStatus.Sent]),
lockHash: anyoneCanPayLockHash,
typeHash,
typeHash: tokenId !== 'CKBytes' ? assetAccountInfo.generateSudtScript(tokenId).computeHash() : IsNull(),
})
.getMany()

return outputs
}
Expand Down
9 changes: 5 additions & 4 deletions packages/neuron-wallet/src/services/cells.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
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 { scriptToAddress, addressToScript } from '../utils/scriptAndAddress'
import {
Expand Down Expand Up @@ -38,6 +38,7 @@ import { LOCKTIME_ARGS_LENGTH, MIN_CELL_CAPACITY } from '../utils/const'
import HdPublicKeyInfo from '../database/chain/entities/hd-public-key-info'
import CellLocalInfoService from './cell-local-info'
import CellLocalInfo from '../database/chain/entities/cell-local-info'
import { getConnection } from '../database/chain/ormconfig'

export interface PaginationResult<T = any> {
totalCount: number
Expand Down Expand Up @@ -508,7 +509,7 @@ export default class CellsService {
}

public static getLiveCell = async (outPoint: OutPoint): Promise<Cell | undefined> => {
const cellEntity: OutputEntity | undefined = await CellsService.getLiveCellEntity(outPoint)
const cellEntity = await CellsService.getLiveCellEntity(outPoint)

if (!cellEntity) {
return undefined
Expand All @@ -517,8 +518,8 @@ export default class CellsService {
return cellEntity.toModel()
}

private static getLiveCellEntity = async (outPoint: OutPoint): Promise<OutputEntity | undefined> => {
const cellEntity: OutputEntity | undefined = await getConnection().getRepository(OutputEntity).findOne({
private static getLiveCellEntity = async (outPoint: OutPoint): Promise<OutputEntity | null> => {
const cellEntity = await getConnection().getRepository(OutputEntity).findOneBy({
outPointTxHash: outPoint.txHash,
outPointIndex: outPoint.index,
status: 'live',
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/services/multisig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getConnection, In, Not } from 'typeorm'
import { In, Not } from 'typeorm'
import MultisigConfig from '../database/chain/entities/multisig-config'
import MultisigOutput from '../database/chain/entities/multisig-output'
import { MultisigConfigNotExistError, MultisigConfigExistError } from '../exceptions/multisig'
Expand All @@ -13,6 +13,7 @@ import SyncProgress, { SyncAddressType } from '../database/chain/entities/sync-p
import { NetworkType } from '../models/network'
import WalletService from './wallets'
import logger from '../utils/logger'
import { getConnection } from '../database/chain/ormconfig'

const max64Int = '0x' + 'f'.repeat(16)
export default class MultisigService {
Expand Down
5 changes: 3 additions & 2 deletions packages/neuron-wallet/src/services/sudt-token-info.ts
Original file line number Diff line number Diff line change
@@ -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/ormconfig'

export default class SudtTokenInfoService {
static async findSudtTokenInfoByArgs(typeArgsList: string[]) {
Expand Down Expand Up @@ -40,7 +41,7 @@ export default class SudtTokenInfoService {
.execute()
}

static getSudtTokenInfo(typeArgs: string): Promise<SudtTokenInfoEntity | undefined> {
static getSudtTokenInfo(typeArgs: string): Promise<SudtTokenInfoEntity | null> {
return getConnection()
.getRepository(SudtTokenInfoEntity)
.createQueryBuilder('info')
Expand Down
5 changes: 3 additions & 2 deletions packages/neuron-wallet/src/services/sync-progress.ts
Original file line number Diff line number Diff line change
@@ -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/ormconfig'

export default class SyncProgressService {
static async resetSyncProgress(
Expand Down Expand Up @@ -108,7 +109,7 @@ export default class SyncProgressService {
}

static async getOtherTypeSyncBlockNumber() {
const items = await getConnection().getRepository(SyncProgress).find({
const items = await getConnection().getRepository(SyncProgress).findBy({
addressType: SyncAddressType.Multisig,
})
return items.reduce<Record<string, number>>((pre, cur) => ({ ...pre, [cur.hash]: cur.localSavedBlockNumber }), {})
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/services/tx/failed-transaction.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { getConnection, In } from 'typeorm'
import { In } from 'typeorm'
import OutputEntity from '../../database/chain/entities/output'
import TransactionEntity from '../../database/chain/entities/transaction'
import { OutputStatus } from '../../models/chain/output'
import TransactionsService from './transaction-service'
import { TransactionStatus } from '../../models/chain/transaction'
import { getConnection } from '../../database/chain/ormconfig'

export class FailedTransaction {
public static pendings = async (): Promise<TransactionEntity[]> => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getConnection } from 'typeorm'
import { getConnection } from '../../database/chain/ormconfig'
import TxDescription from '../../database/chain/entities/tx-description'

const getEntity = async (walletId: string, txHash: string) => {
Expand Down
Loading

1 comment on commit 5a4a3d2

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 7469935326

Please sign in to comment.