From 09b6d1cc6b8c37513bf7289efc3d716c216ecb09 Mon Sep 17 00:00:00 2001 From: zhangyouxin Date: Thu, 6 Jul 2023 15:20:26 +0800 Subject: [PATCH 1/2] refactor: remove most of script.ts --- .../sync/indexer-cache-service.ts | 5 +- .../sync/light-connector.ts | 2 +- .../src/block-sync-renderer/sync/queue.ts | 8 +- .../sync/tx-address-finder.ts | 2 +- .../neuron-wallet/src/controllers/sudt.ts | 17 +- .../src/database/address/meta.ts | 4 +- .../src/database/chain/entities/input.ts | 18 +- .../chain/entities/multisig-output.ts | 12 +- .../src/database/chain/entities/output.ts | 18 +- .../src/database/chain/meta-info.ts | 4 +- ...652945662504-UpdateOutputChequeLockHash.ts | 6 +- .../src/models/address-parser.ts | 10 +- .../src/models/asset-account-info.ts | 66 ++++-- .../neuron-wallet/src/models/chain/input.ts | 21 +- .../src/models/chain/live-cell.ts | 38 ++- .../neuron-wallet/src/models/chain/output.ts | 35 +-- .../neuron-wallet/src/models/chain/script.ts | 58 +---- .../src/models/system-script-info.ts | 40 +++- .../src/models/transaction-size.ts | 19 +- .../neuron-wallet/src/services/addresses.ts | 8 +- .../src/services/anyone-can-pay.ts | 2 +- .../src/services/asset-account-service.ts | 11 +- packages/neuron-wallet/src/services/cells.ts | 16 +- .../src/services/live-cell-service.ts | 6 +- .../neuron-wallet/src/services/multisig.ts | 3 +- .../src/services/transaction-sender.ts | 13 +- .../src/services/tx/transaction-generator.ts | 26 +-- .../src/services/tx/transaction-service.ts | 8 +- .../indexer-connector.test.ts | 23 +- .../light-connector.test.ts | 221 ++++++++++++------ .../tests/block-sync-renderer/queue.test.ts | 60 +++-- .../tests/controllers/multisig.test.ts | 4 +- .../tests/controllers/sudt.test.ts | 5 +- .../tests/models/address-parser.test.ts | 11 +- .../tests/models/asset-account-info.test.ts | 8 +- .../tests/models/chain/live-cell.test.ts | 14 +- .../tests/models/chain/output.test.ts | 12 +- .../tests/models/chain/script.test.ts | 43 ---- .../tests/models/chain/transaction.test.ts | 13 +- .../tests/models/transaction-size.test.ts | 17 +- .../tests/services/address.test.ts | 5 +- .../services/asset-account-service.test.ts | 12 +- .../tests/services/cells.test.ts | 93 +++++--- .../services/tx/transaction-generator.test.ts | 190 ++++++++------- .../services/tx/transaction-persistor.test.ts | 54 +++-- .../services/tx/transaction-sender.test.ts | 83 +++---- .../services/tx/transaction-service.test.ts | 66 +++--- .../public-key-info.fixture.ts | 7 +- .../setupAndTeardown/transactions.fixture.ts | 5 +- 49 files changed, 785 insertions(+), 637 deletions(-) delete mode 100644 packages/neuron-wallet/tests/models/chain/script.test.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 012889fe55..c03401206e 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 @@ -6,6 +6,7 @@ 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 { utils } from '@ckb-lumos/base' export default class IndexerCacheService { private addressMetas: AddressMeta[] @@ -104,7 +105,7 @@ export default class IndexerCacheService { mappingsByTxHash.set(txHash, [ { address: addressMeta.address, - lockHash: lockScript.computeHash(), + lockHash: utils.computeScriptHash(lockScript), }, ]) } @@ -138,7 +139,7 @@ export default class IndexerCacheService { mappingsByTxHash.set(txHash, [ { address: addressMeta.address, - lockHash: lockScript.computeHash(), + lockHash: utils.computeScriptHash(lockScript), }, ]) } diff --git a/packages/neuron-wallet/src/block-sync-renderer/sync/light-connector.ts b/packages/neuron-wallet/src/block-sync-renderer/sync/light-connector.ts index 5cf8ed6625..b00c2aa3b1 100644 --- a/packages/neuron-wallet/src/block-sync-renderer/sync/light-connector.ts +++ b/packages/neuron-wallet/src/block-sync-renderer/sync/light-connector.ts @@ -171,7 +171,7 @@ export default class LightConnector extends Connector { addressMeta.generateLegacyACPLockScript(), ] return lockScripts.map(v => ({ - script: v.toSDK(), + script: v, scriptType: 'lock' as CKBRPC.ScriptType, walletId: addressMeta.walletId, })) diff --git a/packages/neuron-wallet/src/block-sync-renderer/sync/queue.ts b/packages/neuron-wallet/src/block-sync-renderer/sync/queue.ts index 506af6dc94..3b007f004d 100644 --- a/packages/neuron-wallet/src/block-sync-renderer/sync/queue.ts +++ b/packages/neuron-wallet/src/block-sync-renderer/sync/queue.ts @@ -21,6 +21,7 @@ import { AppendScript, BlockTips, Connector } from './connector' import LightConnector from './light-connector' import { generateRPC } from '../../utils/ckb-rpc' import { BUNDLED_LIGHT_CKB_URL } from '../../utils/const' +import { utils } from '@ckb-lumos/base' export default class Queue { #lockHashes: string[] @@ -50,13 +51,13 @@ export default class Queue { .map(blake160 => [ blake160, Multisig.hash([blake160]), - SystemScriptInfo.generateSecpScript(blake160).computeHash().slice(0, 42), + utils.computeScriptHash(SystemScriptInfo.generateSecpScript(blake160)).slice(0, 42), ]) .flat() ) this.#multiSignBlake160s = blake160s.map(blake160 => Multisig.hash([blake160])) this.#anyoneCanPayLockHashes = blake160s.map(b => - this.#assetAccountInfo.generateAnyoneCanPayScript(b).computeHash() + utils.computeScriptHash(this.#assetAccountInfo.generateAnyoneCanPayScript(b)) ) } @@ -217,7 +218,8 @@ export default class Queue { input.setInputIndex(inputIndex.toString()) if ( - previousOutput.type?.computeHash() === SystemScriptInfo.DAO_SCRIPT_HASH && + previousOutput.type && + utils.computeScriptHash(previousOutput.type) === SystemScriptInfo.getInstance().getDaoScriptHash() && previousTx.outputsData![+input.previousOutput!.index] === '0x0000000000000000' ) { const output = tx.outputs![inputIndex] 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 e82b5700d5..7a0b9be255 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 @@ -66,7 +66,7 @@ export default class TxAddressFinder { } if (this.lockHashes.has(output.lockHash!)) { if (output.type) { - if (output.typeHash === SystemScriptInfo.DAO_SCRIPT_HASH) { + if (output.typeHash === SystemScriptInfo.getInstance().getDaoScriptHash()) { this.tx.outputs![index].setDaoData(this.tx.outputsData![index]) } } diff --git a/packages/neuron-wallet/src/controllers/sudt.ts b/packages/neuron-wallet/src/controllers/sudt.ts index 2a227a48e8..dd916a05cb 100644 --- a/packages/neuron-wallet/src/controllers/sudt.ts +++ b/packages/neuron-wallet/src/controllers/sudt.ts @@ -1,11 +1,10 @@ -import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils' import LiveCellService from '../services/live-cell-service' import AssetAccountInfo from '../models/asset-account-info' -import Script, { ScriptHashType } from '../models/chain/script' import parseSUDTTokenInfo from '../utils/parse_sudt_token_info' import { ResponseCode } from '../utils/const' import { SudtTokenInfo } from '../models/chain/transaction' import AssetAccountService from '../services/asset-account-service' +import { Script, utils } from '@ckb-lumos/base' export default class SUDTController { public async getSUDTTokenInfo(params: { tokenID: string }): Promise> { @@ -18,11 +17,11 @@ export default class SUDTController { } } - const typeScript = Script.fromObject({ + const typeScript: Script = { codeHash: new AssetAccountInfo().sudtInfoCodeHash, args: params.tokenID, - hashType: ScriptHashType.Type, - }) + hashType: 'type', + } const liveCell = await LiveCellService.getInstance().getOneByLockScriptAndTypeScript(null, typeScript) if (!liveCell) { return { @@ -38,10 +37,14 @@ export default class SUDTController { public getSUDTTypeScriptHash(params: { tokenID: string }): Controller.Response { const assetAccount = new AssetAccountInfo() - const script = new Script(assetAccount.infos.sudt.codeHash, params.tokenID, assetAccount.infos.sudt.hashType) + const script: Script = { + codeHash: assetAccount.sudtInfoCodeHash, + args: params.tokenID, + hashType: assetAccount.infos.sudt.hashType, + } return { status: ResponseCode.Success, - result: scriptToHash(script.toSDK()), + result: utils.computeScriptHash(script), } } } diff --git a/packages/neuron-wallet/src/database/address/meta.ts b/packages/neuron-wallet/src/database/address/meta.ts index 56f2c05a1b..a917cb4bb7 100644 --- a/packages/neuron-wallet/src/database/address/meta.ts +++ b/packages/neuron-wallet/src/database/address/meta.ts @@ -1,10 +1,10 @@ import { Address, AddressVersion } from '../../models/address' import { AddressType } from '../../models/keys/address' -import Script from '../../models/chain/script' import SystemScriptInfo from '../../models/system-script-info' import AssetAccountInfo from '../../models/asset-account-info' import HdPublicKeyInfoModel from '../../models/keys/hd-public-key-info' import Multisig from '../../models/multisig' +import { Script, utils } from '@ckb-lumos/base' export default class AddressMeta implements Address { walletId: string @@ -116,6 +116,6 @@ export default class AddressMeta implements Address { public generateChequeLockScriptWithReceiverLockHash(): Script { const defaultLockScript = this.generateDefaultLockScript() const assetAccountInfo = new AssetAccountInfo() - return assetAccountInfo.generateChequeScript(defaultLockScript.computeHash(), '0'.repeat(40)) + return assetAccountInfo.generateChequeScript(utils.computeScriptHash(defaultLockScript), '0'.repeat(40)) } } diff --git a/packages/neuron-wallet/src/database/chain/entities/input.ts b/packages/neuron-wallet/src/database/chain/entities/input.ts index 2aa7c1532b..45e8686658 100644 --- a/packages/neuron-wallet/src/database/chain/entities/input.ts +++ b/packages/neuron-wallet/src/database/chain/entities/input.ts @@ -2,7 +2,7 @@ import { Entity, BaseEntity, Column, ManyToOne, PrimaryGeneratedColumn } from 't import Transaction from './transaction' import OutPoint from '../../../models/chain/out-point' import InputModel from '../../../models/chain/input' -import Script, { ScriptHashType } from '../../../models/chain/script' +import { HashType, Script } from '@ckb-lumos/base' // cellbase input may have same OutPoint @Entity() @@ -51,7 +51,7 @@ export default class Input extends BaseEntity { type: 'varchar', nullable: true, }) - lockHashType: ScriptHashType | null = null + lockHashType: HashType | null = null @Column({ type: 'varchar', @@ -69,7 +69,7 @@ export default class Input extends BaseEntity { type: 'varchar', nullable: true, }) - typeHashType: ScriptHashType | null = null + typeHashType: HashType | null = null @Column({ type: 'varchar', @@ -119,14 +119,22 @@ export default class Input extends BaseEntity { public lockScript(): Script | undefined { if (this.lockCodeHash && this.lockArgs && this.lockHashType) { - return new Script(this.lockCodeHash, this.lockArgs, this.lockHashType) + return { + codeHash: this.lockCodeHash, + args: this.lockArgs, + hashType: this.lockHashType, + } } return undefined } public typeScript(): Script | undefined { if (this.typeCodeHash && this.typeArgs && this.typeHashType) { - return new Script(this.typeCodeHash, this.typeArgs, this.typeHashType) + return { + codeHash: this.typeCodeHash, + args: this.typeArgs, + hashType: this.typeHashType, + } } return undefined } diff --git a/packages/neuron-wallet/src/database/chain/entities/multisig-output.ts b/packages/neuron-wallet/src/database/chain/entities/multisig-output.ts index deeaf9f9ba..64b61c5ccd 100644 --- a/packages/neuron-wallet/src/database/chain/entities/multisig-output.ts +++ b/packages/neuron-wallet/src/database/chain/entities/multisig-output.ts @@ -1,8 +1,8 @@ import { Entity, BaseEntity, Column, PrimaryColumn } from 'typeorm' -import Script, { ScriptHashType } from '../../../models/chain/script' import OutPoint from '../../../models/chain/out-point' import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils' import { OutputStatus } from '../../../models/chain/output' +import { HashType, Script } from '@ckb-lumos/base' @Entity() export default class MultisigOutput extends BaseEntity { @@ -39,7 +39,7 @@ export default class MultisigOutput extends BaseEntity { @Column({ type: 'varchar', }) - lockHashType!: ScriptHashType + lockHashType!: HashType @Column({ type: 'varchar', @@ -56,7 +56,11 @@ export default class MultisigOutput extends BaseEntity { } public lockScript(): Script { - return new Script(this.lockCodeHash, this.lockArgs, this.lockHashType) + return { + codeHash: this.lockCodeHash, + args: this.lockArgs, + hashType: this.lockHashType as HashType, + } } public static fromIndexer(params: { @@ -70,7 +74,7 @@ export default class MultisigOutput extends BaseEntity { entity.capacity = BigInt(params.output.capacity).toString() entity.lockArgs = params.output.lock.args entity.lockCodeHash = params.output.lock.code_hash - entity.lockHashType = params.output.lock.hash_type as ScriptHashType + entity.lockHashType = params.output.lock.hash_type as HashType entity.lockHash = scriptToHash({ args: entity.lockArgs, codeHash: entity.lockCodeHash, diff --git a/packages/neuron-wallet/src/database/chain/entities/output.ts b/packages/neuron-wallet/src/database/chain/entities/output.ts index d05af4ce0f..6489921536 100644 --- a/packages/neuron-wallet/src/database/chain/entities/output.ts +++ b/packages/neuron-wallet/src/database/chain/entities/output.ts @@ -1,8 +1,8 @@ import { Entity, BaseEntity, Column, PrimaryColumn, ManyToOne } from 'typeorm' import TransactionEntity from './transaction' -import Script, { ScriptHashType } from '../../../models/chain/script' import OutPoint from '../../../models/chain/out-point' import OutputModel, { OutputStatus } from '../../../models/chain/output' +import { HashType, Script } from '@ckb-lumos/base' @Entity() export default class Output extends BaseEntity { @@ -34,7 +34,7 @@ export default class Output extends BaseEntity { @Column({ type: 'varchar', }) - lockHashType!: ScriptHashType + lockHashType!: HashType @Column({ type: 'varchar', @@ -62,7 +62,7 @@ export default class Output extends BaseEntity { type: 'varchar', nullable: true, }) - typeHashType: ScriptHashType | null = null + typeHashType: HashType | null = null @Column({ type: 'varchar', @@ -118,12 +118,20 @@ export default class Output extends BaseEntity { } public lockScript(): Script { - return new Script(this.lockCodeHash, this.lockArgs, this.lockHashType) + return { + codeHash: this.lockCodeHash, + args: this.lockArgs, + hashType: this.lockHashType as HashType, + } } public typeScript(): Script | undefined { if (this.typeCodeHash && this.typeArgs && this.typeHashType) { - return new Script(this.typeCodeHash, this.typeArgs, this.typeHashType) + return { + codeHash: this.typeCodeHash, + args: this.typeArgs, + hashType: this.typeHashType as HashType, + } } return undefined } diff --git a/packages/neuron-wallet/src/database/chain/meta-info.ts b/packages/neuron-wallet/src/database/chain/meta-info.ts index 6a39f00225..d56ad38c7e 100644 --- a/packages/neuron-wallet/src/database/chain/meta-info.ts +++ b/packages/neuron-wallet/src/database/chain/meta-info.ts @@ -1,6 +1,6 @@ import FileService from '../../services/file' import OutPoint from '../../models/chain/out-point' -import { ScriptHashType } from '../../models/chain/script' +import { HashType } from '@ckb-lumos/base' const moduleName = 'cells' const fileName = 'meta-info.json' @@ -8,7 +8,7 @@ const fileName = 'meta-info.json' export interface SystemScript { codeHash: string outPoint: OutPoint - hashType: ScriptHashType + hashType: HashType } export interface MetaInfo { diff --git a/packages/neuron-wallet/src/database/chain/migrations/1652945662504-UpdateOutputChequeLockHash.ts b/packages/neuron-wallet/src/database/chain/migrations/1652945662504-UpdateOutputChequeLockHash.ts index 9d4d306ad8..a2f4edf5ae 100644 --- a/packages/neuron-wallet/src/database/chain/migrations/1652945662504-UpdateOutputChequeLockHash.ts +++ b/packages/neuron-wallet/src/database/chain/migrations/1652945662504-UpdateOutputChequeLockHash.ts @@ -1,7 +1,7 @@ import { In, MigrationInterface, QueryRunner } from "typeorm"; import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils' -import { ScriptHashType } from "../../../models/chain/script"; import Output from "../entities/output"; +import { HashType } from "@ckb-lumos/base"; export class UpdateOutputChequeLockHash1652945662504 implements MigrationInterface { name = 'UpdateOutputChequeLockHash1652945662504' @@ -11,12 +11,12 @@ export class UpdateOutputChequeLockHash1652945662504 implements MigrationInterfa scriptToHash({ args: '0x' + '0'.repeat(80), codeHash: process.env.TESTNET_CHEQUE_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_CHEQUE_SCRIPT_HASHTYPE! as ScriptHashType + hashType: process.env.TESTNET_CHEQUE_SCRIPT_HASHTYPE! as HashType }), scriptToHash({ args: '0x' + '0'.repeat(80), codeHash: process.env.MAINNET_CHEQUE_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_CHEQUE_SCRIPT_HASHTYPE! as ScriptHashType + hashType: process.env.MAINNET_CHEQUE_SCRIPT_HASHTYPE! as HashType }) ] const chequeOutput = await queryRunner.connection diff --git a/packages/neuron-wallet/src/models/address-parser.ts b/packages/neuron-wallet/src/models/address-parser.ts index ae48dd1e8a..0d1e5e7ce9 100644 --- a/packages/neuron-wallet/src/models/address-parser.ts +++ b/packages/neuron-wallet/src/models/address-parser.ts @@ -1,12 +1,16 @@ -import Script, { ScriptHashType } from './chain/script' import { addressToScript } from '@nervosnetwork/ckb-sdk-utils' import SystemScriptInfo from './system-script-info' +import { Script, utils } from '@ckb-lumos/base' export default class AddressParser { public static parse(address: string): Script { try { const script = addressToScript(address) - return new Script(script.codeHash, script.args, script.hashType as ScriptHashType) + return { + codeHash: script.codeHash, + args: script.args, + hashType: script.hashType, + } } catch { throw new Error('Address format error') } @@ -17,7 +21,7 @@ export default class AddressParser { } public static batchToLockHash(addresses: string[]): string[] { - return this.batchParse(addresses).map(lock => lock.computeHash()) + return this.batchParse(addresses).map(lock => utils.computeScriptHash(lock)) } public static toBlake160(address: string) { diff --git a/packages/neuron-wallet/src/models/asset-account-info.ts b/packages/neuron-wallet/src/models/asset-account-info.ts index dac6d3722a..053cf6b5e3 100644 --- a/packages/neuron-wallet/src/models/asset-account-info.ts +++ b/packages/neuron-wallet/src/models/asset-account-info.ts @@ -1,16 +1,16 @@ import CellDep, { DepType } from './chain/cell-dep' -import Script, { ScriptHashType } from './chain/script' import OutPoint from './chain/out-point' import NetworksService from '../services/networks' import Transaction from './chain/transaction' import HexUtils from '../utils/hex' import SystemScriptInfo from './system-script-info' import { Address } from './address' +import { HashType, Script, utils } from '@ckb-lumos/base' export interface ScriptCellInfo { cellDep: CellDep codeHash: string - hashType: ScriptHashType + hashType: HashType } export default class AssetAccountInfo { @@ -43,7 +43,7 @@ export default class AssetAccountInfo { process.env.MAINNET_SUDT_DEP_TYPE! as DepType ), codeHash: process.env.MAINNET_SUDT_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_SUDT_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.MAINNET_SUDT_SCRIPT_HASHTYPE! as HashType, } this.sudtInfo = { cellDep: new CellDep( @@ -51,7 +51,7 @@ export default class AssetAccountInfo { process.env.MAINNET_SUDT_INFO_DEP_TYPE! as DepType ), codeHash: process.env.MAINNET_SUDT_INFO_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_SUDT_INFO_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.MAINNET_SUDT_INFO_SCRIPT_HASHTYPE! as HashType, } this.anyoneCanPayInfo = { cellDep: new CellDep( @@ -59,7 +59,7 @@ export default class AssetAccountInfo { process.env.MAINNET_ACP_DEP_TYPE! as DepType ), codeHash: process.env.MAINNET_ACP_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_ACP_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.MAINNET_ACP_SCRIPT_HASHTYPE! as HashType, } this.legacyAnyoneCanPayInfo = { cellDep: new CellDep( @@ -67,7 +67,7 @@ export default class AssetAccountInfo { process.env.LEGACY_MAINNET_ACP_DEP_TYPE! as DepType ), codeHash: process.env.LEGACY_MAINNET_ACP_SCRIPT_CODEHASH!, - hashType: process.env.LEGACY_MAINNET_ACP_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.LEGACY_MAINNET_ACP_SCRIPT_HASHTYPE! as HashType, } this.pwAnyoneCanPayInfo = { cellDep: new CellDep( @@ -75,7 +75,7 @@ export default class AssetAccountInfo { process.env.MAINNET_PW_ACP_DEP_TYPE! as DepType ), codeHash: process.env.MAINNET_PW_ACP_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_PW_ACP_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.MAINNET_PW_ACP_SCRIPT_HASHTYPE! as HashType, } this.chequeInfo = { cellDep: new CellDep( @@ -83,7 +83,7 @@ export default class AssetAccountInfo { process.env.MAINNET_CHEQUE_DEP_TYPE! as DepType ), codeHash: process.env.MAINNET_CHEQUE_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_CHEQUE_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.MAINNET_CHEQUE_SCRIPT_HASHTYPE! as HashType, } this.nftIssuerInfo = { cellDep: new CellDep( @@ -91,7 +91,7 @@ export default class AssetAccountInfo { process.env.MAINNET_NFT_ISSUER_DEP_TYPE as DepType ), codeHash: process.env.MAINNET_NFT_ISSUER_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_NFT_ISSUER_SCRIPT_HASH_TYPE! as ScriptHashType, + hashType: process.env.MAINNET_NFT_ISSUER_SCRIPT_HASH_TYPE! as HashType, } this.nftClassInfo = { cellDep: new CellDep( @@ -99,7 +99,7 @@ export default class AssetAccountInfo { process.env.MAINNET_NFT_CLASS_DEP_TYPE as DepType ), codeHash: process.env.MAINNET_NFT_CLASS_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_NFT_CLASS_SCRIPT_HASH_TYPE! as ScriptHashType, + hashType: process.env.MAINNET_NFT_CLASS_SCRIPT_HASH_TYPE! as HashType, } this.nftInfo = { cellDep: new CellDep( @@ -107,7 +107,7 @@ export default class AssetAccountInfo { process.env.MAINNET_NFT_DEP_TYPE as DepType ), codeHash: process.env.MAINNET_NFT_SCRIPT_CODEHASH!, - hashType: process.env.MAINNET_NFT_SCRIPT_HASH_TYPE! as ScriptHashType, + hashType: process.env.MAINNET_NFT_SCRIPT_HASH_TYPE! as HashType, } } else { this.sudt = { @@ -116,7 +116,7 @@ export default class AssetAccountInfo { process.env.TESTNET_SUDT_DEP_TYPE! as DepType ), codeHash: process.env.TESTNET_SUDT_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_SUDT_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.TESTNET_SUDT_SCRIPT_HASHTYPE! as HashType, } this.sudtInfo = { cellDep: new CellDep( @@ -124,7 +124,7 @@ export default class AssetAccountInfo { process.env.TESTNET_SUDT_INFO_DEP_TYPE! as DepType ), codeHash: process.env.TESTNET_SUDT_INFO_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_SUDT_INFO_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.TESTNET_SUDT_INFO_SCRIPT_HASHTYPE! as HashType, } this.anyoneCanPayInfo = { cellDep: new CellDep( @@ -132,7 +132,7 @@ export default class AssetAccountInfo { process.env.TESTNET_ACP_DEP_TYPE! as DepType ), codeHash: process.env.TESTNET_ACP_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_ACP_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.TESTNET_ACP_SCRIPT_HASHTYPE! as HashType, } this.legacyAnyoneCanPayInfo = { cellDep: new CellDep( @@ -140,7 +140,7 @@ export default class AssetAccountInfo { process.env.LEGACY_TESTNET_ACP_DEP_TYPE! as DepType ), codeHash: process.env.LEGACY_TESTNET_ACP_SCRIPT_CODEHASH!, - hashType: process.env.LEGACY_TESTNET_ACP_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.LEGACY_TESTNET_ACP_SCRIPT_HASHTYPE! as HashType, } this.pwAnyoneCanPayInfo = { cellDep: new CellDep( @@ -148,7 +148,7 @@ export default class AssetAccountInfo { process.env.TESTNET_PW_ACP_DEP_TYPE! as DepType ), codeHash: process.env.TESTNET_PW_ACP_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_PW_ACP_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.TESTNET_PW_ACP_SCRIPT_HASHTYPE! as HashType, } this.chequeInfo = { cellDep: new CellDep( @@ -156,7 +156,7 @@ export default class AssetAccountInfo { process.env.TESTNET_CHEQUE_DEP_TYPE! as DepType ), codeHash: process.env.TESTNET_CHEQUE_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_CHEQUE_SCRIPT_HASHTYPE! as ScriptHashType, + hashType: process.env.TESTNET_CHEQUE_SCRIPT_HASHTYPE! as HashType, } this.nftIssuerInfo = { cellDep: new CellDep( @@ -164,7 +164,7 @@ export default class AssetAccountInfo { process.env.TESTNET_NFT_ISSUER_DEP_TYPE as DepType ), codeHash: process.env.TESTNET_NFT_ISSUER_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_NFT_ISSUER_SCRIPT_HASH_TYPE! as ScriptHashType, + hashType: process.env.TESTNET_NFT_ISSUER_SCRIPT_HASH_TYPE! as HashType, } this.nftClassInfo = { cellDep: new CellDep( @@ -172,7 +172,7 @@ export default class AssetAccountInfo { process.env.TESTNET_NFT_CLASS_DEP_TYPE as DepType ), codeHash: process.env.TESTNET_NFT_CLASS_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_NFT_CLASS_SCRIPT_HASH_TYPE! as ScriptHashType, + hashType: process.env.TESTNET_NFT_CLASS_SCRIPT_HASH_TYPE! as HashType, } this.nftInfo = { cellDep: new CellDep( @@ -180,7 +180,7 @@ export default class AssetAccountInfo { process.env.TESTNET_NFT_DEP_TYPE as DepType ), codeHash: process.env.TESTNET_NFT_SCRIPT_CODEHASH!, - hashType: process.env.TESTNET_NFT_SCRIPT_HASH_TYPE! as ScriptHashType, + hashType: process.env.TESTNET_NFT_SCRIPT_HASH_TYPE! as HashType, } } } @@ -230,17 +230,29 @@ export default class AssetAccountInfo { } public generateSudtScript(args: string): Script { - return new Script(this.sudt.codeHash, args, this.sudt.hashType) + return { + codeHash: this.sudt.codeHash, + hashType: this.sudt.hashType, + args, + } } public generateAnyoneCanPayScript(args: string): Script { const info = this.anyoneCanPayInfo - return new Script(info.codeHash, args, info.hashType) + return { + codeHash: info.codeHash, + hashType: info.hashType, + args, + } } public generateLegacyAnyoneCanPayScript(args: string): Script { const info = this.legacyAnyoneCanPayInfo - return new Script(info.codeHash, args, info.hashType) + return { + codeHash: info.codeHash, + hashType: info.hashType, + args, + } } public generateChequeScript(receiverLockHash: string, senderLockHash: string): Script { @@ -248,7 +260,11 @@ export default class AssetAccountInfo { const senderLockHash20 = HexUtils.removePrefix(senderLockHash).slice(0, 40) const args = `0x${receiverLockHash20}${senderLockHash20}` const info = this.chequeInfo - return new Script(info.codeHash, args, info.hashType) + return { + codeHash: info.codeHash, + hashType: info.hashType, + args, + } } public isSudtScript(script: Script): boolean { @@ -292,7 +308,7 @@ export default class AssetAccountInfo { for (const lockHash20 of [receiverLockHash, senderLockHash]) { const foundAddressInfo = addressInfos.find(info => { const defaultLockScript = SystemScriptInfo.generateSecpScript(info.blake160) - const addressLockHash20 = HexUtils.removePrefix(defaultLockScript.computeHash()).slice(0, 40) + const addressLockHash20 = HexUtils.removePrefix(utils.computeScriptHash(defaultLockScript)).slice(0, 40) return lockHash20 === addressLockHash20 }) if (foundAddressInfo) { diff --git a/packages/neuron-wallet/src/models/chain/input.ts b/packages/neuron-wallet/src/models/chain/input.ts index ec3dacece7..dad82e6f60 100644 --- a/packages/neuron-wallet/src/models/chain/input.ts +++ b/packages/neuron-wallet/src/models/chain/input.ts @@ -1,7 +1,7 @@ import OutPoint from './out-point' -import Script from './script' import HexUtils from '../../utils/hex' import TypeChecker from '../../utils/type-checker' +import { Script, utils } from '@ckb-lumos/base' export default class Input { public previousOutput: OutPoint | null @@ -36,11 +36,16 @@ export default class Input { this.inputIndex = inputIndex ? (+inputIndex).toString() : undefined this.multiSignBlake160 = multiSignBlake160 - this.lockHash = lockHash || this.lock?.computeHash() - + this.lockHash = lockHash + if (lock) { + this.lockHash = utils.computeScriptHash(lock) + } this.type = type - this.typeHash = typeHash || this.type?.computeHash() + this.typeHash = typeHash + if (type) { + this.typeHash = utils.computeScriptHash(type) + } this.data = data TypeChecker.hashChecker(this.lockHash, this.typeHash) @@ -74,11 +79,11 @@ export default class Input { previousOutput ? OutPoint.fromObject(previousOutput) : previousOutput, since, capacity, - lock ? Script.fromObject(lock) : lock, + lock, lockHash, inputIndex, multiSignBlake160, - type ? Script.fromObject(type) : type, + type, typeHash, data ) @@ -90,12 +95,12 @@ export default class Input { public setLock(value: Script) { this.lock = value - this.lockHash = this.lock.computeHash() + this.lockHash = utils.computeScriptHash(value) } public setType(value: Script) { this.type = value - this.typeHash = this.type.computeHash() + this.typeHash = utils.computeScriptHash(value) } public setData(value: string) { diff --git a/packages/neuron-wallet/src/models/chain/live-cell.ts b/packages/neuron-wallet/src/models/chain/live-cell.ts index 83d156be7f..297fd16eb0 100644 --- a/packages/neuron-wallet/src/models/chain/live-cell.ts +++ b/packages/neuron-wallet/src/models/chain/live-cell.ts @@ -1,12 +1,6 @@ -import Script, { ScriptHashType } from './script' import OutPoint from './out-point' import { LumosCell } from '../../block-sync-renderer/sync/connector' - -const LUMOS_HASH_TYPE_MAP: Record = { - type: ScriptHashType.Type, - data1: ScriptHashType.Data1, - data: ScriptHashType.Data, -} +import { HashType, Script, utils } from '@ckb-lumos/base' export default class LiveCell { public txHash: string @@ -26,12 +20,12 @@ export default class LiveCell { this.txHash = txHash this.outputIndex = BigInt(outputIndex).toString() this.capacity = BigInt(capacity).toString() - this.lockHash = lock.computeHash() + this.lockHash = utils.computeScriptHash(lock) this.lockHashType = lock.hashType this.lockCodeHash = lock.codeHash this.lockArgs = lock.args if (type) { - this.typeHash = type.computeHash() + this.typeHash = utils.computeScriptHash(type) this.typeHashType = type.hashType this.typeCodeHash = type.codeHash this.typeArgs = type.args @@ -44,34 +38,32 @@ export default class LiveCell { } public lock(): Script { - return new Script(this.lockCodeHash, this.lockArgs, this.lockHashType as ScriptHashType) + return { + codeHash: this.lockCodeHash, + args: this.lockArgs, + hashType: this.lockHashType as HashType, + } } public type(): Script | undefined { if (this.typeCodeHash && this.typeArgs && this.typeHashType) { - return new Script(this.typeCodeHash, this.typeArgs, this.typeHashType as ScriptHashType) + return { + codeHash: this.typeCodeHash, + args: this.typeArgs, + hashType: this.typeHashType as HashType, + } } return undefined } public static fromLumos(cell: LumosCell): LiveCell { - const type = cell.cellOutput.type - ? new Script( - cell.cellOutput.type.codeHash, - cell.cellOutput.type.args, - LUMOS_HASH_TYPE_MAP[cell.cellOutput.type.hashType] ?? ScriptHashType.Data - ) - : null + const type = (cell.cellOutput.type as Script) || null return new LiveCell( cell.outPoint.txHash, cell.outPoint.index, cell.cellOutput.capacity, - new Script( - cell.cellOutput.lock.codeHash, - cell.cellOutput.lock.args, - LUMOS_HASH_TYPE_MAP[cell.cellOutput.lock.hashType] ?? ScriptHashType.Data - ), + cell.cellOutput.lock as Script, type, cell.data ? cell.data : '0x' ) diff --git a/packages/neuron-wallet/src/models/chain/output.ts b/packages/neuron-wallet/src/models/chain/output.ts index 071a3f24e3..f7be137b06 100644 --- a/packages/neuron-wallet/src/models/chain/output.ts +++ b/packages/neuron-wallet/src/models/chain/output.ts @@ -1,7 +1,8 @@ -import Script from './script' import OutPoint from './out-point' import HexUtils from '../../utils/hex' import TypeChecker from '../../utils/type-checker' +import { Script, utils } from '@ckb-lumos/base' +import { calculateScriptBytesize } from './script' // sent: pending transaction's output // pending: pending transaction's input @@ -55,7 +56,8 @@ export default class Output { lock: Script, type?: Script | null, data?: string, - lockHash?: string, + // REFACTOR: remove lockHash, use lock to calculate lockHash + _lockHash?: string, typeHash?: string, outPoint?: OutPoint, status?: OutputStatus, @@ -69,9 +71,12 @@ export default class Output { ) { this.capacity = BigInt(capacity).toString() this.lock = lock + this.lockHash = utils.computeScriptHash(lock) this.type = type - this.lockHash = lockHash || this.lock.computeHash() - this.typeHash = typeHash || this.type?.computeHash() + this.typeHash = typeHash + if (type) { + this.typeHash = utils.computeScriptHash(type) + } this.outPoint = outPoint this.status = status this.daoData = daoData @@ -125,8 +130,8 @@ export default class Output { }): Output { return new Output( capacity, - Script.fromObject(lock), - type ? Script.fromObject(type) : type, + lock, + type, data, lockHash, typeHash, @@ -165,13 +170,13 @@ export default class Output { public setLock(value: Script) { this.lock = value - this.lockHash = value.computeHash() + this.lockHash = utils.computeScriptHash(value) } public setType(value: Script | null) { if (value) { this.type = value - this.lockHash = value.computeHash() + this.lockHash = utils.computeScriptHash(value) } else { this.type = value this.typeHash = undefined @@ -203,9 +208,9 @@ export default class Output { } public calculateBytesize(): number { - let bytesize = 8 + HexUtils.byteLength(this.data) + this.lock.calculateBytesize() + let bytesize = 8 + HexUtils.byteLength(this.data) + calculateScriptBytesize(this.lock) if (this.type) { - bytesize += this.type.calculateBytesize() + bytesize += calculateScriptBytesize(this.type) } return bytesize } @@ -213,16 +218,12 @@ export default class Output { public toSDK(): CKBComponents.CellOutput { return { capacity: HexUtils.toHex(this.capacity), - lock: this.lock.toSDK(), - type: this.type ? this.type.toSDK() : this.type, + lock: this.lock, + type: this.type, } } public static fromSDK(output: CKBComponents.CellOutput): Output { - return new Output( - output.capacity, - Script.fromSDK(output.lock), - output.type ? Script.fromSDK(output.type) : output.type - ) + return new Output(output.capacity, output.lock, output.type) } } diff --git a/packages/neuron-wallet/src/models/chain/script.ts b/packages/neuron-wallet/src/models/chain/script.ts index 09a341e039..6f2fedc0d8 100644 --- a/packages/neuron-wallet/src/models/chain/script.ts +++ b/packages/neuron-wallet/src/models/chain/script.ts @@ -1,56 +1,8 @@ -import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils' +import { Script } from '@ckb-lumos/base' import HexUtils from '../../utils/hex' -import TypeChecker from '../../utils/type-checker' -export enum ScriptHashType { - Data = 'data', - Type = 'type', - Data1 = 'data1', -} - -export default class Script { - public codeHash: string - public args: string - public hashType: ScriptHashType - - constructor(codeHash: string, args: string, hashType: ScriptHashType) { - this.args = args - this.codeHash = codeHash - this.hashType = hashType - - TypeChecker.hashChecker(this.codeHash) - } - - public static fromObject({ - codeHash, - args, - hashType, - }: { - codeHash: string - args: string - hashType: ScriptHashType - }): Script { - return new Script(codeHash, args, hashType) - } - - public computeHash(): string { - const hash: string = scriptToHash(this.toSDK()) - return HexUtils.addPrefix(hash) - } - - public calculateBytesize(): number { - return 1 + HexUtils.byteLength(this.codeHash) + HexUtils.byteLength(this.args) - } - - public toSDK(): CKBComponents.Script { - return { - args: this.args, - codeHash: this.codeHash, - hashType: this.hashType, - } - } - - public static fromSDK(sdkScript: CKBComponents.Script): Script { - return new Script(sdkScript.codeHash, sdkScript.args, sdkScript.hashType as ScriptHashType) - } +// calculate bytelength of script, but without the header bytes of molecule encoding +// TODO: refactor me with @ckb-lumos/codec +export const calculateScriptBytesize = (script: Script): number => { + return 1 + HexUtils.byteLength(script.codeHash) + HexUtils.byteLength(script.args) } diff --git a/packages/neuron-wallet/src/models/system-script-info.ts b/packages/neuron-wallet/src/models/system-script-info.ts index b1a282f02a..19c55abd44 100644 --- a/packages/neuron-wallet/src/models/system-script-info.ts +++ b/packages/neuron-wallet/src/models/system-script-info.ts @@ -2,22 +2,22 @@ import OutPoint from './chain/out-point' import CellDep, { DepType } from './chain/cell-dep' import NetworksService from '../services/networks' import RpcService from '../services/rpc-service' -import Script, { ScriptHashType } from './chain/script' +import { Hash, HashType, Script, utils } from '@ckb-lumos/base' export default class SystemScriptInfo { static SECP_CODE_HASH = process.env.SECP256K1_CODE_HASH! static DAO_CODE_HASH = process.env.DAO_CODE_HASH! static MULTI_SIGN_CODE_HASH = process.env.MULTISIG_CODE_HASH! - static SECP_HASH_TYPE = ScriptHashType.Type - static DAO_HASH_TYPE = ScriptHashType.Type - static MULTI_SIGN_HASH_TYPE = ScriptHashType.Type + static SECP_HASH_TYPE = 'type' as HashType + static DAO_HASH_TYPE = 'type' as HashType + static MULTI_SIGN_HASH_TYPE = 'type' as HashType - static DAO_SCRIPT_HASH = new Script( - SystemScriptInfo.DAO_CODE_HASH, - '0x', - SystemScriptInfo.DAO_HASH_TYPE - ).computeHash() + static DAO_SCRIPT: Script = { + codeHash: SystemScriptInfo.DAO_CODE_HASH, + hashType: SystemScriptInfo.DAO_HASH_TYPE, + args: '0x', + } private static instance: SystemScriptInfo static getInstance(): SystemScriptInfo { @@ -35,6 +35,10 @@ export default class SystemScriptInfo { private multiSignOutPointInfo = new Map() + public getDaoScriptHash(): Hash { + return utils.computeScriptHash(SystemScriptInfo.DAO_SCRIPT) + } + // need network url and genesisBlockHash public async getSecpCellDep( network: { remote: string; genesisHash: string } = NetworksService.getInstance().getCurrent() @@ -73,15 +77,27 @@ export default class SystemScriptInfo { } public static generateSecpScript(args: string): Script { - return new Script(SystemScriptInfo.SECP_CODE_HASH, args, SystemScriptInfo.SECP_HASH_TYPE) + return { + codeHash: SystemScriptInfo.SECP_CODE_HASH, + hashType: SystemScriptInfo.SECP_HASH_TYPE, + args, + } } public static generateDaoScript(args: string = '0x'): Script { - return new Script(SystemScriptInfo.DAO_CODE_HASH, args, SystemScriptInfo.DAO_HASH_TYPE) + return { + codeHash: SystemScriptInfo.DAO_CODE_HASH, + hashType: SystemScriptInfo.DAO_HASH_TYPE, + args, + } } public static generateMultiSignScript(args: string): Script { - return new Script(SystemScriptInfo.MULTI_SIGN_CODE_HASH, args, SystemScriptInfo.MULTI_SIGN_HASH_TYPE) + return { + codeHash: SystemScriptInfo.MULTI_SIGN_CODE_HASH, + hashType: SystemScriptInfo.MULTI_SIGN_HASH_TYPE, + args, + } } public static isSecpScript(script: Script): boolean { diff --git a/packages/neuron-wallet/src/models/transaction-size.ts b/packages/neuron-wallet/src/models/transaction-size.ts index 4bdca0deb3..8cb8a124fc 100644 --- a/packages/neuron-wallet/src/models/transaction-size.ts +++ b/packages/neuron-wallet/src/models/transaction-size.ts @@ -5,7 +5,6 @@ import Output from './chain/output' import WitnessArgs from './chain/witness-args' import Transaction from './chain/transaction' import Multisig from './multisig' -import Script, { ScriptHashType } from './chain/script' import BufferUtils from '../utils/buffer' export default class TransactionSize { @@ -37,7 +36,11 @@ export default class TransactionSize { const hash20 = '0x' + '0'.repeat(40) const sudtOutput = Output.fromObject({ capacity: '61', - lock: new Script(hash32, hash20, ScriptHashType.Type), + lock: { + codeHash: hash32, + hashType: 'type', + args: hash20, + }, }) return TransactionSize.output(sudtOutput) } @@ -48,8 +51,16 @@ export default class TransactionSize { const hash20 = '0x' + '0'.repeat(40) const sudtOutput = Output.fromObject({ capacity: '142', - lock: new Script(hash32, hash20, ScriptHashType.Type), - type: new Script(hash32, hash32, ScriptHashType.Type), + lock: { + codeHash: hash32, + hashType: 'type', + args: hash20, + }, + type: { + codeHash: hash32, + hashType: 'type', + args: hash32, + }, }) return TransactionSize.output(sudtOutput) } diff --git a/packages/neuron-wallet/src/services/addresses.ts b/packages/neuron-wallet/src/services/addresses.ts index 4c85b6c4f1..02a4f9300f 100644 --- a/packages/neuron-wallet/src/services/addresses.ts +++ b/packages/neuron-wallet/src/services/addresses.ts @@ -8,12 +8,12 @@ import { getConnection } from 'typeorm' import { TransactionsService } from '../services/tx' import CellsService from './cells' import SystemScriptInfo from '../models/system-script-info' -import Script from '../models/chain/script' import HdPublicKeyInfo from '../database/chain/entities/hd-public-key-info' 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 { Script, utils } from '@ckb-lumos/base' const MAX_ADDRESS_COUNT = 100 @@ -383,12 +383,12 @@ export default class AddressService { hashType: SystemScriptInfo.SECP_HASH_TYPE, }) const allAddressesWithBalances = addresses.map(address => { - const script = Script.fromObject({ + const script: Script = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: SystemScriptInfo.SECP_HASH_TYPE, args: address.blake160, - }) - const lockHash = script.computeHash() + } + const lockHash = utils.computeScriptHash(script) const liveBalance = liveBalances.get(lockHash) || '0' const sentBalance = sentBalances.get(lockHash) || '0' const pendingBalance = pendingBalances.get(lockHash) || '0' diff --git a/packages/neuron-wallet/src/services/anyone-can-pay.ts b/packages/neuron-wallet/src/services/anyone-can-pay.ts index 639e406aa7..7f713e7bba 100644 --- a/packages/neuron-wallet/src/services/anyone-can-pay.ts +++ b/packages/neuron-wallet/src/services/anyone-can-pay.ts @@ -12,7 +12,6 @@ import { TargetOutputNotFoundError, AcpSendSameAccountError, } from '../exceptions' -import Script from '../models/chain/script' import OutPoint from '../models/chain/out-point' import LiveCellService from './live-cell-service' import WalletService from './wallets' @@ -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 { Script } from '@ckb-lumos/base' export default class AnyoneCanPayService { public static async generateAnyoneCanPayTx( diff --git a/packages/neuron-wallet/src/services/asset-account-service.ts b/packages/neuron-wallet/src/services/asset-account-service.ts index a7a7c2b43b..58b1aa5ecc 100644 --- a/packages/neuron-wallet/src/services/asset-account-service.ts +++ b/packages/neuron-wallet/src/services/asset-account-service.ts @@ -16,14 +16,15 @@ import OutPoint from '../models/chain/out-point' import SystemScriptInfo from '../models/system-script-info' import Input from '../models/chain/input' import { MIN_CELL_CAPACITY } from '../utils/const' +import { utils } from '@ckb-lumos/base' export default class AssetAccountService { private static async getACPCells(publicKeyHash: string, tokenId: string = 'CKBytes') { const assetAccountInfo = new AssetAccountInfo() - const anyoneCanPayLockHash = assetAccountInfo.generateAnyoneCanPayScript(publicKeyHash).computeHash() + const anyoneCanPayLockHash = utils.computeScriptHash(assetAccountInfo.generateAnyoneCanPayScript(publicKeyHash)) let typeHash = null if (tokenId !== 'CKBytes') { - typeHash = assetAccountInfo.generateSudtScript(tokenId).computeHash() + typeHash = utils.computeScriptHash(assetAccountInfo.generateSudtScript(tokenId)) } const outputs = await getConnection() .getRepository(OutputEntity) @@ -56,8 +57,8 @@ export default class AssetAccountService { private static async calculateUDTAccountBalance(publicKeyHash: string, tokenId: string) { const assetAccountInfo = new AssetAccountInfo() - const anyoneCanPayLockHash = assetAccountInfo.generateAnyoneCanPayScript(publicKeyHash).computeHash() - const typeHash = assetAccountInfo.generateSudtScript(tokenId).computeHash() + const anyoneCanPayLockHash = utils.computeScriptHash(assetAccountInfo.generateAnyoneCanPayScript(publicKeyHash)) + const typeHash = utils.computeScriptHash(assetAccountInfo.generateSudtScript(tokenId)) const outputs = await getConnection() .getRepository(OutputEntity) .createQueryBuilder('output') @@ -482,7 +483,7 @@ export default class AssetAccountService { const receiverDefaultLock = addressInfos .map(info => SystemScriptInfo.generateSecpScript(info.blake160)) - .find(defaultLock => defaultLock.computeHash().slice(0, 42) === receiverLockHash20) + .find(defaultLock => utils.computeScriptHash(defaultLock).slice(0, 42) === receiverLockHash20) if (!receiverDefaultLock) { throw new Error('receiver default lock not found by receiver lock hash') diff --git a/packages/neuron-wallet/src/services/cells.ts b/packages/neuron-wallet/src/services/cells.ts index 44e0e10d84..50f5768dd2 100644 --- a/packages/neuron-wallet/src/services/cells.ts +++ b/packages/neuron-wallet/src/services/cells.ts @@ -23,13 +23,13 @@ import BufferUtils from '../utils/buffer' import LiveCell from '../models/chain/live-cell' import Output from '../models/chain/output' import SystemScriptInfo from '../models/system-script-info' -import Script, { ScriptHashType } from '../models/chain/script' import LiveCellService from './live-cell-service' import AssetAccountInfo from '../models/asset-account-info' import NFT from '../models/nft' import MultisigConfigModel from '../models/multisig-config' import MultisigOutput from '../database/chain/entities/multisig-output' import { MIN_CELL_CAPACITY } from '../utils/const' +import { HashType, Script, utils } from '@ckb-lumos/base' export interface PaginationResult { totalCount: number @@ -265,7 +265,7 @@ export default class CellsService { const acpCodehash = assetAccountInfo.getAcpCodeHash() const sudtCodehash = assetAccountInfo.getSudtCodeHash() const secp256k1LockHashes = [...blake160Hashes].map(blake160 => - SystemScriptInfo.generateSecpScript(blake160).computeHash() + utils.computeScriptHash(SystemScriptInfo.generateSecpScript(blake160)) ) const skip = (pageNo - 1) * pageSize @@ -441,7 +441,7 @@ export default class CellsService { walletId: string, lockClass: { codeHash: string - hashType: ScriptHashType + hashType: HashType } ) => { return await getConnection() @@ -473,7 +473,7 @@ export default class CellsService { private static getLiveOrSentCellByLockArgsMultisigOutput = async (lockClass: { lockArgs?: string[] codeHash: string - hashType: ScriptHashType + hashType: HashType }) => { return await getConnection() .getRepository(MultisigOutput) @@ -516,8 +516,8 @@ export default class CellsService { lockClass: { lockArgs?: string[] codeHash: string - hashType: ScriptHashType - } = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: ScriptHashType.Type }, + hashType: HashType + } = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: 'type' }, multisigConfigs: MultisigConfigModel[] = [] ): Promise<{ inputs: Input[] @@ -671,9 +671,9 @@ export default class CellsService { walletId: string, lockClass: { codeHash: string - hashType: ScriptHashType + hashType: HashType args?: string - } = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: ScriptHashType.Type } + } = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: 'type' } ): Promise => { const cellEntities: (OutputEntity | MultisigOutput)[] = await (!lockClass.args ? CellsService.getLiveOrSentCellByWalletId(walletId, lockClass) diff --git a/packages/neuron-wallet/src/services/live-cell-service.ts b/packages/neuron-wallet/src/services/live-cell-service.ts index 8c6694e935..deec6ad0b2 100644 --- a/packages/neuron-wallet/src/services/live-cell-service.ts +++ b/packages/neuron-wallet/src/services/live-cell-service.ts @@ -1,7 +1,7 @@ -import Script from '../models/chain/script' import LiveCell from '../models/chain/live-cell' import { queryIndexer } from '../block-sync-renderer/index' import { LumosCell, LumosCellQuery } from '../block-sync-renderer/sync/connector' +import { Script, utils } from '@ckb-lumos/base' export default class LiveCellService { private static instance: LiveCellService @@ -36,7 +36,7 @@ export default class LiveCellService { return null } - const typeHash = type ? type.computeHash() : '' + const typeHash = type ? utils.computeScriptHash(type) : '' for (let i = 0; i < result.length; i++) { const item = LiveCell.fromLumos(result[i]) if (type) { @@ -59,7 +59,7 @@ export default class LiveCellService { const cells = [] - const typeHash = type ? type.computeHash() : '' + const typeHash = type ? utils.computeScriptHash(type) : '' for (let i = 0; i < result.length; i++) { const item = LiveCell.fromLumos(result[i]) if (type) { diff --git a/packages/neuron-wallet/src/services/multisig.ts b/packages/neuron-wallet/src/services/multisig.ts index 64e08a260e..3e07a4b05d 100644 --- a/packages/neuron-wallet/src/services/multisig.ts +++ b/packages/neuron-wallet/src/services/multisig.ts @@ -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 { utils } from '@ckb-lumos/base' const max64Int = '0x' + 'f'.repeat(16) export default class MultisigService { @@ -95,7 +96,7 @@ export default class MultisigService { private static removeDulpicateConfig(multisigConfigs: MultisigConfig[]) { const existMultisigLockHash: Set = new Set() return multisigConfigs.filter(v => { - const multisigLockHash = Multisig.getMultisigScript(v.blake160s, v.r, v.m, v.n).computeHash() + const multisigLockHash = utils.computeScriptHash(Multisig.getMultisigScript(v.blake160s, v.r, v.m, v.n)) if (existMultisigLockHash.has(multisigLockHash)) { return false } diff --git a/packages/neuron-wallet/src/services/transaction-sender.ts b/packages/neuron-wallet/src/services/transaction-sender.ts index beb800eacf..ba1e00aec2 100644 --- a/packages/neuron-wallet/src/services/transaction-sender.ts +++ b/packages/neuron-wallet/src/services/transaction-sender.ts @@ -17,7 +17,6 @@ import OutPoint from '../models/chain/out-point' import Output from '../models/chain/output' import WitnessArgs from '../models/chain/witness-args' import Transaction from '../models/chain/transaction' -import Script from '../models/chain/script' import Multisig from '../models/multisig' import Blake2b from '../models/blake2b' import logger from '../utils/logger' @@ -685,13 +684,13 @@ export default class TransactionSender { const wallet = WalletService.getInstance().get(walletID) const address = await wallet.getNextAddress() const blake160 = AddressParser.toBlake160(address!.address) + const outputLock = { + codeHash: SystemScriptInfo.SECP_CODE_HASH, + hashType: SystemScriptInfo.SECP_HASH_TYPE, + args: blake160, + } - const output: Output = new Output( - outputCapacity.toString(), - new Script(SystemScriptInfo.SECP_CODE_HASH, blake160, SystemScriptInfo.SECP_HASH_TYPE), - undefined, - '0x' - ) + const output: Output = new Output(outputCapacity.toString(), outputLock, undefined, '0x') const outputs: Output[] = [output] diff --git a/packages/neuron-wallet/src/services/tx/transaction-generator.ts b/packages/neuron-wallet/src/services/tx/transaction-generator.ts index 701a726e92..7908107331 100644 --- a/packages/neuron-wallet/src/services/tx/transaction-generator.ts +++ b/packages/neuron-wallet/src/services/tx/transaction-generator.ts @@ -12,7 +12,6 @@ import { CapacityNotEnough, CurrentWalletNotSet, LiveCapacityNotEnough } from '. import Output from '../../models/chain/output' import Input from '../../models/chain/input' import OutPoint from '../../models/chain/out-point' -import Script, { ScriptHashType } from '../../models/chain/script' import Transaction from '../../models/chain/transaction' import WitnessArgs from '../../models/chain/witness-args' import AddressParser from '../../models/address-parser' @@ -34,6 +33,7 @@ import WalletService from '../../services/wallets' import { MIN_CELL_CAPACITY, MIN_SUDT_CAPACITY } from '../../utils/const' import AssetAccountService from '../../services/asset-account-service' import LiveCellService from '../../services/live-cell-service' +import { HashType, Script, utils } from '@ckb-lumos/base' export interface TargetOutput { address: string @@ -68,7 +68,7 @@ export class TransactionGenerator { throw new Error('NFT cell not found') } const cellDeps = [secpCellDep, nftCellDep] - const outputLock = new Script(prevOutput.lock.codeHash, prevOutput.lock.args, prevOutput.lock.hashType) + const outputLock = prevOutput.lock if (assetAccountInfo.isDefaultAnyoneCanPayScript(outputLock)) { cellDeps.push(anyoneCanPayDep) } @@ -77,7 +77,7 @@ export class TransactionGenerator { previousOutput: op, capacity: nftCell.capacity, lock: outputLock, - type: nftCell.type ? new Script(nftCell.type.codeHash, nftCell.type.args, nftCell.type.hashType) : null, + type: nftCell.type ?? null, data: nftCell.data, since: '0', }) @@ -152,8 +152,8 @@ export class TransactionGenerator { lockClass: { lockArgs?: string[] codeHash: string - hashType: ScriptHashType - } = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: ScriptHashType.Type }, + hashType: HashType + } = { codeHash: SystemScriptInfo.SECP_CODE_HASH, hashType: 'type' }, multisigConfig?: MultisigConfigModel ): Promise => { let cellDep: CellDep @@ -223,7 +223,7 @@ export class TransactionGenerator { if (hasChangeOutput) { const changeCapacity = BigInt(capacities) - needCapacities - finalFeeInt - const output = new Output(changeCapacity.toString(), Script.fromSDK(addressToScript(changeAddress))) + const output = new Output(changeCapacity.toString(), addressToScript(changeAddress)) tx.addOutput(output) } @@ -259,9 +259,7 @@ export class TransactionGenerator { const allInputs: Input[] = await CellsService.gatherAllInputs( walletId, multisigConfig - ? Script.fromSDK( - Multisig.getMultisigScript(multisigConfig.blake160s, multisigConfig.r, multisigConfig.m, multisigConfig.n) - ) + ? Multisig.getMultisigScript(multisigConfig.blake160s, multisigConfig.r, multisigConfig.m, multisigConfig.n) : undefined ) @@ -950,7 +948,7 @@ export class TransactionGenerator { cell.lockCodeHash = newACPLockScript.codeHash cell.lockHashType = newACPLockScript.hashType cell.lockArgs = newACPLockScript.args - cell.lockHash = newACPLockScript.computeHash() + cell.lockHash = utils.computeScriptHash(newACPLockScript) return cell }) @@ -1092,8 +1090,8 @@ export class TransactionGenerator { lockHash: undefined, data: BufferUtils.writeBigUInt128LE(BigInt(gatheredSudtInputResult.amount)), lock: assetAccountInfo.generateChequeScript( - receiverLockScript.computeHash(), - senderDefaultCell.lock!.computeHash() + utils.computeScriptHash(receiverLockScript), + utils.computeScriptHash(senderDefaultCell.lock!) ), }) tx.outputs.unshift(chequeCell) @@ -1131,7 +1129,7 @@ export class TransactionGenerator { const receiverLockHash20 = chequeCell.lock.args.slice(0, 42) const allAddressInfos = await AddressService.getAddressesByWalletId(walletId) const receiverAddressInfo = allAddressInfos.find(info => { - const lockHash = SystemScriptInfo.generateSecpScript(info.blake160).computeHash() + const lockHash = utils.computeScriptHash(SystemScriptInfo.generateSecpScript(info.blake160)) return lockHash.startsWith(receiverLockHash20) }) if (!receiverAddressInfo) { @@ -1408,7 +1406,7 @@ export class TransactionGenerator { throw new MigrateSudtCellNoTypeError() } const receiverAcpCell = await LiveCellService.getInstance().getOneByLockScriptAndTypeScript( - Script.fromSDK(addressToScript(acpAddress)), + addressToScript(acpAddress), inputSudtCell.type ) if (!receiverAcpCell) { diff --git a/packages/neuron-wallet/src/services/tx/transaction-service.ts b/packages/neuron-wallet/src/services/tx/transaction-service.ts index c38d3a3e03..8aed9ff9ce 100644 --- a/packages/neuron-wallet/src/services/tx/transaction-service.ts +++ b/packages/neuron-wallet/src/services/tx/transaction-service.ts @@ -18,8 +18,8 @@ import SudtTokenInfoEntity from '../../database/chain/entities/sudt-token-info' import exportTransactions from '../../utils/export-history' import RpcService from '../rpc-service' import NetworksService from '../networks' -import Script from '../../models/chain/script' import Input from '../../models/chain/input' +import { utils } from '@ckb-lumos/base' export interface TransactionsByAddressesParam { pageNo: number @@ -78,7 +78,7 @@ export class TransactionsService { let allTxHashes: string[] = [] if (type === SearchType.Address) { - const lockHashToSearch = AddressParser.parse(searchValue).computeHash() + const lockHashToSearch = utils.computeScriptHash(AddressParser.parse(searchValue)) allTxHashes = await connection .createQueryRunner() .query( @@ -522,9 +522,9 @@ export class TransactionsService { const output = inputTxMap.get(v.previousOutput.txHash)?.outputs?.[+v.previousOutput.index] if (!output) return v v.setCapacity(output.capacity) - v.setLock(Script.fromSDK(output.lock)) + v.setLock(output.lock) if (output.type) { - v.setType(Script.fromSDK(output.type)) + v.setType(output.type) } return v }) diff --git a/packages/neuron-wallet/tests/block-sync-renderer/indexer-connector.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/indexer-connector.test.ts index 488fdfb7f0..060d56a3af 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/indexer-connector.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/indexer-connector.test.ts @@ -6,7 +6,6 @@ import SystemScriptInfo from '../../src/models/system-script-info' import IndexerConnector from '../../src/block-sync-renderer/sync/indexer-connector' import type { LumosCell, LumosCellQuery } from '../../src/block-sync-renderer/sync/connector' import { flushPromises } from '../test-utils' -import { ScriptHashType } from '../../src/models/chain/script' const stubbedTipFn = jest.fn() const stubbedGetTransactionFn = jest.fn() @@ -237,7 +236,10 @@ describe('unit tests for IndexerConnector', () => { }) it('emits new transactions in batch by the next unprocessed block number', () => { expect(txObserver).toHaveBeenCalledTimes(1) - expect(txObserver).toHaveBeenCalledWith({ txHashes: [fakeTx1.transaction.hash], params: fakeTx1.transaction.blockNumber }) + expect(txObserver).toHaveBeenCalledWith({ + txHashes: [fakeTx1.transaction.hash], + params: fakeTx1.transaction.blockNumber, + }) }) }) describe('when loaded block number is not in order', () => { @@ -253,7 +255,10 @@ describe('unit tests for IndexerConnector', () => { }) it('emits new transactions in batch by the next unprocessed block number', () => { expect(txObserver).toHaveBeenCalledTimes(1) - expect(txObserver).toHaveBeenCalledWith({ txHashes: [fakeTx1.transaction.hash], params: fakeTx1.transaction.blockNumber }) + expect(txObserver).toHaveBeenCalledWith({ + txHashes: [fakeTx1.transaction.hash], + params: fakeTx1.transaction.blockNumber, + }) }) }) describe('#notifyCurrentBlockNumberProcessed', () => { @@ -448,12 +453,12 @@ describe('unit tests for IndexerConnector', () => { describe('when success', () => { const query: LumosCellQuery = { lock: { - hashType: ScriptHashType.Data, + hashType: 'data', codeHash: '0xcode', args: '0x', }, type: { - hashType: ScriptHashType.Data, + hashType: 'data', codeHash: '0xcode', args: '0x', }, @@ -492,12 +497,12 @@ describe('unit tests for IndexerConnector', () => { describe('when handling concurrent requests', () => { const query1: LumosCellQuery = { lock: { - hashType: ScriptHashType.Data, + hashType: 'data', codeHash: '0xcode', args: '0x1', }, type: { - hashType: ScriptHashType.Data, + hashType: 'data', codeHash: '0xcode', args: '0x1', }, @@ -505,12 +510,12 @@ describe('unit tests for IndexerConnector', () => { } const query2: LumosCellQuery = { lock: { - hashType: ScriptHashType.Type, + hashType: 'type', codeHash: '0xcode', args: '0x2', }, type: { - hashType: ScriptHashType.Type, + hashType: 'type', codeHash: '0xcode', args: '0x2', }, diff --git a/packages/neuron-wallet/tests/block-sync-renderer/light-connector.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/light-connector.test.ts index 779a7f366e..a57df7304f 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/light-connector.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/light-connector.test.ts @@ -1,8 +1,8 @@ -import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils' import LightConnector from '../../src/block-sync-renderer/sync/light-connector' import SyncProgress from '../../src/database/chain/entities/sync-progress' import HexUtils from '../../src/utils/hex' import AddressMeta from '../../src/database/address/meta' +import { utils } from '@ckb-lumos/base' const getSyncStatusMock = jest.fn() const getCurrentWalletMinBlockNumberMock = jest.fn() @@ -56,13 +56,15 @@ jest.mock('../../src/services/sync-progress', () => { static updateSyncStatus: any = (hash: string, update: any) => updateSyncStatusMock(hash, update) static updateSyncProgressFlag: any = (walletIds: string[]) => updateSyncProgressFlagMock(walletIds) static getWalletMinBlockNumber: any = () => getWalletMinBlockNumberMock() - static removeByHashesAndAddressType: any = (type: number, scripts: CKBComponents.Script[]) => removeByHashesAndAddressType(type, scripts) + static removeByHashesAndAddressType: any = (type: number, scripts: CKBComponents.Script[]) => + removeByHashesAndAddressType(type, scripts) + static getOtherTypeSyncProgress: any = () => getOtherTypeSyncProgressMock() } }) jest.mock('../../src/utils/ckb-rpc', () => ({ - LightRPC: function() { + LightRPC: function () { return { setScripts: setScriptsMock, getScripts: getScriptsMock, @@ -70,11 +72,11 @@ jest.mock('../../src/utils/ckb-rpc', () => ({ getTransactions: getTransactionsMock, createBatchRequest: () => ({ exec: createBatchRequestMock }), } - } + }, })) jest.mock('../../src/services/multisig', () => ({ - getMultisigConfigForLight: () => getMultisigConfigForLightMock() + getMultisigConfigForLight: () => getMultisigConfigForLightMock(), })) jest.mock('../../src/services/wallets', () => ({ @@ -83,21 +85,21 @@ jest.mock('../../src/services/wallets', () => ({ getCurrent: walletGetCurrentMock, getAll: walletGetAllMock, } - } + }, })) jest.mock('timers/promises', () => ({ scheduler: { wait: (delay: number) => schedulerWaitMock(delay), - } + }, })) const script: CKBComponents.Script = { args: '0x403f0d4e833b2a8d372772a63facaa310dfeef92', codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', - hashType: 'type' + hashType: 'type', } -const scriptHash = scriptToHash(script) +const scriptHash = utils.computeScriptHash(script) const address = 'ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq2q8ux5aqem92xnwfmj5cl6e233phlwlysqhjx5w' describe('test light connector', () => { @@ -135,7 +137,7 @@ describe('test light connector', () => { const syncProgress = SyncProgress.fromObject({ script, scriptType: 'lock', - walletId: 'walletId1' + walletId: 'walletId1', }) syncProgress.blockStartNumber = 0 syncProgress.blockEndNumber = 1 @@ -152,11 +154,11 @@ describe('test light connector', () => { script: { codeHash: syncProgress.codeHash, hashType: syncProgress.hashType, - args: syncProgress.args + args: syncProgress.args, }, blockRange: [HexUtils.toHex(syncProgress.blockStartNumber), HexUtils.toHex(syncProgress.blockEndNumber)], scriptType: syncProgress.scriptType, - cursor: syncProgress.cursor + cursor: syncProgress.cursor, }) }) it('some script sync cursor is not empty but is in sync queue', async () => { @@ -164,7 +166,7 @@ describe('test light connector', () => { const syncProgress = SyncProgress.fromObject({ script, scriptType: 'lock', - walletId: 'walletId1' + walletId: 'walletId1', }) syncProgress.blockStartNumber = 0 syncProgress.blockEndNumber = 1 @@ -183,15 +185,17 @@ describe('test light connector', () => { expect(connector.syncQueue.length()).toBe(0) }) it('some script sync to new block', async () => { - getScriptsMock.mockResolvedValue([{ - script, - scriptType: 'lock', - blockNumber: '0xaa' - }]) + getScriptsMock.mockResolvedValue([ + { + script, + scriptType: 'lock', + blockNumber: '0xaa', + }, + ]) const syncProgress = SyncProgress.fromObject({ script, scriptType: 'lock', - walletId: 'walletId1' + walletId: 'walletId1', }) syncProgress.blockStartNumber = 0 syncProgress.blockEndNumber = 1 @@ -207,39 +211,41 @@ describe('test light connector', () => { script: { codeHash: syncProgress.codeHash, hashType: syncProgress.hashType, - args: syncProgress.args + args: syncProgress.args, }, blockRange: [HexUtils.toHex(syncProgress.blockEndNumber), HexUtils.toHex('0xaa')], scriptType: syncProgress.scriptType, - cursor: syncProgress.cursor + cursor: syncProgress.cursor, }) }), - it('some script sync to new block but is in sync queue', async () => { - getScriptsMock.mockResolvedValue([{ - script, - scriptType: 'lock', - blockNumber: '0xaa' - }]) - const syncProgress = SyncProgress.fromObject({ - script, - scriptType: 'lock', - walletId: 'walletId1' + it('some script sync to new block but is in sync queue', async () => { + getScriptsMock.mockResolvedValue([ + { + script, + scriptType: 'lock', + blockNumber: '0xaa', + }, + ]) + const syncProgress = SyncProgress.fromObject({ + script, + scriptType: 'lock', + walletId: 'walletId1', + }) + syncProgress.blockStartNumber = 0 + syncProgress.blockEndNumber = 1 + getAllSyncStatusToMapMock.mockResolvedValue(new Map([[scriptHash, syncProgress]])) + const connector = new LightConnector([], '') + // @ts-ignore: private-method + connector.syncInQueue.set(scriptHash, {}) + // @ts-ignore: private-method + connector.subscribeSync = jest.fn() + // @ts-ignore: private-method + connector.syncQueue.pause() + // @ts-ignore: private-method + await connector.synchronize() + // @ts-ignore: private-method + expect(connector.syncQueue.length()).toBe(0) }) - syncProgress.blockStartNumber = 0 - syncProgress.blockEndNumber = 1 - getAllSyncStatusToMapMock.mockResolvedValue(new Map([[scriptHash, syncProgress]])) - const connector = new LightConnector([], '') - // @ts-ignore: private-method - connector.syncInQueue.set(scriptHash, {}) - // @ts-ignore: private-method - connector.subscribeSync = jest.fn() - // @ts-ignore: private-method - connector.syncQueue.pause() - // @ts-ignore: private-method - await connector.synchronize() - // @ts-ignore: private-method - expect(connector.syncQueue.length()).toBe(0) - }) }) describe('test subscribeSync', () => { @@ -254,7 +260,7 @@ describe('test light connector', () => { // @ts-ignore: private-method expect(connector.blockTipsSubject.next).toBeCalledWith({ cacheTipNumber: 100, - indexerTipNumber: 170 + indexerTipNumber: 170, }) }) }) @@ -273,52 +279,118 @@ describe('test light connector', () => { await connect.initSyncProgress([{ walletId: 'walletId', script, addressType: 1, scriptType: 'lock' }]) expect(getScriptsMock).toBeCalledTimes(1) expect(setScriptsMock).toBeCalledWith([ - { script, scriptType: 'lock', walletId: 'walletId', blockNumber: '0x0', addressType: 1, }, + { script, scriptType: 'lock', walletId: 'walletId', blockNumber: '0x0', addressType: 1 }, ]) }) it('there is not exist sync scripts with light client', async () => { getScriptsMock.mockResolvedValue([{ script, blockNumber: '0xaa' }]) - const addressMeta = AddressMeta.fromObject({ walletId: 'walletId', address, path: '', addressIndex: 10, addressType: 0, blake160: script.args }) + const addressMeta = AddressMeta.fromObject({ + walletId: 'walletId', + address, + path: '', + addressIndex: 10, + addressType: 0, + blake160: script.args, + }) const connect = new LightConnector([addressMeta], '') //@ts-ignore await connect.initSyncProgress() expect(setScriptsMock).toBeCalledWith([ - { script: addressMeta.generateDefaultLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, - { script: addressMeta.generateACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0x0' }, - { script: addressMeta.generateLegacyACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0x0' }, + { + script: addressMeta.generateDefaultLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, + { + script: addressMeta.generateACPLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0x0', + }, + { + script: addressMeta.generateLegacyACPLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0x0', + }, ]) expect(resetSyncProgressMock).toBeCalledWith([ - { script: addressMeta.generateDefaultLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId' }, - { script: addressMeta.generateACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId' }, - { script: addressMeta.generateLegacyACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId' }, + { script: addressMeta.generateDefaultLockScript(), scriptType: 'lock', walletId: 'walletId' }, + { script: addressMeta.generateACPLockScript(), scriptType: 'lock', walletId: 'walletId' }, + { script: addressMeta.generateLegacyACPLockScript(), scriptType: 'lock', walletId: 'walletId' }, ]) expect(updateSyncProgressFlagMock).toBeCalledWith(['walletId']) }) it('set new script with the synced min block number', async () => { getScriptsMock.mockResolvedValue([]) - const addressMeta = AddressMeta.fromObject({ walletId: 'walletId', address, path: '', addressIndex: 10, addressType: 0, blake160: script.args }) - getWalletMinBlockNumberMock.mockResolvedValue({ 'walletId': 170}) + const addressMeta = AddressMeta.fromObject({ + walletId: 'walletId', + address, + path: '', + addressIndex: 10, + addressType: 0, + blake160: script.args, + }) + getWalletMinBlockNumberMock.mockResolvedValue({ walletId: 170 }) const connect = new LightConnector([addressMeta], '') //@ts-ignore await connect.initSyncProgress() expect(setScriptsMock).toBeCalledWith([ - { script: addressMeta.generateDefaultLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, - { script: addressMeta.generateACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, - { script: addressMeta.generateLegacyACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, + { + script: addressMeta.generateDefaultLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, + { + script: addressMeta.generateACPLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, + { + script: addressMeta.generateLegacyACPLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, ]) }) it('set new script with start block number in wallet', async () => { getScriptsMock.mockResolvedValue([]) - const addressMeta = AddressMeta.fromObject({ walletId: 'walletId', address, path: '', addressIndex: 10, addressType: 0, blake160: script.args }) + const addressMeta = AddressMeta.fromObject({ + walletId: 'walletId', + address, + path: '', + addressIndex: 10, + addressType: 0, + blake160: script.args, + }) getWalletMinBlockNumberMock.mockResolvedValue({}) walletGetAllMock.mockReturnValue([{ id: 'walletId', startBlockNumberInLight: '0xaa' }]) const connect = new LightConnector([addressMeta], '') //@ts-ignore await connect.initSyncProgress() expect(setScriptsMock).toBeCalledWith([ - { script: addressMeta.generateDefaultLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, - { script: addressMeta.generateACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, - { script: addressMeta.generateLegacyACPLockScript().toSDK(), scriptType: 'lock', walletId: 'walletId', blockNumber: '0xaa' }, + { + script: addressMeta.generateDefaultLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, + { + script: addressMeta.generateACPLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, + { + script: addressMeta.generateLegacyACPLockScript(), + scriptType: 'lock', + walletId: 'walletId', + blockNumber: '0xaa', + }, ]) }) }) @@ -362,8 +434,17 @@ describe('test light connector', () => { const connect = new LightConnector([], '') //@ts-ignore await connect.syncNextWithScript({ script, scriptType: 'lock', blockRange: ['0xaa', '0xbb'] }) - expect(getTransactionsMock).toBeCalledWith({ script, blockRange: ['0xaa', '0xbb'], scriptType: 'lock' }, 'asc', '0x64', undefined) - expect(updateSyncStatusMock).toBeCalledWith(scriptHash, { blockStartNumber: 187, blockEndNumber: 187, cursor: undefined }) + expect(getTransactionsMock).toBeCalledWith( + { script, blockRange: ['0xaa', '0xbb'], scriptType: 'lock' }, + 'asc', + '0x64', + undefined + ) + expect(updateSyncStatusMock).toBeCalledWith(scriptHash, { + blockStartNumber: 187, + blockEndNumber: 187, + cursor: undefined, + }) }) it('there are some txs in blockRange but no more', async () => { const syncProgress = SyncProgress.fromObject({ script, scriptType: 'lock', walletId: 'walletId' }) @@ -421,7 +502,9 @@ describe('test light connector', () => { const connect = new LightConnector([], '') //@ts-ignore connect.initSync = mockFn - mockFn.mockImplementation(() => { throw new Error('error') }) + mockFn.mockImplementation(() => { + throw new Error('error') + }) expect(connect.connect()).rejects.toThrowError(new Error('error')) }) }) @@ -438,7 +521,7 @@ describe('test light connector', () => { }) describe('test notifyCurrentBlockNumberProcessed', () => { - it ('hash is not in syncInQueue', async () => { + it('hash is not in syncInQueue', async () => { const connect = new LightConnector([], '') const mockFn = jest.fn() //@ts-ignore @@ -447,7 +530,7 @@ describe('test light connector', () => { expect(updateSyncStatusMock).toBeCalledTimes(0) expect(mockFn).toBeCalledTimes(1) }) - it ('hash is in syncInQueue', async () => { + it('hash is in syncInQueue', async () => { const connect = new LightConnector([], '') //@ts-ignore connect.subscribeSync = jest.fn() diff --git a/packages/neuron-wallet/tests/block-sync-renderer/queue.test.ts b/packages/neuron-wallet/tests/block-sync-renderer/queue.test.ts index c510304219..98aa6c5aed 100644 --- a/packages/neuron-wallet/tests/block-sync-renderer/queue.test.ts +++ b/packages/neuron-wallet/tests/block-sync-renderer/queue.test.ts @@ -1,5 +1,5 @@ import { Subject } from 'rxjs' -import { Tip } from '@ckb-lumos/base' +import { Tip, utils } from '@ckb-lumos/base' import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils' import { AddressType } from '../../src/models/keys/address' import SystemScriptInfo from '../../src/models/system-script-info' @@ -10,7 +10,6 @@ import TxStatus, { TxStatusType } from '../../src/models/chain/tx-status' import Input from '../../src/models/chain/input' import Output from '../../src/models/chain/output' import OutPoint from '../../src/models/chain/out-point' -import Script, { ScriptHashType } from '../../src/models/chain/script' import { flushPromises } from '../test-utils' import AssetAccountInfo from '../../src/models/asset-account-info' import Multisig from '../../src/models/multisig' @@ -70,7 +69,7 @@ const generateFakeTx = (id: string, publicKeyHash: string = '0x') => { fakeTx.outputs = [ Output.fromObject({ capacity: '1', - lock: Script.fromObject({ hashType: ScriptHashType.Type, codeHash: '0x' + id.repeat(64), args: publicKeyHash }), + lock: { hashType: 'type', codeHash: '0x' + id.repeat(64), args: publicKeyHash }, }), ] fakeTx.blockNumber = '0x1' @@ -101,7 +100,7 @@ describe('queue', () => { const fakeWalletId = 'w1' const addressInfo: Address = { address, - blake160: '0xfakeblake160', + blake160: `0x${'0'.repeat(40)}`, walletId: fakeWalletId, path: '', addressType: AddressType.Receiving, @@ -123,7 +122,7 @@ describe('queue', () => { jest.useFakeTimers('legacy') stubbedBlockTipsSubject = new Subject() - stubbedTransactionsSubject = new Subject<{ txHashes: CKBComponents.Hash[], params: unknown }>() + stubbedTransactionsSubject = new Subject<{ txHashes: CKBComponents.Hash[]; params: unknown }>() const stubbedIndexerConnector = jest.fn().mockImplementation((...args) => { stubbedIndexerConnectorConstructor(...args) return { @@ -175,11 +174,11 @@ describe('queue', () => { return { createBatchRequest() { return { - exec: stubbedRPCCreateBatchRequestExecFn + exec: stubbedRPCCreateBatchRequestExecFn, } - } + }, } - } + }, } }) const Queue = require('../../src/block-sync-renderer/sync/queue').default @@ -223,10 +222,17 @@ describe('queue', () => { beforeEach(() => { stubbedAddressesFn.mockResolvedValue([true, addresses.map(addressMeta => addressMeta.address), []]) stubbedGetTransactionFn.mockResolvedValue(fakeTxWithStatus1) - stubbedRPCCreateBatchRequestExecFn - .mockResolvedValueOnce(fakeTxs) - .mockResolvedValueOnce(fakeTxs.map(v => ({ ...fakeBlockHeader, timestamp: v.transaction.timestamp, number: v.transaction.blockNumber }))) - stubbedTransactionsSubject.next({ txHashes: fakeTxs.map(v => v.transaction.hash), params: fakeTxs[0].transaction.blockNumber }) + stubbedRPCCreateBatchRequestExecFn.mockResolvedValueOnce(fakeTxs).mockResolvedValueOnce( + fakeTxs.map(v => ({ + ...fakeBlockHeader, + timestamp: v.transaction.timestamp, + number: v.transaction.blockNumber, + })) + ) + stubbedTransactionsSubject.next({ + txHashes: fakeTxs.map(v => v.transaction.hash), + params: fakeTxs[0].transaction.blockNumber, + }) }) describe('when saving transactions is succeeded', () => { beforeEach(flushPromises) @@ -239,7 +245,7 @@ describe('queue', () => { tx.timestamp = BigInt(fakeTxWithStatus2.transaction.timestamp!).toString() expect(stubbedTxAddressFinderConstructor).toHaveBeenCalledWith( lockHashes, - [new AssetAccountInfo().generateAnyoneCanPayScript(addressInfo.blake160).computeHash()], + [utils.computeScriptHash(new AssetAccountInfo().generateAnyoneCanPayScript(addressInfo.blake160))], tx, [Multisig.hash([addressInfo.blake160])] ) @@ -250,11 +256,14 @@ describe('queue', () => { tx.blockHash = fakeTxWithStatus2.txStatus.blockHash! tx.blockNumber = BigInt(fakeTxWithStatus2.transaction.blockNumber!).toString() tx.timestamp = BigInt(fakeTxWithStatus2.transaction.timestamp!).toString() - expect(stubbedSaveFetchFn).toHaveBeenCalledWith(tx, new Set([ - addressInfo.blake160, - Multisig.hash([addressInfo.blake160]), - SystemScriptInfo.generateSecpScript(addressInfo.blake160).computeHash().slice(0, 42), - ])) + expect(stubbedSaveFetchFn).toHaveBeenCalledWith( + tx, + new Set([ + addressInfo.blake160, + Multisig.hash([addressInfo.blake160]), + utils.computeScriptHash(SystemScriptInfo.generateSecpScript(addressInfo.blake160)).slice(0, 42), + ]) + ) } }) it('checks and generate new addresses', () => { @@ -276,10 +285,17 @@ describe('queue', () => { const err = new Error() beforeEach(async () => { stubbedSaveFetchFn.mockRejectedValueOnce(err) - stubbedRPCCreateBatchRequestExecFn - .mockResolvedValueOnce(fakeTxs) - .mockResolvedValueOnce(fakeTxs.map(v => ({ ...fakeBlockHeader, timestamp: v.transaction.timestamp, number: v.transaction.blockNumber }))) - stubbedTransactionsSubject.next({ txHashes: fakeTxs.map(v => v.transaction.hash), params: fakeTxs[0].transaction.blockNumber }) + stubbedRPCCreateBatchRequestExecFn.mockResolvedValueOnce(fakeTxs).mockResolvedValueOnce( + fakeTxs.map(v => ({ + ...fakeBlockHeader, + timestamp: v.transaction.timestamp, + number: v.transaction.blockNumber, + })) + ) + stubbedTransactionsSubject.next({ + txHashes: fakeTxs.map(v => v.transaction.hash), + params: fakeTxs[0].transaction.blockNumber, + }) await flushPromises() }) it('handles the exception', async () => { diff --git a/packages/neuron-wallet/tests/controllers/multisig.test.ts b/packages/neuron-wallet/tests/controllers/multisig.test.ts index be977b1c88..bc2691f19d 100644 --- a/packages/neuron-wallet/tests/controllers/multisig.test.ts +++ b/packages/neuron-wallet/tests/controllers/multisig.test.ts @@ -23,9 +23,9 @@ jest.mock('services/wallets', () => ({ return { getCurrent() { return jest.fn() - } + }, } - } + }, })) jest.mock('../../src/services/multisig') diff --git a/packages/neuron-wallet/tests/controllers/sudt.test.ts b/packages/neuron-wallet/tests/controllers/sudt.test.ts index 44ab0f3347..e820de2f4f 100644 --- a/packages/neuron-wallet/tests/controllers/sudt.test.ts +++ b/packages/neuron-wallet/tests/controllers/sudt.test.ts @@ -1,5 +1,4 @@ import LiveCell from '../../src/models/chain/live-cell' -import Script, { ScriptHashType } from '../../src/models/chain/script' import { ResponseCode } from '../../src/utils/const' describe('SUDTController', () => { @@ -63,8 +62,8 @@ describe('SUDTController', () => { 'txHash', '0', '10000', - Script.fromObject({ codeHash: '', args: '', hashType: ScriptHashType.Type }), - Script.fromObject({ codeHash: '', args: '', hashType: ScriptHashType.Type }), + { codeHash: '0x' + '0'.repeat(64), args: '0x', hashType: 'type' }, + { codeHash: '0x' + '0'.repeat(64), args: '0x', hashType: 'type' }, '0x080a456972632d320a455432' ) beforeEach(async () => { diff --git a/packages/neuron-wallet/tests/models/address-parser.test.ts b/packages/neuron-wallet/tests/models/address-parser.test.ts index 74890eb1a2..e7ce836808 100644 --- a/packages/neuron-wallet/tests/models/address-parser.test.ts +++ b/packages/neuron-wallet/tests/models/address-parser.test.ts @@ -1,39 +1,38 @@ import AddressParser from '../../src/models/address-parser' import AssetAccountInfo from '../../src/models/asset-account-info' -import { ScriptHashType } from '../../src/models/chain/script' describe('AddressParser', () => { const fullAddressInfo = { address: 'ckb1qjda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xw3vumhs9nvu786dj9p0q5elx66t24n3kxgj53qks', codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0xb39bbc0b3673c7d36450bc14cfcdad2d559c6c64', - hashType: ScriptHashType.Type, + hashType: 'type', } const shortAddressInfo = { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0x36c329ed630d6ce750712a477543672adab57f4c', - hashType: ScriptHashType.Type, + hashType: 'type', address: 'ckt1qyqrdsefa43s6m882pcj53m4gdnj4k440axqswmu83', } const multiSignAddressInfo = { address: 'ckb1qyq5lv479ewscx3ms620sv34pgeuz6zagaaqklhtgg', - hashType: ScriptHashType.Type, + hashType: 'type', args: '0x4fb2be2e5d0c1a3b8694f832350a33c1685d477a', codeHash: '0x5c5069eb0857efc65e1bca0c07df34c31663b3622fd3876c876320fc9634e2a8', } const shortACPAddressInfo = { args: '0x4fb2be2e5d0c1a3b8694f832350a33c1685d477a', - hashType: ScriptHashType.Type, + hashType: 'type', address: 'ckb1qypylv479ewscx3ms620sv34pgeuz6zagaaqvrugu7', } const newFullVersionAddressInfo = { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0xb39bbc0b3673c7d36450bc14cfcdad2d559c6c64', - hashType: ScriptHashType.Type, + hashType: 'type', address: 'ckb1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqdnnw7qkdnnclfkg59uzn8umtfd2kwxceqxwquc4', } // @ts-ignore private property diff --git a/packages/neuron-wallet/tests/models/asset-account-info.test.ts b/packages/neuron-wallet/tests/models/asset-account-info.test.ts index 9a35c45a2b..f52449797a 100644 --- a/packages/neuron-wallet/tests/models/asset-account-info.test.ts +++ b/packages/neuron-wallet/tests/models/asset-account-info.test.ts @@ -1,9 +1,9 @@ import AssetAccountInfo from '../../src/models/asset-account-info' import CellDep, { DepType } from '../../src/models/chain/cell-dep' import OutPoint from '../../src/models/chain/out-point' -import { ScriptHashType } from '../../src/models/chain/script' import { AddressType } from '../../src/models/keys/address' import AddressMeta from '../../src/database/address/meta' +import { utils } from '@ckb-lumos/base' describe('AssetAccountInfo', () => { const testnetSudtInfo = { @@ -12,7 +12,7 @@ describe('AssetAccountInfo', () => { DepType.Code ), codeHash: '0x48dbf59b4c7ee1547238021b4869bceedf4eea6b43772e5d66ef8865b6ae7212', - hashType: ScriptHashType.Data, + hashType: 'data', } const testnetAnyoneCanPayInfo = { @@ -64,8 +64,8 @@ describe('AssetAccountInfo', () => { blake160: '0xe2193df51d78411601796b35b17b4f8f2cd85bd1', }) const chequeScript = assetAccountInfo.generateChequeScript( - receiverAddressInfo.generateDefaultLockScript().computeHash(), - senderAddressInfo.generateDefaultLockScript().computeHash() + utils.computeScriptHash(receiverAddressInfo.generateDefaultLockScript()), + utils.computeScriptHash(senderAddressInfo.generateDefaultLockScript()) ) describe('receiver address is ordered first', () => { const addressInfos = [receiverAddressInfo, senderAddressInfo] diff --git a/packages/neuron-wallet/tests/models/chain/live-cell.test.ts b/packages/neuron-wallet/tests/models/chain/live-cell.test.ts index ac52ee6359..b9d1429656 100644 --- a/packages/neuron-wallet/tests/models/chain/live-cell.test.ts +++ b/packages/neuron-wallet/tests/models/chain/live-cell.test.ts @@ -1,6 +1,6 @@ -import Script, { ScriptHashType } from '../../../src/models/chain/script' +import { HashType } from '@ckb-lumos/base' import { LumosCell } from '../../../src/block-sync-renderer/sync/connector' -import LiveCell from "../../../src/models/chain/live-cell" +import LiveCell from '../../../src/models/chain/live-cell' describe('LiveCell Test', () => { const INITIAL_DATA = { @@ -9,12 +9,12 @@ describe('LiveCell Test', () => { capacity: '0x2', lock: { codeHash: '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - hashType: ScriptHashType.Data, + hashType: 'data' as HashType, args: '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', }, type: { codeHash: '0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', - hashType: ScriptHashType.Data1, + hashType: 'data1' as HashType, args: '0xdddddddddddddddddddddddddddddddddddddddd', }, data: '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', @@ -27,8 +27,8 @@ describe('LiveCell Test', () => { INITIAL_DATA.txHash, INITIAL_DATA.outputIndex, INITIAL_DATA.capacity, - new Script(INITIAL_DATA.lock.codeHash, INITIAL_DATA.lock.args, INITIAL_DATA.lock.hashType), - new Script(INITIAL_DATA.type.codeHash, INITIAL_DATA.type.args, INITIAL_DATA.type.hashType), + INITIAL_DATA.lock, + INITIAL_DATA.type, INITIAL_DATA.data ) }) @@ -79,7 +79,7 @@ describe('LiveCell Test', () => { INITIAL_DATA.txHash, INITIAL_DATA.outputIndex, INITIAL_DATA.capacity, - new Script(INITIAL_DATA.lock.codeHash, INITIAL_DATA.lock.args, INITIAL_DATA.lock.hashType), + INITIAL_DATA.lock, null, INITIAL_DATA.data ) diff --git a/packages/neuron-wallet/tests/models/chain/output.test.ts b/packages/neuron-wallet/tests/models/chain/output.test.ts index 16444eaf06..638dbd7767 100644 --- a/packages/neuron-wallet/tests/models/chain/output.test.ts +++ b/packages/neuron-wallet/tests/models/chain/output.test.ts @@ -1,12 +1,12 @@ +import { Script } from '@ckb-lumos/base' import Output from '../../../src/models/chain/output' -import Script, { ScriptHashType } from '../../../src/models/chain/script' describe('Output', () => { - const lockScript = new Script( - '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', - '0x36c329ed630d6ce750712a477543672adab57f4c', - ScriptHashType.Type - ) + const lockScript: Script = { + codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', + hashType: 'type', + args: '0x36c329ed630d6ce750712a477543672adab57f4c', + } const output = new Output('1000', lockScript, undefined, '0x') const outputWithType = new Output('1000', lockScript, lockScript, '0x') const outputWithData = new Output('1000', lockScript, undefined, '0x1234') diff --git a/packages/neuron-wallet/tests/models/chain/script.test.ts b/packages/neuron-wallet/tests/models/chain/script.test.ts deleted file mode 100644 index 86c6db9af7..0000000000 --- a/packages/neuron-wallet/tests/models/chain/script.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import Script, { ScriptHashType } from '../../../src/models/chain/script' - -describe('Script', () => { - const codeHash = '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8' - const args = '0x36c329ed630d6ce750712a477543672adab57f4c' - const hashType = ScriptHashType.Type - - const script = new Script(codeHash, args, hashType) - const expectedLockHash = '0x1f2615a8dde4e28ca736ff763c2078aff990043f4cbf09eb4b3a58a140a0862d' - - it('new', () => { - expect(script.codeHash).toEqual(codeHash) - expect(script.args).toEqual(args) - expect(script.hashType).toEqual(hashType) - }) - - it('computeHash', () => { - const hash = script.computeHash() - expect(hash).toEqual(expectedLockHash) - }) - - it('calculateBytesize', () => { - expect(script.calculateBytesize()).toEqual(53) - }) - - it('toSDK', () => { - const i = script.toSDK() - expect(i.codeHash).toEqual(script.codeHash) - expect(i.args).toEqual(script.args) - expect(i.hashType).toEqual(script.hashType) - }) - - it('fromSDK', () => { - const s = Script.fromSDK({ - codeHash, - args, - hashType, - }) - expect(s.codeHash).toEqual(script.codeHash) - expect(s.args).toEqual(script.args) - expect(s.hashType).toEqual(script.hashType) - }) -}) diff --git a/packages/neuron-wallet/tests/models/chain/transaction.test.ts b/packages/neuron-wallet/tests/models/chain/transaction.test.ts index 6d92ccdfdb..976449f4fb 100644 --- a/packages/neuron-wallet/tests/models/chain/transaction.test.ts +++ b/packages/neuron-wallet/tests/models/chain/transaction.test.ts @@ -1,6 +1,5 @@ import Transaction, { TransactionStatus } from '../../../src/models/chain/transaction' import CellDep, { DepType } from '../../../src/models/chain/cell-dep' -import Script, { ScriptHashType } from '../../../src/models/chain/script' import Output, { OutputStatus } from '../../../src/models/chain/output' import WitnessArgs from '../../../src/models/chain/witness-args' import OutPoint from '../../../src/models/chain/out-point' @@ -19,8 +18,16 @@ describe('Transaction', () => { Output.fromObject({ capacity: '1000', data: '0x', - lock: new Script(hash, '0x', ScriptHashType.Type), - type: new Script(hash, '0x00', ScriptHashType.Type), + lock: { + codeHash: hash, + args: '0x', + hashType: 'type', + }, + type: { + codeHash: hash, + args: '0x00', + hashType: 'type', + }, outPoint: new OutPoint(hash, '0'), status: OutputStatus.Live, daoData: '0x', diff --git a/packages/neuron-wallet/tests/models/transaction-size.test.ts b/packages/neuron-wallet/tests/models/transaction-size.test.ts index de105ce411..53b18001fd 100644 --- a/packages/neuron-wallet/tests/models/transaction-size.test.ts +++ b/packages/neuron-wallet/tests/models/transaction-size.test.ts @@ -1,6 +1,5 @@ import TransactionSize from '../../src/models/transaction-size' import HexUtils from '../../src/utils/hex' -import Script, { ScriptHashType } from '../../src/models/chain/script' import WitnessArgs from '../../src/models/chain/witness-args' import Transaction from '../../src/models/chain/transaction' import Output from '../../src/models/chain/output' @@ -8,12 +7,16 @@ import Output from '../../src/models/chain/output' describe('TransactionSize', () => { const output = Output.fromObject({ capacity: '0x174876e800', - lock: new Script( - '0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88', - '0x59a27ef3ba84f061517d13f42cf44ed020610061', - ScriptHashType.Type - ), - type: new Script('0xece45e0979030e2f8909f76258631c42333b1e906fd9701ec3600a464a90b8f6', '0x', ScriptHashType.Data), + lock: { + codeHash: '0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88', + args: '0x59a27ef3ba84f061517d13f42cf44ed020610061', + hashType: 'data', + }, + type: { + codeHash: '0xece45e0979030e2f8909f76258631c42333b1e906fd9701ec3600a464a90b8f6', + args: '0x', + hashType: 'data', + }, }) const witnessArgs = new WitnessArgs('', '0x', '') diff --git a/packages/neuron-wallet/tests/services/address.test.ts b/packages/neuron-wallet/tests/services/address.test.ts index 67b2d59fc4..9453d3c4f0 100644 --- a/packages/neuron-wallet/tests/services/address.test.ts +++ b/packages/neuron-wallet/tests/services/address.test.ts @@ -11,6 +11,7 @@ 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 { Script, utils } from '@ckb-lumos/base' const walletId = '1' const extendedKey = new AccountExtendedPublicKey( @@ -28,7 +29,7 @@ const randomHex = (length: number = 64): string => { return `0x${str}` } -const generateCell = (capacity: string, lockScript: any, status: OutputStatus) => { +const generateCell = (capacity: string, lockScript: Script, status: OutputStatus) => { const output = new OutputEntity() output.outPointTxHash = randomHex() output.outPointIndex = '0' @@ -36,7 +37,7 @@ const generateCell = (capacity: string, lockScript: any, status: OutputStatus) = output.lockCodeHash = lockScript.codeHash output.lockArgs = lockScript.args output.lockHashType = lockScript.hashType - output.lockHash = lockScript.computeHash() + output.lockHash = utils.computeScriptHash(lockScript) output.status = status output.hasData = false 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 0178c0311b..5d1807673f 100644 --- a/packages/neuron-wallet/tests/services/asset-account-service.test.ts +++ b/packages/neuron-wallet/tests/services/asset-account-service.test.ts @@ -17,9 +17,9 @@ import { AddressType } from '../../src/models/keys/address' import OutPoint from '../../src/models/chain/out-point' import { when } from 'jest-when' import SystemScriptInfo from '../../src/models/system-script-info' -import Script from '../../src/models/chain/script' import Input from '../../src/models/chain/input' import { keyInfos } from '../setupAndTeardown/public-key-info.fixture' +import { Script, utils } from '@ckb-lumos/base' const stubbedWalletServiceGet = jest.fn() const stubbedGenerateClaimChequeTx = jest.fn() @@ -72,7 +72,7 @@ const generateOutput = ( outputEntity.lockCodeHash = lockToUse.codeHash outputEntity.lockArgs = lockToUse.args outputEntity.lockHashType = lockToUse.hashType - outputEntity.lockHash = lockToUse.computeHash() + outputEntity.lockHash = utils.computeScriptHash(lockToUse) outputEntity.status = status outputEntity.data = customData || '0x' @@ -82,7 +82,7 @@ const generateOutput = ( outputEntity.typeCodeHash = type.codeHash outputEntity.typeArgs = type.args outputEntity.typeHashType = type.hashType - outputEntity.typeHash = type.computeHash() + outputEntity.typeHash = utils.computeScriptHash(type) outputEntity.data = BufferUtils.writeBigUInt128LE(BigInt(tokenAmount)) } const tx = new TransactionEntity() @@ -770,7 +770,7 @@ describe('AssetAccountService', () => { }) describe('checkAndDeleteWhenFork', () => { - const anyoneCanPayLockHashes = [assetAccountInfo.generateAnyoneCanPayScript(blake160).computeHash()] + const anyoneCanPayLockHashes = [utils.computeScriptHash(assetAccountInfo.generateAnyoneCanPayScript(blake160))] beforeEach(async () => { const assetAccounts = [ @@ -1013,8 +1013,8 @@ describe('AssetAccountService', () => { const receiverDefaultLockScript = SystemScriptInfo.generateSecpScript(blake160) const senderDefaultLockScript = SystemScriptInfo.generateSecpScript('0x' + '1'.repeat(40)) const chequeLock = assetAccountInfo.generateChequeScript( - receiverDefaultLockScript.computeHash(), - senderDefaultLockScript.computeHash() + utils.computeScriptHash(receiverDefaultLockScript), + utils.computeScriptHash(senderDefaultLockScript) ) const output = generateOutput( tokenID, diff --git a/packages/neuron-wallet/tests/services/cells.test.ts b/packages/neuron-wallet/tests/services/cells.test.ts index aa1e47b7f2..3ad74aa18b 100644 --- a/packages/neuron-wallet/tests/services/cells.test.ts +++ b/packages/neuron-wallet/tests/services/cells.test.ts @@ -8,7 +8,6 @@ import { CapacityNotEnough, CapacityNotEnoughForChange, LiveCapacityNotEnough } import TransactionEntity from '../../src/database/chain/entities/transaction' import TransactionSize from '../../src/models/transaction-size' import TransactionFee from '../../src/models/transaction-fee' -import Script, { ScriptHashType } from '../../src/models/chain/script' import { TransactionStatus } from '../../src/models/chain/transaction' import Transaction from '../../src/models/chain/transaction' import Output from '../../src/models/chain/output' @@ -23,6 +22,7 @@ import MultisigOutput from '../../src/database/chain/entities/multisig-output' import { MultisigConfigNeedError, TransactionInputParameterMiss } from '../../src/exceptions' import LiveCell from '../../src/models/chain/live-cell' import BufferUtils from '../../src/utils/buffer' +import { HashType, Script, utils } from '@ckb-lumos/base' const randomHex = (length: number = 64): string => { const str: string = Array.from({ length }) @@ -52,7 +52,7 @@ describe('CellsService', () => { const aliceLockScript = SystemScriptInfo.generateSecpScript(alicePublicKeyHash) const alice = { lockScript: aliceLockScript, - lockHash: aliceLockScript.computeHash(), + lockHash: utils.computeScriptHash(aliceLockScript), address: scriptToAddress(aliceLockScript, false), blake160: alicePublicKeyHash, walletId: walletId1, @@ -62,7 +62,7 @@ describe('CellsService', () => { const bobLockScript = SystemScriptInfo.generateSecpScript(bobPublicKeyHash) const bob = { lockScript: bobLockScript, - lockHash: bobLockScript.computeHash(), + lockHash: utils.computeScriptHash(bobLockScript), address: scriptToAddress(bobLockScript, false), blake160: bobPublicKeyHash, walletId: walletId1, @@ -72,7 +72,7 @@ describe('CellsService', () => { const multisigLockScript = SystemScriptInfo.generateMultiSignScript(multisigPublicKeyHash) const multisigInfo = { lockScript: multisigLockScript, - lockHash: multisigLockScript.computeHash(), + lockHash: utils.computeScriptHash(multisigLockScript), address: scriptToAddress(multisigLockScript, false), blake160: multisigPublicKeyHash, walletId: walletId1, @@ -82,7 +82,7 @@ describe('CellsService', () => { const charlieLockScript = SystemScriptInfo.generateSecpScript(charliePublicKeyHash) const charlie = { lockScript: charlieLockScript, - lockHash: charlieLockScript.computeHash(), + lockHash: utils.computeScriptHash(charlieLockScript), address: scriptToAddress(charlieLockScript, false), blake160: charliePublicKeyHash, walletId: walletId2, @@ -133,14 +133,14 @@ describe('CellsService', () => { if (who.lockScript.codeHash === SystemScriptInfo.MULTI_SIGN_CODE_HASH) { output.multiSignBlake160 = who.lockScript.args } - output.lockHash = who.lockScript.computeHash() + output.lockHash = utils.computeScriptHash(who.lockScript) output.status = status output.hasData = hasData if (typeScript) { output.typeCodeHash = typeScript.codeHash output.typeArgs = typeScript.args output.typeHashType = typeScript.hashType - output.typeHash = typeScript.computeHash() + output.typeHash = utils.computeScriptHash(typeScript) } output.daoData = daoData if (transaction) { @@ -177,7 +177,11 @@ describe('CellsService', () => { return multisigCell } - const typeScript = new Script(randomHex(), '0x', ScriptHashType.Data) + const typeScript: Script = { + codeHash: randomHex(), + args: '0x', + hashType: 'data', + } it('getLiveCell', async () => { const capacity = '1000' @@ -265,7 +269,11 @@ describe('CellsService', () => { const cells: OutputEntity[] = [ generateCell(toShannon('1000'), OutputStatus.Live, false, null), generateCell(toShannon('1'), OutputStatus.Live, false, null, { - lockScript: new Script(bob.lockScript.codeHash, bob.lockScript.args, ScriptHashType.Data), + lockScript: { + codeHash: bob.lockScript.codeHash, + args: bob.lockScript.args, + hashType: 'data', + }, }), generateCell(toShannon('200'), OutputStatus.Sent, false, null), generateCell(toShannon('2000'), OutputStatus.Live, true, null), @@ -460,7 +468,7 @@ describe('CellsService', () => { undefined, undefined, undefined, - { codeHash: lockCodeHash, hashType: ScriptHashType.Type } + { codeHash: lockCodeHash, hashType: 'type' } ) } catch (e) { error = e @@ -663,7 +671,11 @@ describe('CellsService', () => { const cells: OutputEntity[] = [ generateCell(toShannon('1000'), OutputStatus.Live, false, null), generateCell(toShannon('1'), OutputStatus.Live, false, null, { - lockScript: new Script(bob.lockScript.codeHash, bob.lockScript.args, ScriptHashType.Data), + lockScript: { + codeHash: bob.lockScript.codeHash, + args: bob.lockScript.args, + hashType: 'data', + }, }), generateCell(toShannon('200'), OutputStatus.Sent, false, null), generateCell(toShannon('2000'), OutputStatus.Live, true, null), @@ -686,7 +698,7 @@ describe('CellsService', () => { beforeEach(async () => { allInputs = await CellsService.gatherAllInputs(walletId1, { codeHash: 'non exist lock code hash', - hashType: ScriptHashType.Type, + hashType: 'type', }) }) it('returns empty array', async () => { @@ -1090,17 +1102,26 @@ describe('CellsService', () => { }) describe('#usedByAnyoneCanPayBlake160s', () => { - const fakeArgs1 = '0x1' - const fakeArgs2 = '0x2' - const fakeArgs3 = '0x3' const codeHash = randomHex() - const lockScript1 = new Script(codeHash, fakeArgs1, ScriptHashType.Type) - const lockScript2 = new Script(codeHash, fakeArgs2, ScriptHashType.Type) - const lockScript3 = new Script(codeHash, fakeArgs3, ScriptHashType.Type) + const lockScript1: Script = { + args: '0x01', + codeHash, + hashType: 'type', + } + const lockScript2: Script = { + args: '0x02', + codeHash, + hashType: 'type', + } + const lockScript3: Script = { + args: '0x03', + codeHash, + hashType: 'type', + } - const owner1 = { lockScript: lockScript1, lockHash: lockScript1.computeHash() } - const owner2 = { lockScript: lockScript2, lockHash: lockScript2.computeHash() } - const owner3 = { lockScript: lockScript3, lockHash: lockScript3.computeHash() } + const owner1 = { lockScript: lockScript1, lockHash: utils.computeScriptHash(lockScript1) } + const owner2 = { lockScript: lockScript2, lockHash: utils.computeScriptHash(lockScript2) } + const owner3 = { lockScript: lockScript3, lockHash: utils.computeScriptHash(lockScript3) } beforeEach(async () => { await createCell('1000', OutputStatus.Live, false, null, owner1) @@ -1144,11 +1165,21 @@ describe('CellsService', () => { lockScript: multiSignLockScript, } - const receiverChequeLock = assetAccountInfo.generateChequeScript(bobDefaultLock.computeHash(), '0'.repeat(40)) - const senderChequeLock = assetAccountInfo.generateChequeScript('0'.repeat(40), bobDefaultLock.computeHash()) + const receiverChequeLock = assetAccountInfo.generateChequeScript( + utils.computeScriptHash(bobDefaultLock), + '0'.repeat(40) + ) + const senderChequeLock = assetAccountInfo.generateChequeScript( + '0'.repeat(40), + utils.computeScriptHash(bobDefaultLock) + ) const acpLock = assetAccountInfo.generateAnyoneCanPayScript('0x') - const sudtType = new Script(assetAccountInfo.getSudtCodeHash(), '0x', ScriptHashType.Type) + const sudtType: Script = { + args: '0x', + codeHash: assetAccountInfo.getSudtCodeHash(), + hashType: 'type', + } beforeEach(async () => { const cells: OutputEntity[] = [ @@ -1279,12 +1310,12 @@ describe('CellsService', () => { lock: { codeHash: string args: string - hashType: ScriptHashType + hashType: HashType }, type: { codeHash: string args: string - hashType: ScriptHashType + hashType: HashType }, outPoint: { txHash: string @@ -1299,16 +1330,16 @@ describe('CellsService', () => { outPoint.txHash, outPoint.index, `0x${BigInt(toShannon(capacity)).toString(16)}`, - Script.fromObject(lock), - Script.fromObject(type), + lock, + type, data ? BufferUtils.writeBigUInt128LE(BigInt(data)) : '0x00' ) } - const gliaTypeScript = Script.fromObject({ + const gliaTypeScript: Script = { codeHash: '0xc5e5dcf215925f7ef4dfaf5f4b4f105bc321c02776d6e7d52a1db3fcd9d011a4', - hashType: ScriptHashType.Type, + hashType: 'type', args: '0x6fe3733cd9df22d05b8a70f7b505d0fb67fb58fb88693217135ff5079713e902', - }) + } it('exception no live cell CapacityNotEnough', async () => { getManyByLockScriptsAndTypeScriptMock.mockResolvedValue([]) await expect(CellsService.gatherSudtInputs('0', walletId1, [], gliaTypeScript, '')).rejects.toThrow( 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 5cdfbb5d42..d94e7e1d2f 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts @@ -7,7 +7,6 @@ import TransactionEntity from '../../../src/database/chain/entities/transaction' import { TargetOutput } from '../../../src/services/tx/transaction-generator' import TransactionSize from '../../../src/models/transaction-size' import TransactionFee from '../../../src/models/transaction-fee' -import Script, { ScriptHashType } from '../../../src/models/chain/script' import Transaction, { TransactionStatus } from '../../../src/models/chain/transaction' import OutPoint from '../../../src/models/chain/out-point' import Output, { OutputStatus } from '../../../src/models/chain/output' @@ -17,6 +16,7 @@ import SystemScriptInfo from '../../../src/models/system-script-info' import AssetAccountInfo from '../../../src/models/asset-account-info' import BufferUtils from '../../../src/utils/buffer' import WitnessArgs from '../../../src/models/chain/witness-args' +import { HashType, utils } from '@ckb-lumos/base' import { serializeWitnessArgs, scriptToAddress, addressToScript } from '@nervosnetwork/ckb-sdk-utils' import { CapacityNotEnough, @@ -42,14 +42,14 @@ const toShannon = (ckb: string) => `${ckb}00000000` const [alice, bob] = keyInfos const walletId1 = alice.walletId -const fullAddressLockScript: Script = new Script( - '0x0000000000000000000000000000000000000000000000000000000000000011', - '0x1234', - ScriptHashType.Type -) +const fullAddressLockScript: Script = { + codeHash: '0x0000000000000000000000000000000000000000000000000000000000000011', + args: '0x1234', + hashType: 'type', +} const fullAddressInfo = { lockScript: fullAddressLockScript, - lockHash: fullAddressLockScript.computeHash(), + lockHash: utils.computeScriptHash(fullAddressLockScript), address: scriptToAddress(fullAddressLockScript, false), } @@ -85,6 +85,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 { Script } from '@ckb-lumos/base' describe('TransactionGenerator', () => { beforeAll(async () => { @@ -140,7 +141,7 @@ describe('TransactionGenerator', () => { output.lockCodeHash = who.lockScript.codeHash output.lockArgs = who.lockScript.args output.lockHashType = who.lockScript.hashType - output.lockHash = who.lockScript.computeHash() + output.lockHash = utils.computeScriptHash(who.lockScript) output.status = status output.hasData = hasData if (typeScript) { @@ -164,12 +165,12 @@ describe('TransactionGenerator', () => { input.lockArgs = lock.args input.lockCodeHash = lock.codeHash input.lockHashType = lock.hashType - input.lockHash = lock.computeHash() + input.lockHash = utils.computeScriptHash(lock) if (type) { input.typeArgs = type!.args input.typeCodeHash = type!.codeHash input.typeHashType = type!.hashType - input.typeHash = type!.computeHash() + input.typeHash = utils.computeScriptHash(type!) } input.since = '0x0' @@ -184,12 +185,12 @@ describe('TransactionGenerator', () => { output.lockArgs = lock.args output.lockCodeHash = lock.codeHash output.lockHashType = lock.hashType - output.lockHash = lock.computeHash() + output.lockHash = utils.computeScriptHash(lock) if (type) { output.typeArgs = type!.args output.typeCodeHash = type!.codeHash output.typeHashType = type!.hashType - output.typeHash = type!.computeHash() + output.typeHash = utils.computeScriptHash(type!) } output.hasData = true output.data = data @@ -210,7 +211,7 @@ describe('TransactionGenerator', () => { multisigCell.lockCodeHash = who.lockScript.codeHash multisigCell.lockArgs = who.lockScript.args multisigCell.lockHashType = who.lockScript.hashType - multisigCell.lockHash = who.lockScript.computeHash() + multisigCell.lockHash = utils.computeScriptHash(who.lockScript) await getConnection().manager.save(multisigCell) return multisigCell } @@ -380,13 +381,13 @@ describe('TransactionGenerator', () => { }) describe('with full address', () => { - it(`only full address, 43 capacity`, async () => { + it(`only full address, 63 capacity`, async () => { const tx: Transaction = await TransactionGenerator.generateTx( walletId1, [ { address: fullAddressInfo.address, - capacity: BigInt(43 * 10 ** 8).toString(), + capacity: BigInt(63 * 10 ** 8).toString(), }, ], bob.address, @@ -651,14 +652,14 @@ describe('TransactionGenerator', () => { expect(outputCapacities + BigInt(tx.fee ?? 0)).toEqual(totalCapacities) }) - it('full address with feeRate 1000, 43 capacity', async () => { + it('full address with feeRate 1000, 63 capacity', async () => { const feeRate = '1000' const tx: Transaction = await TransactionGenerator.generateSendingAllTx( walletId1, [ { address: fullAddressInfo.address, - capacity: toShannon('43'), + capacity: toShannon('63'), }, { address: fullAddressInfo.address, @@ -678,7 +679,7 @@ describe('TransactionGenerator', () => { const expectedFee: bigint = TransactionFee.fee(expectedSize, BigInt(feeRate)) expect(tx.fee).toEqual(expectedFee.toString()) - expect(tx.outputs[0].capacity).toEqual(toShannon('43')) + expect(tx.outputs[0].capacity).toEqual(toShannon('63')) expect(outputCapacities + BigInt(tx.fee ?? 0)).toEqual(totalCapacities) }) @@ -734,11 +735,11 @@ describe('TransactionGenerator', () => { it('generator with multisigConfig', async () => { await createMultisigCell(toShannon('3000'), OutputStatus.Live, { - lockScript: Script.fromObject({ + lockScript: { codeHash: '0x5c5069eb0857efc65e1bca0c07df34c31663b3622fd3876c876320fc9634e2a8', - hashType: ScriptHashType.Type, + hashType: 'type', args: '0x87b9ae2c1c7108178e709bf4a89b736bc0f0ae60', - }), + }, }) const feeRate = '1000' const tx: Transaction = await TransactionGenerator.generateSendingAllTx( @@ -1195,7 +1196,7 @@ describe('TransactionGenerator', () => { const targetOutput: Output = Output.fromObject({ capacity: toShannon('61'), lock: aliceAnyoneCanPayLockScript, - type: assetAccountInfo.generateSudtScript('0xuuid'), + type: assetAccountInfo.generateSudtScript('0x1234'), data: '0x', }) @@ -1243,11 +1244,11 @@ describe('TransactionGenerator', () => { .calledWith({ lock: bobAnyoneCanPayLockScript, type: null, data: null }) .mockResolvedValue([generateLiveCell(toShannon('70'), undefined, undefined, bobAnyoneCanPayLockScript)]) - const pwAnyoneCanPayLockScript = new Script( - process.env.MAINNET_PW_ACP_SCRIPT_CODEHASH!, - '0x36c329ed630d6ce750712a477543672adab57f4c', - process.env.MAINNET_PW_ACP_SCRIPT_HASHTYPE as ScriptHashType - ) + const pwAnyoneCanPayLockScript: Script = { + codeHash: process.env.MAINNET_PW_ACP_SCRIPT_CODEHASH!, + hashType: process.env.MAINNET_PW_ACP_SCRIPT_HASHTYPE as HashType, + args: '0x36c329ed630d6ce750712a477543672adab57f4c', + } const targetOutput: Output = Output.fromObject({ capacity: toShannon('61'), @@ -1527,12 +1528,12 @@ describe('TransactionGenerator', () => { expect(tx.outputs.length).toEqual(2) const changeOutput = tx.outputs.find( - output => output.lock.computeHash() === bobAnyoneCanPayLockScript.computeHash() + output => utils.computeScriptHash(output.lock) === utils.computeScriptHash(bobAnyoneCanPayLockScript) ) expect(changeOutput!.capacity).toEqual(toShannon('61')) const aliceOutput = tx.outputs.find( - output => output.lock.computeHash() === aliceAnyoneCanPayLockScript.computeHash() + output => utils.computeScriptHash(output.lock) === utils.computeScriptHash(aliceAnyoneCanPayLockScript) ) expect(aliceOutput!.capacity).toEqual( @@ -1570,7 +1571,7 @@ describe('TransactionGenerator', () => { expect(tx.inputs.length).toEqual(2) const aliceOutputs = tx.outputs.filter( - output => output.lock!.computeHash() === bobAnyoneCanPayLockScript.computeHash() + output => utils.computeScriptHash(output.lock!) === utils.computeScriptHash(bobAnyoneCanPayLockScript) ) expect(aliceOutputs.length).toEqual(1) expect(aliceOutputs[0].data).toEqual('0x') @@ -1580,7 +1581,7 @@ describe('TransactionGenerator', () => { }) describe('generateAnyoneCanPayToSudtTx, with feeRate 1000', () => { - const tokenID = bob.lockScript.computeHash() + const tokenID = utils.computeScriptHash(bob.lockScript) const feeRate = '1000' let tx: Transaction let expectedTxSize: number @@ -1628,8 +1629,8 @@ describe('TransactionGenerator', () => { expect(tx.inputs.length).toEqual(2) expect(tx.outputs.length).toEqual(2) expect(tx.outputs.map(o => o.lockHash)).toEqual([ - bobAnyoneCanPayLockScript.computeHash(), - aliceAnyoneCanPayLockScript.computeHash(), + utils.computeScriptHash(bobAnyoneCanPayLockScript), + utils.computeScriptHash(aliceAnyoneCanPayLockScript), ]) }) it('calculates fees', () => { @@ -1659,11 +1660,11 @@ describe('TransactionGenerator', () => { }) describe('when sending to pw acp', () => { - const pwAnyoneCanPayLockScript = new Script( - process.env.MAINNET_PW_ACP_SCRIPT_CODEHASH!, - '0x36c329ed630d6ce750712a477543672adab57f4c', - process.env.MAINNET_PW_ACP_SCRIPT_HASHTYPE as ScriptHashType - ) + const pwAnyoneCanPayLockScript: Script = { + codeHash: process.env.MAINNET_PW_ACP_SCRIPT_CODEHASH!, + hashType: process.env.MAINNET_PW_ACP_SCRIPT_HASHTYPE as HashType, + args: '0x36c329ed630d6ce750712a477543672adab57f4c', + } beforeEach(async () => { const targetLiveCellEntity = generateLiveCell(toShannon('142'), '100', tokenID, pwAnyoneCanPayLockScript) @@ -1784,9 +1785,9 @@ describe('TransactionGenerator', () => { expect(tx.outputs.length).toEqual(3) expect(tx.outputs.map(o => o.lockHash)).toEqual([ - bobAnyoneCanPayLockScript.computeHash(), - aliceAnyoneCanPayLockScript.computeHash(), - bob.lockScript.computeHash(), + utils.computeScriptHash(bobAnyoneCanPayLockScript), + utils.computeScriptHash(aliceAnyoneCanPayLockScript), + utils.computeScriptHash(bob.lockScript), ]) }) it('calculates fees', () => { @@ -1862,8 +1863,8 @@ describe('TransactionGenerator', () => { expect(tx.outputs.length).toEqual(2) expect(tx.outputs.map(o => o.lockHash)).toEqual([ - bobAnyoneCanPayLockScript.computeHash(), - aliceAnyoneCanPayLockScript.computeHash(), + utils.computeScriptHash(bobAnyoneCanPayLockScript), + utils.computeScriptHash(aliceAnyoneCanPayLockScript), ]) }) it('calculates fees', () => { @@ -1994,8 +1995,8 @@ describe('TransactionGenerator', () => { expect(tx.outputs.length).toEqual(2) expect(tx.outputs.map(o => o.lockHash)).toEqual([ - bobAnyoneCanPayLockScript.computeHash(), - aliceAnyoneCanPayLockScript.computeHash(), + utils.computeScriptHash(bobAnyoneCanPayLockScript), + utils.computeScriptHash(aliceAnyoneCanPayLockScript), ]) }) it('updates output data', () => { @@ -2047,13 +2048,13 @@ describe('TransactionGenerator', () => { expect(tx.inputs.length).toEqual(2) expect(tx.outputs.length).toEqual(3) expect(tx.inputs.map(o => o.lockHash)).toEqual([ - bobAnyoneCanPayLockScript.computeHash(), - alice.lockScript.computeHash(), + utils.computeScriptHash(bobAnyoneCanPayLockScript), + utils.computeScriptHash(alice.lockScript), ]) expect(tx.outputs.map(o => o.lockHash)).toEqual([ - bobAnyoneCanPayLockScript.computeHash(), - aliceAnyoneCanPayLockScript.computeHash(), - bob.lockScript.computeHash(), + utils.computeScriptHash(bobAnyoneCanPayLockScript), + utils.computeScriptHash(aliceAnyoneCanPayLockScript), + utils.computeScriptHash(bob.lockScript), ]) }) it('calculates fees', () => { @@ -2181,8 +2182,8 @@ describe('TransactionGenerator', () => { expectedChequeOutput = Output.fromObject({ capacity: toShannon('161'), lock: assetAccountInfo.generateChequeScript( - receiverDefaultLock.computeHash(), - senderDefaultLock.computeHash() + utils.computeScriptHash(receiverDefaultLock), + utils.computeScriptHash(senderDefaultLock) ), type: senderAcpLiveCell.type(), data: BufferUtils.writeBigUInt128LE(BigInt(110)), @@ -2203,7 +2204,7 @@ describe('TransactionGenerator', () => { }) it('creates cheque output', () => { const chequeOutput = tx.outputs[0] - expect(chequeOutput.lock.computeHash()).toEqual(expectedChequeOutput.lockHash) + expect(utils.computeScriptHash(chequeOutput.lock)).toEqual(expectedChequeOutput.lockHash) expect(chequeOutput.lock.args.length).toEqual(82) }) it('sender lock hash equals to one of default lock inputs', () => { @@ -2211,7 +2212,7 @@ describe('TransactionGenerator', () => { const isDefaultLock = input.lock!.codeHash === SystemScriptInfo.SECP_CODE_HASH return ( isDefaultLock && - input.lock!.computeHash().slice(0, 42) === '0x' + expectedChequeOutput.lock.args.slice(42) + utils.computeScriptHash(input.lock!).slice(0, 42) === '0x' + expectedChequeOutput.lock.args.slice(42) ) }) expect(defaultLockInput).not.toEqual(undefined) @@ -2249,8 +2250,8 @@ describe('TransactionGenerator', () => { const receiverDefaultLock = bob.lockScript beforeEach(async () => { - const receiverDefaultLockHash = receiverDefaultLock.computeHash() - const senderDefaultLockHash = senderDefaultLock.computeHash() + const receiverDefaultLockHash = utils.computeScriptHash(receiverDefaultLock) + const senderDefaultLockHash = utils.computeScriptHash(senderDefaultLock) const transaction = new TransactionEntity() transaction.hash = '0x' @@ -2292,15 +2293,15 @@ describe('TransactionGenerator', () => { it('uses the existing acp cell to hold the claimed sudt amount', () => { const acpInput = tx.inputs.find( input => - input.lock!.computeHash() === receiverAcpCell!.lockScript()!.computeHash() && - input.type!.computeHash() === receiverAcpCell!.typeScript()!.computeHash() + utils.computeScriptHash(input.lock!) === utils.computeScriptHash(receiverAcpCell!.lockScript()!) && + utils.computeScriptHash(input.type!) === utils.computeScriptHash(receiverAcpCell!.typeScript()!) ) const acpInputAmount = BufferUtils.readBigUInt128LE(acpInput!.data!) const acpOutput = tx.outputs.find( input => - input.lock!.computeHash() === receiverAcpCell!.lockScript()!.computeHash() && - input.type!.computeHash() === receiverAcpCell!.typeScript()!.computeHash() + utils.computeScriptHash(input.lock!) === utils.computeScriptHash(receiverAcpCell!.lockScript()!) && + utils.computeScriptHash(input.type!) === utils.computeScriptHash(receiverAcpCell!.typeScript()!) ) const chequeCellAmount = BufferUtils.readBigUInt128LE(expectedChequeOutput.data) @@ -2311,7 +2312,7 @@ describe('TransactionGenerator', () => { }) it('returns ckb to sender', () => { const senderDefaultOutput = tx.outputs.find( - input => input.lock!.computeHash() === senderDefaultLock.computeHash() + input => utils.computeScriptHash(input.lock!) === utils.computeScriptHash(senderDefaultLock) ) expect(senderDefaultOutput!.capacity).toEqual(expectedChequeOutput.capacity) }) @@ -2330,15 +2331,15 @@ describe('TransactionGenerator', () => { it('creates an new acp cell to hold the claimed sudt amount', () => { const acpInput = tx.inputs.find( input => - input.lock!.computeHash() === receiverAcpCell!.lockScript()!.computeHash() && - input.type!.computeHash() === receiverAcpCell!.typeScript()!.computeHash() + utils.computeScriptHash(input.lock!) === utils.computeScriptHash(receiverAcpCell!.lockScript()!) && + utils.computeScriptHash(input.type!) === utils.computeScriptHash(receiverAcpCell!.typeScript()!) ) expect(acpInput).toBe(undefined) const acpOutput = tx.outputs.find( input => - input.lock!.computeHash() === receiverAcpCell!.lockScript()!.computeHash() && - input.type!.computeHash() === receiverAcpCell!.typeScript()!.computeHash() + utils.computeScriptHash(input.lock!) === utils.computeScriptHash(receiverAcpCell!.lockScript()!) && + utils.computeScriptHash(input.type!) === utils.computeScriptHash(receiverAcpCell!.typeScript()!) ) const chequeCellAmount = BufferUtils.readBigUInt128LE(expectedChequeOutput.data) @@ -2348,7 +2349,7 @@ describe('TransactionGenerator', () => { }) it('returns ckb to sender', () => { const senderDefaultOutput = tx.outputs.find( - input => input.lock!.computeHash() === senderDefaultLock.computeHash() + input => utils.computeScriptHash(input.lock!) === utils.computeScriptHash(senderDefaultLock) ) expect(senderDefaultOutput!.capacity).toEqual(expectedChequeOutput.capacity) }) @@ -2368,7 +2369,10 @@ describe('TransactionGenerator', () => { senderDefaultLockInputEntity = createInput(senderDefaultLock, undefined, transaction.hash) - const chequeLock = assetAccountInfo.generateChequeScript('0x' + '0'.repeat(40), senderDefaultLock.computeHash()) + const chequeLock = assetAccountInfo.generateChequeScript( + '0x' + '0'.repeat(40), + utils.computeScriptHash(senderDefaultLock) + ) chequeOutputEntity = createOutput( chequeLock, typeScript, @@ -2541,7 +2545,7 @@ describe('TransactionGenerator', () => { expect(res.outputs[1].data).toEqual(BufferUtils.writeBigUInt128LE(BigInt(200))) expect(res.outputs[2].capacity).toEqual((BigInt(secpCell.capacity) - BigInt(res.fee ?? 0)).toString()) expect(res.inputs).toHaveLength(3) - expect(res.inputs[2].lockHash).toBe(bobAnyoneCanPayLockScript.computeHash()) + expect(res.inputs[2].lockHash).toBe(utils.computeScriptHash(bobAnyoneCanPayLockScript)) }) }) @@ -2668,14 +2672,18 @@ describe('TransactionGenerator', () => { }) describe('#generateMigrateLegacyACPTx', () => { - const defaultLock = new Script( - SystemScriptInfo.SECP_CODE_HASH, - alice.publicKeyInBlake160, - SystemScriptInfo.SECP_HASH_TYPE - ) + const defaultLock: Script = { + codeHash: SystemScriptInfo.SECP_CODE_HASH, + hashType: SystemScriptInfo.SECP_HASH_TYPE, + args: alice.publicKeyInBlake160, + } const legacyACPCodeHash: string = process.env.LEGACY_MAINNET_ACP_SCRIPT_CODEHASH as string const legacyACPHashType: string = process.env.LEGACY_MAINNET_ACP_SCRIPT_HASHTYPE as string - const legacyACPLock = new Script(legacyACPCodeHash, alice.publicKeyInBlake160, legacyACPHashType as ScriptHashType) + const legacyACPLock: Script = { + codeHash: legacyACPCodeHash, + hashType: legacyACPHashType as HashType, + args: alice.publicKeyInBlake160, + } const assetAccountInfo = new AssetAccountInfo() const tokenID = '0x' + '0'.repeat(64) @@ -2716,24 +2724,26 @@ describe('TransactionGenerator', () => { it('generates acp migration transaction', async () => { const tx = (await TransactionGenerator.generateMigrateLegacyACPTx(alice.walletId))! const totalLegacyACPCellsCount = tx.inputs.filter( - input => input.lockHash === legacyACPLock.computeHash() + input => input.lockHash === utils.computeScriptHash(legacyACPLock) + ).length + const totalMigratedACPCellsCount = tx.outputs.filter( + output => output.lockHash === utils.computeScriptHash(acpLock) ).length - const totalMigratedACPCellsCount = tx.outputs.filter(output => output.lockHash === acpLock.computeHash()).length const totalMigratedSUDTCellCount = tx.outputs.filter( - output => output.typeHash === sudtScript.computeHash() + output => output.typeHash === utils.computeScriptHash(sudtScript) ).length const normalInputCellCapacity = tx.inputs - .filter(input => input.lockHash === defaultLock.computeHash()) + .filter(input => input.lockHash === utils.computeScriptHash(defaultLock)) .reduce((sum, input) => { return (sum += BigInt(input.capacity ?? 0)) }, BigInt(0)) const normalOutputCellCapacity = tx.outputs - .filter(output => output.lockHash === defaultLock.computeHash()) + .filter(output => output.lockHash === utils.computeScriptHash(defaultLock)) .reduce((sum, output) => { return (sum += BigInt(output.capacity)) }, BigInt(0)) const acpCellCapacity = tx.outputs - .filter(output => output.lockHash === acpLock.computeHash()) + .filter(output => output.lockHash === utils.computeScriptHash(acpLock)) .reduce((sum, output) => { return (sum += BigInt(output.capacity)) }, BigInt(0)) @@ -2854,11 +2864,11 @@ describe('TransactionGenerator', () => { }) describe('sUDT account', () => { it('sUDT amount is not zero throw exception', async () => { - const typeScript = new Script( - '0xc5e5dcf215925f7ef4dfaf5f4b4f105bc321c02776d6e7d52a1db3fcd9d011a4', - '0x2619a9dc0428f87c0921ed22d0f10707c5c4ec9e8185764d8236d7ea996a9b03', - ScriptHashType.Type - ) + const typeScript: Script = { + codeHash: '0xc5e5dcf215925f7ef4dfaf5f4b4f105bc321c02776d6e7d52a1db3fcd9d011a4', + hashType: 'type', + args: '0x2619a9dc0428f87c0921ed22d0f10707c5c4ec9e8185764d8236d7ea996a9b03', + } const input = createInput(alice.lockScript, typeScript, '0x' + '0'.repeat(64)) const asssetAccountInput = input.toModel() asssetAccountInput.capacity = toShannon('142') @@ -2873,11 +2883,11 @@ describe('TransactionGenerator', () => { ).rejects.toThrow(new SudtAcpHaveDataError()) }) it('destroy success', async () => { - const typeScript = new Script( - '0xc5e5dcf215925f7ef4dfaf5f4b4f105bc321c02776d6e7d52a1db3fcd9d011a4', - '0x2619a9dc0428f87c0921ed22d0f10707c5c4ec9e8185764d8236d7ea996a9b03', - ScriptHashType.Type - ) + const typeScript: Script = { + codeHash: '0xc5e5dcf215925f7ef4dfaf5f4b4f105bc321c02776d6e7d52a1db3fcd9d011a4', + hashType: 'type', + args: '0x2619a9dc0428f87c0921ed22d0f10707c5c4ec9e8185764d8236d7ea996a9b03', + } const input = createInput(alice.lockScript, typeScript, '0x' + '0'.repeat(64)) const asssetAccountInput = input.toModel() asssetAccountInput.capacity = toShannon('142') 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 9d236e5b11..ccb23f7758 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-persistor.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-persistor.test.ts @@ -8,6 +8,7 @@ import AssetAccountInfo from '../../../src/models/asset-account-info' import SystemScriptInfo from '../../../src/models/system-script-info' import Multisig from '../../../src/models/multisig' import TxLockEntity from '../../../src/database/chain/entities/tx-lock' +import { utils } from '@ckb-lumos/base' const [tx, tx2] = transactions @@ -88,14 +89,15 @@ describe('TransactionPersistor', () => { expect(loadedTx?.inputs.length).toBe(0) expect(loadedTx?.outputs.length).toBe(1) expect(loadedTx?.outputs[0].lockArgs).toBe(tx.outputs[0].lock.args) - const txLocks = await getConnection() - .getRepository(TxLockEntity) - .find({ transactionHash: tx.hash }) + const txLocks = await getConnection().getRepository(TxLockEntity).find({ transactionHash: tx.hash }) expect(txLocks.length).toBe(1) - expect(txLocks[0].lockHash).toBe(tx.inputs[0].lock?.computeHash()) + const firstOutputLock = tx.inputs[0].lock + expect(txLocks[0].lockHash).toBe(firstOutputLock ? utils.computeScriptHash(firstOutputLock) : undefined) }) it('all args is current', async () => { - const args = [...tx.inputs.map(v => v.lock?.args), ...tx.outputs.map(v => v.lock.args)].filter((v): v is string => !!v) + const args = [...tx.inputs.map(v => v.lock?.args), ...tx.outputs.map(v => v.lock.args)].filter( + (v): v is string => !!v + ) await TransactionPersistor.convertTransactionAndSave(tx, TxSaveType.Fetch, new Set(args)) const loadedTx = await getConnection() .getRepository(TransactionEntity) @@ -106,22 +108,26 @@ describe('TransactionPersistor', () => { .getOne() expect(loadedTx?.inputs.length).toBe(1) expect(loadedTx?.outputs.length).toBe(2) - const txLocks = await getConnection() - .getRepository(TxLockEntity) - .find({ transactionHash: tx.hash }) + const txLocks = await getConnection().getRepository(TxLockEntity).find({ transactionHash: tx.hash }) expect(txLocks.length).toBe(0) }) it('filter with receive cheque and send cheque', async () => { const assetAccountInfo = new AssetAccountInfo() const txWithCheque = Transaction.fromObject(tx) - const outputReceiveChequeLock = assetAccountInfo.generateChequeScript(txWithCheque.outputs[0].lockHash, `0x${'0'.repeat(42)}`) - const outputSendChequeLock = assetAccountInfo.generateChequeScript(`0x${'0'.repeat(42)}`, txWithCheque.outputs[0].lockHash) + const outputReceiveChequeLock = assetAccountInfo.generateChequeScript( + txWithCheque.outputs[0].lockHash, + `0x${'0'.repeat(42)}` + ) + const outputSendChequeLock = assetAccountInfo.generateChequeScript( + `0x${'0'.repeat(42)}`, + txWithCheque.outputs[0].lockHash + ) txWithCheque.outputs[0].setLock(outputReceiveChequeLock) txWithCheque.outputs[1].setLock(outputSendChequeLock) - const args = [...tx.inputs.map(v => v.lock?.args), ...tx.outputs.map(v => v.lock.args)].filter((v): v is string => !!v).map(v => [ - v, - SystemScriptInfo.generateSecpScript(v).computeHash().slice(0, 42), - ]).flat() + const args = [...tx.inputs.map(v => v.lock?.args), ...tx.outputs.map(v => v.lock.args)] + .filter((v): v is string => !!v) + .map(v => [v, utils.computeScriptHash(SystemScriptInfo.generateSecpScript(v)).slice(0, 42)]) + .flat() await TransactionPersistor.convertTransactionAndSave(txWithCheque, TxSaveType.Fetch, new Set(args)) const loadedTx = await getConnection() .getRepository(TransactionEntity) @@ -132,19 +138,19 @@ describe('TransactionPersistor', () => { .getOne() expect(loadedTx?.inputs.length).toBe(1) expect(loadedTx?.outputs.length).toBe(2) - const txLocks = await getConnection() - .getRepository(TxLockEntity) - .find({ transactionHash: tx.hash }) + const txLocks = await getConnection().getRepository(TxLockEntity).find({ transactionHash: tx.hash }) expect(txLocks.length).toBe(0) }) it('filter with multi lock time', async () => { const txWithCheque = Transaction.fromObject(tx) - const multisigLockTimeLock = SystemScriptInfo.generateMultiSignScript(Multisig.hash([txWithCheque.outputs[0].lock.args])) + const multisigLockTimeLock = SystemScriptInfo.generateMultiSignScript( + Multisig.hash([txWithCheque.outputs[0].lock.args]) + ) txWithCheque.outputs[0].setLock(multisigLockTimeLock) - const args = [...tx.inputs.map(v => v.lock?.args), ...tx.outputs.map(v => v.lock.args)].filter((v): v is string => !!v).map(v => [ - v, - Multisig.hash([v]), - ]).flat() + const args = [...tx.inputs.map(v => v.lock?.args), ...tx.outputs.map(v => v.lock.args)] + .filter((v): v is string => !!v) + .map(v => [v, Multisig.hash([v])]) + .flat() await TransactionPersistor.convertTransactionAndSave(txWithCheque, TxSaveType.Fetch, new Set(args)) const loadedTx = await getConnection() .getRepository(TransactionEntity) @@ -155,9 +161,7 @@ describe('TransactionPersistor', () => { .getOne() expect(loadedTx?.inputs.length).toBe(1) expect(loadedTx?.outputs.length).toBe(2) - const txLocks = await getConnection() - .getRepository(TxLockEntity) - .find({ transactionHash: tx.hash }) + const txLocks = await getConnection().getRepository(TxLockEntity).find({ transactionHash: tx.hash }) expect(txLocks.length).toBe(0) }) }) diff --git a/packages/neuron-wallet/tests/services/tx/transaction-sender.test.ts b/packages/neuron-wallet/tests/services/tx/transaction-sender.test.ts index 19b64eef66..4a2c0ae668 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-sender.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-sender.test.ts @@ -131,7 +131,7 @@ jest.doMock('services/hardware', () => ({ })) jest.doMock('@nervosnetwork/ckb-sdk-core', () => { - return function() { + return function () { return { calculateDaoMaximumWithdraw: stubbedCalculateDaoMaximumWithdraw, } @@ -141,13 +141,13 @@ jest.doMock('@nervosnetwork/ckb-sdk-core', () => { jest.doMock('utils/ckb-rpc.ts', () => ({ generateRPC() { return { - sendTransaction: stubbedSendTransaction + sendTransaction: stubbedSendTransaction, } - } + }, })) jest.doMock('services/cells', () => ({ - getLiveCell: stubbedGetLiveCell + getLiveCell: stubbedGetLiveCell, })) import Transaction from '../../../src/models/chain/transaction' @@ -155,7 +155,6 @@ import TxStatus from '../../../src/models/chain/tx-status' import CellDep, { DepType } from '../../../src/models/chain/cell-dep' import OutPoint from '../../../src/models/chain/out-point' import Input from '../../../src/models/chain/input' -import Script, { ScriptHashType } from '../../../src/models/chain/script' import Output from '../../../src/models/chain/output' import Keystore from '../../../src/models/keys/keystore' import { AddressType } from '../../../src/models/keys/address' @@ -173,12 +172,13 @@ import TransactionSender from '../../../src/services/transaction-sender' import MultisigConfigModel from '../../../src/models/multisig-config' import Multisig from '../../../src/models/multisig' import { addressToScript, serializeWitnessArgs } from '@nervosnetwork/ckb-sdk-utils' +import { Script, utils } from '@ckb-lumos/base' -const fakeScript = new Script( - '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', - '0x36c329ed630d6ce750712a477543672adab57f4c', - ScriptHashType.Type -) +const fakeScript: Script = { + codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', + hashType: 'type', + args: '0x36c329ed630d6ce750712a477543672adab57f4c', +} const generateTxWithStatus = ( id: string, block: any, @@ -331,30 +331,30 @@ describe('TransactionSender Test', () => { index: '0x0', }), since: '0x0', - lock: Script.fromObject({ + lock: { args: '0x36c329ed630d6ce750712a477543672adab57f4c', codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, }), ], outputs: [ Output.fromObject({ capacity: '0x174876e800', - lock: Script.fromObject({ + lock: { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0xe2193df51d78411601796b35b17b4f8f2cd85bd0', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, type: null, }), Output.fromObject({ capacity: '0x12319d9962f4', - lock: Script.fromObject({ + lock: { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0x36c329ed630d6ce750712a477543672adab57f4c', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, type: null, }), ], @@ -392,22 +392,21 @@ describe('TransactionSender Test', () => { index: '0x0', }), since: '0x2000f00078000002', - lock: Script.fromObject({ - // "args": "0x36c329ed630d6ce750712a477543672adab57f4c", + lock: { args: '0x56f281b3d4bb5fc73c751714af0bf78eb8aba0d80200007800f00020', codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, }), ], outputs: [ Output.fromObject({ capacity: '0xd18c2e2800', - lock: Script.fromObject({ + lock: { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0x36c329ed630d6ce750712a477543672adab57f4c', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, type: null, }), ], @@ -452,7 +451,10 @@ describe('TransactionSender Test', () => { }) describe('when matched receiver lock hash', () => { beforeEach(() => { - const chequeLock = assetAccountInfo.generateChequeScript(receiverDefaultLock.computeHash(), '0'.repeat(40)) + const chequeLock = assetAccountInfo.generateChequeScript( + utils.computeScriptHash(receiverDefaultLock), + '0'.repeat(40) + ) tx.inputs[0].lock = chequeLock }) it('success', async () => { @@ -502,7 +504,10 @@ describe('TransactionSender Test', () => { }) describe('when matched sender lock hash', () => { beforeEach(() => { - const chequeLock = assetAccountInfo.generateChequeScript('0'.repeat(40), senderDefaultLock.computeHash()) + const chequeLock = assetAccountInfo.generateChequeScript( + '0'.repeat(40), + utils.computeScriptHash(senderDefaultLock) + ) tx.inputs[0].lock = chequeLock }) it('success', async () => { @@ -817,30 +822,30 @@ describe('TransactionSender Test', () => { index: '0x0', }), since: '0x0', - lock: Script.fromObject({ - args: '', + lock: { + args: '0x', codeHash: SystemScriptInfo.MULTI_SIGN_CODE_HASH, hashType: SystemScriptInfo.MULTI_SIGN_HASH_TYPE, - }), + }, }), ], outputs: [ Output.fromObject({ capacity: '0x174876e800', - lock: Script.fromObject({ + lock: { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0xe2193df51d78411601796b35b17b4f8f2cd85bd0', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, type: null, }), Output.fromObject({ capacity: '0x12319d9962f4', - lock: Script.fromObject({ + lock: { codeHash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', args: '0x36c329ed630d6ce750712a477543672adab57f4c', - hashType: 'type' as ScriptHashType, - }), + hashType: 'type', + }, type: null, }), ], @@ -1040,11 +1045,11 @@ describe('TransactionSender Test', () => { index: '0x0', }), since: '0x0', - lock: Script.fromObject({ + lock: { args: multiArgs, codeHash: SystemScriptInfo.MULTI_SIGN_CODE_HASH, hashType: SystemScriptInfo.MULTI_SIGN_HASH_TYPE, - }), + }, }) ) tx.witnesses = ['0x', '0x'] 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 6915efe39e..5d24104cfd 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-service.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-service.test.ts @@ -1,4 +1,4 @@ - import os from 'os' +import os from 'os' import fs from 'fs' import path from 'path' import TransactionService, { SearchType } from '../../../src/services/tx/transaction-service' @@ -25,9 +25,9 @@ jest.mock('../../../src/models/asset-account-info', () => { const getTransactionMock = jest.fn() jest.mock('../../../src/services/rpc-service', () => { - return function() { + return function () { return { - getTransaction: getTransactionMock + getTransaction: getTransactionMock, } } }) @@ -35,15 +35,15 @@ jest.mock('../../../src/services/rpc-service', () => { const ckbRpcExecMock = jest.fn() jest.mock('@nervosnetwork/ckb-sdk-core', () => { - return function() { + return function () { return { rpc: { createBatchRequest() { return { - exec: ckbRpcExecMock + exec: ckbRpcExecMock, } - } - } + }, + }, } } }) @@ -286,7 +286,9 @@ describe('Test TransactionService', () => { it('Get input and outputs from rpc', async () => { getTransactionMock.mockResolvedValue({ transaction: Transaction.fromObject(transactions[0]) }) - ckbRpcExecMock.mockResolvedValue([{ transaction: { outputs: [{ capacity: '0x100', lock: transactions[0].inputs[0].lock } ]} }]) + ckbRpcExecMock.mockResolvedValue([ + { transaction: { outputs: [{ capacity: '0x100', lock: transactions[0].inputs[0].lock }] } }, + ]) const actual = await TransactionService.get(stubProvider.hash) expect(actual).not.toBeUndefined() expect(actual?.inputs.length).toBe(transactions[0].inputs.length) @@ -472,7 +474,11 @@ describe('Test TransactionService', () => { const args = `0x${'0'.repeat(42)}` const script = SystemScriptInfo.generateSecpScript(args) tx.inputs[0].setLock(script) - await TransactionPersistor.convertTransactionAndSave(tx, TxSaveType.Fetch, new Set([tx.outputs[0].lock.args, tx.outputs[1].lock.args])) + await TransactionPersistor.convertTransactionAndSave( + tx, + TxSaveType.Fetch, + new Set([tx.outputs[0].lock.args, tx.outputs[1].lock.args]) + ) const actual = await TransactionService.getAllByAddresses(stubProvider, scriptToAddress(script)) expect(actual.totalCount).toBe(1) }) @@ -574,8 +580,8 @@ describe('Test TransactionService', () => { it('inputs without txHash', async () => { const inputs = [ Input.fromObject({ - previousOutput: null - }) + previousOutput: null, + }), ] //@ts-ignore private-method const actual = await TransactionService.fillInputFields(inputs) @@ -584,8 +590,8 @@ describe('Test TransactionService', () => { it('can not get output', async () => { const inputs = [ Input.fromObject({ - previousOutput: new OutPoint(`0x${'0'.repeat(64)}`, '0x0') - }) + previousOutput: new OutPoint(`0x${'0'.repeat(64)}`, '0x0'), + }), ] ckbRpcExecMock.mockResolvedValueOnce([]) //@ts-ignore private-method @@ -595,8 +601,8 @@ describe('Test TransactionService', () => { it('success fill input fields without type', async () => { const inputs = [ Input.fromObject({ - previousOutput: new OutPoint(`0x${'0'.repeat(64)}`, '0x0') - }) + previousOutput: new OutPoint(`0x${'0'.repeat(64)}`, '0x0'), + }), ] const transactionWithStatus = { transaction: { @@ -606,24 +612,24 @@ describe('Test TransactionService', () => { lock: { codeHash: `0x${'0'.repeat(64)}`, hashType: 'data', - args: '0x0' + args: '0x00', }, - } - ] - } + }, + ], + }, } ckbRpcExecMock.mockResolvedValueOnce([transactionWithStatus]) //@ts-ignore private-method const actual = await TransactionService.fillInputFields(inputs) expect(actual[0].capacity).toBe('4096') - expect(actual[0].lock?.toSDK()).toStrictEqual(transactionWithStatus.transaction.outputs[0].lock) + expect(actual[0].lock).toStrictEqual(transactionWithStatus.transaction.outputs[0].lock) expect(actual[0].type).toBeUndefined() }) it('success fill input fields with type', async () => { const inputs = [ Input.fromObject({ - previousOutput: new OutPoint(`0x${'0'.repeat(64)}`, '0x0') - }) + previousOutput: new OutPoint(`0x${'0'.repeat(64)}`, '0x0'), + }), ] const transactionWithStatus = { transaction: { @@ -633,23 +639,23 @@ describe('Test TransactionService', () => { lock: { codeHash: `0x${'0'.repeat(64)}`, hashType: 'data', - args: '0x0' + args: '0x00', }, type: { codeHash: `0x${'1'.repeat(64)}`, hashType: 'data', - args: '0x1' - } - } - ] - } + args: '0x01', + }, + }, + ], + }, } ckbRpcExecMock.mockResolvedValueOnce([transactionWithStatus]) //@ts-ignore private-method const actual = await TransactionService.fillInputFields(inputs) expect(actual[0].capacity).toBe('4096') - expect(actual[0].lock?.toSDK()).toStrictEqual(transactionWithStatus.transaction.outputs[0].lock) - expect(actual[0].type?.toSDK()).toStrictEqual(transactionWithStatus.transaction.outputs[0].type) + expect(actual[0].lock).toStrictEqual(transactionWithStatus.transaction.outputs[0].lock) + expect(actual[0].type).toStrictEqual(transactionWithStatus.transaction.outputs[0].type) }) }) }) diff --git a/packages/neuron-wallet/tests/setupAndTeardown/public-key-info.fixture.ts b/packages/neuron-wallet/tests/setupAndTeardown/public-key-info.fixture.ts index 585fb8dde0..4ece31856a 100644 --- a/packages/neuron-wallet/tests/setupAndTeardown/public-key-info.fixture.ts +++ b/packages/neuron-wallet/tests/setupAndTeardown/public-key-info.fixture.ts @@ -1,6 +1,7 @@ import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils' import { AddressType } from '../../src/models/keys/address' import SystemScriptInfo from '../../src/models/system-script-info' +import { utils } from '@ckb-lumos/base' const walletId1 = 'w1' const walletId2 = 'w2' @@ -10,7 +11,7 @@ const alicePublicKeyHash = '0xe2193df51d78411601796b35b17b4f8f2cd85bd0' const aliceLockScript = SystemScriptInfo.generateSecpScript(alicePublicKeyHash) const alice = { lockScript: aliceLockScript, - lockHash: aliceLockScript.computeHash(), + lockHash: utils.computeScriptHash(aliceLockScript), address: scriptToAddress(aliceLockScript, false), blake160: aliceLockScript.args, walletId: walletId1, @@ -20,7 +21,7 @@ const bobPublicKeyHash = '0x36c329ed630d6ce750712a477543672adab57f4c' const bobLockScript = SystemScriptInfo.generateSecpScript(bobPublicKeyHash) const bob = { lockScript: bobLockScript, - lockHash: bobLockScript.computeHash(), + lockHash: utils.computeScriptHash(bobLockScript), address: scriptToAddress(bobLockScript, false), blake160: bobPublicKeyHash, walletId: walletId1, @@ -30,7 +31,7 @@ const charliePublicKeyHash = '0xe2193df51d78411601796b35b17b4f8f2cd80000' const charlieLockScript = SystemScriptInfo.generateSecpScript(charliePublicKeyHash) const charlie = { lockScript: charlieLockScript, - lockHash: charlieLockScript.computeHash(), + lockHash: utils.computeScriptHash(charlieLockScript), address: scriptToAddress(charlieLockScript, false), blake160: charliePublicKeyHash, walletId: walletId2, diff --git a/packages/neuron-wallet/tests/setupAndTeardown/transactions.fixture.ts b/packages/neuron-wallet/tests/setupAndTeardown/transactions.fixture.ts index 378fb42e48..c14636bb21 100644 --- a/packages/neuron-wallet/tests/setupAndTeardown/transactions.fixture.ts +++ b/packages/neuron-wallet/tests/setupAndTeardown/transactions.fixture.ts @@ -3,7 +3,6 @@ import Transaction from '../../src/models/chain/transaction' import CellDep from '../../src/models/chain/cell-dep' import OutPoint from '../../src/models/chain/out-point' import Input from '../../src/models/chain/input' -import Script from '../../src/models/chain/script' import Output from '../../src/models/chain/output' import { DEPLOY_KEY } from './keys' import { systemScripts } from '@nervosnetwork/ckb-sdk-utils' @@ -19,12 +18,12 @@ const fromTxObject = (tx: any) => inputs: tx.inputs.map((input: any) => { const previousOutput = OutPoint.fromObject(input.previousOutput) const { since } = input - const lock = Script.fromObject(input.lock) + const lock = input.lock return Input.fromObject({ previousOutput, since, lock }) }), outputs: tx.outputs.map((output: any) => { const { capacity, type } = output - const lock = Script.fromObject(output.lock) + const lock = output.lock const outPoint = new OutPoint(output.outPoint.txHash, output.outPoint.index) return Output.fromObject({ capacity, From 6954b0b5de9d4f8ea96b76bd3b0e9447ae0a2972 Mon Sep 17 00:00:00 2001 From: zhangyouxin Date: Thu, 6 Jul 2023 15:55:04 +0800 Subject: [PATCH 2/2] fix: fix typos --- .../src/services/tx/transaction-generator.ts | 8 ++--- .../services/tx/transaction-generator.test.ts | 32 +++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/neuron-wallet/src/services/tx/transaction-generator.ts b/packages/neuron-wallet/src/services/tx/transaction-generator.ts index 7908107331..3cb42add05 100644 --- a/packages/neuron-wallet/src/services/tx/transaction-generator.ts +++ b/packages/neuron-wallet/src/services/tx/transaction-generator.ts @@ -711,7 +711,7 @@ export class TransactionGenerator { public static async generateDestroyAssetAccountTx( walletId: string, - asssetAccountInputs: Input[], + assetAccountInputs: Input[], changeBlake160: string, isCKBAccount: boolean ) { @@ -719,7 +719,7 @@ export class TransactionGenerator { const assetAccountInfo = new AssetAccountInfo() const cellDeps = [secpCellDep, assetAccountInfo.anyoneCanPayCellDep] - if (asssetAccountInputs.some(v => v.type && v.data !== '0x' && BigInt(v.data || 0) !== BigInt(0))) { + if (assetAccountInputs.some(v => v.type && v.data !== '0x' && BigInt(v.data || 0) !== BigInt(0))) { throw new SudtAcpHaveDataError() } if (!isCKBAccount) { @@ -735,13 +735,13 @@ export class TransactionGenerator { version: '0', headerDeps: [], cellDeps, - inputs: asssetAccountInputs, + inputs: assetAccountInputs, outputs: [output], outputsData: [output.data], witnesses: [], }) - let allCapacities = asssetAccountInputs.reduce((a, b) => { + let allCapacities = assetAccountInputs.reduce((a, b) => { return a + BigInt(b.capacity as string) }, BigInt(0)) tx.fee = TransactionFee.fee(TransactionSize.tx(tx), BigInt(1e4)).toString() 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 d94e7e1d2f..31f072da42 100644 --- a/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts +++ b/packages/neuron-wallet/tests/services/tx/transaction-generator.test.ts @@ -2820,12 +2820,12 @@ describe('TransactionGenerator', () => { describe('CKB account', () => { it('capacity not enough for fee', async () => { const input = createInput(alice.lockScript, undefined, '0x' + '0'.repeat(64)) - const asssetAccountInput = input.toModel() - asssetAccountInput.capacity = toShannon('61') + const assetAccountInput = input.toModel() + assetAccountInput.capacity = toShannon('61') await expect( TransactionGenerator.generateDestroyAssetAccountTx( 'walletId', - [asssetAccountInput], + [assetAccountInput], bob.publicKeyInBlake160, true ) @@ -2833,13 +2833,13 @@ describe('TransactionGenerator', () => { }) it('account capacity not enough for fee need other address', async () => { const input = createInput(alice.lockScript, undefined, '0x' + '0'.repeat(64)) - const asssetAccountInput = input.toModel() - asssetAccountInput.capacity = toShannon('61') + const assetAccountInput = input.toModel() + assetAccountInput.capacity = toShannon('61') const cell: OutputEntity = generateCell(toShannon('62'), OutputStatus.Live, false, null, alice) await getConnection().manager.save(cell) const res = await TransactionGenerator.generateDestroyAssetAccountTx( alice.walletId, - [asssetAccountInput], + [assetAccountInput], bob.publicKeyInBlake160, true ) @@ -2850,11 +2850,11 @@ describe('TransactionGenerator', () => { }) it('account capacity enough for fee', async () => { const input = createInput(alice.lockScript, undefined, '0x' + '0'.repeat(64)) - const asssetAccountInput = input.toModel() - asssetAccountInput.capacity = toShannon('62') + const assetAccountInput = input.toModel() + assetAccountInput.capacity = toShannon('62') const res = await TransactionGenerator.generateDestroyAssetAccountTx( alice.walletId, - [asssetAccountInput], + [assetAccountInput], bob.publicKeyInBlake160, true ) @@ -2870,13 +2870,13 @@ describe('TransactionGenerator', () => { args: '0x2619a9dc0428f87c0921ed22d0f10707c5c4ec9e8185764d8236d7ea996a9b03', } const input = createInput(alice.lockScript, typeScript, '0x' + '0'.repeat(64)) - const asssetAccountInput = input.toModel() - asssetAccountInput.capacity = toShannon('142') - asssetAccountInput.data = BufferUtils.writeBigUInt128LE(BigInt('10')) + const assetAccountInput = input.toModel() + assetAccountInput.capacity = toShannon('142') + assetAccountInput.data = BufferUtils.writeBigUInt128LE(BigInt('10')) await expect( TransactionGenerator.generateDestroyAssetAccountTx( alice.walletId, - [asssetAccountInput], + [assetAccountInput], bob.publicKeyInBlake160, false ) @@ -2889,11 +2889,11 @@ describe('TransactionGenerator', () => { args: '0x2619a9dc0428f87c0921ed22d0f10707c5c4ec9e8185764d8236d7ea996a9b03', } const input = createInput(alice.lockScript, typeScript, '0x' + '0'.repeat(64)) - const asssetAccountInput = input.toModel() - asssetAccountInput.capacity = toShannon('142') + const assetAccountInput = input.toModel() + assetAccountInput.capacity = toShannon('142') const res = await TransactionGenerator.generateDestroyAssetAccountTx( alice.walletId, - [asssetAccountInput], + [assetAccountInput], bob.publicKeyInBlake160, false )