Skip to content

Commit

Permalink
refactor: remove address and script convertion from ckb-sdk-js (#2801)
Browse files Browse the repository at this point in the history
* refactor: remove address <--> script convertion of ckb-sdk-js

* chore: prettier

* Update packages/neuron-wallet/src/services/cells.ts

Co-authored-by: WhiteMind <[email protected]>

* Update packages/neuron-wallet/src/services/transaction-sender.ts

Co-authored-by: WhiteMind <[email protected]>

---------

Co-authored-by: WhiteMind <[email protected]>
  • Loading branch information
zhangyouxin and WhiteMinds authored Aug 24, 2023
1 parent 2652061 commit 9d585fe
Show file tree
Hide file tree
Showing 19 changed files with 193 additions and 71 deletions.
2 changes: 2 additions & 0 deletions packages/neuron-wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
"@ckb-lumos/bi": "0.20.0-alpha.3",
"@ckb-lumos/ckb-indexer": "0.20.0-alpha.3",
"@ckb-lumos/codec": "0.20.0-alpha.3",
"@ckb-lumos/config-manager": "0.20.0-alpha.3",
"@ckb-lumos/helpers": "0.20.0-alpha.3",
"@ckb-lumos/rpc": "0.20.0-alpha.3",
"@iarna/toml": "2.2.5",
"@ledgerhq/hw-transport-node-hid": "6.27.16",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getConnection } from 'typeorm'
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../utils/scriptAndAddress'
import OutputEntity from '../../database/chain/entities/output'
import NetworksService from '../../services/networks'
import Output from '../../models/chain/output'
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/asset-account.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../utils/scriptAndAddress'
import AssetAccount from '../models/asset-account'
import Transaction from '../models/chain/transaction'
import AssetAccountService from '../services/asset-account-service'
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/controllers/multisig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import fs from 'fs'
import path from 'path'
import { dialog, BrowserWindow } from 'electron'
import { t } from 'i18next'
import { addressToScript, scriptToAddress, scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress, addressToScript } from '../utils/scriptAndAddress'
import { ResponseCode } from '../utils/const'
import MultisigConfig from '../database/chain/entities/multisig-config'
import MultisigConfigModel from '../models/multisig-config'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MigrationInterface, QueryRunner } from "typeorm";
import { scriptToAddress, addressToScript } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress, addressToScript } from '../../../utils/scriptAndAddress'
import AddressDescription from '../entities/address-description'

export class UpdateAddressDescription1650984779265 implements MigrationInterface {
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/models/keys/address.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AddressPrefix, blake160, scriptToAddress, systemScripts, bytesToHex } from '@nervosnetwork/ckb-sdk-utils'
import { AddressPrefix, blake160, systemScripts, bytesToHex } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../utils/scriptAndAddress'

import { AccountExtendedPublicKey } from './key'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../utils/scriptAndAddress'
import SystemScriptInfo from '../../models/system-script-info'
import NetworksService from '../../services/networks'
import Address, { AddressType } from './address'
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/services/cells.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getConnection, In } from 'typeorm'
import { addressToScript, scriptToAddress, scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToHash } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress, addressToScript } from '../utils/scriptAndAddress'
import {
CapacityNotEnough,
CapacityNotEnoughForChange,
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/src/services/transaction-sender.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import ECPair from '@nervosnetwork/ckb-sdk-utils/lib/ecpair'
import signWitnesses from '@nervosnetwork/ckb-sdk-core/lib/signWitnesses'
import NodeService from './node'
import { scriptToAddress, serializeWitnessArgs, toUint64Le } from '@nervosnetwork/ckb-sdk-utils'
import { serializeWitnessArgs, toUint64Le } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../utils/scriptAndAddress'
import { TransactionPersistor, TransactionGenerator, TargetOutput } from './tx'
import AddressService from './addresses'
import WalletService, { Wallet } from '../services/wallets'
Expand Down
25 changes: 25 additions & 0 deletions packages/neuron-wallet/src/utils/scriptAndAddress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Script } from '@ckb-lumos/base'
import { predefined } from '@ckb-lumos/config-manager'
import { encodeToAddress, parseAddress } from '@ckb-lumos/helpers'

export const scriptToAddress = (script: CKBComponents.Script, isMainnet = true): string => {
const lumosConfig = !isMainnet ? predefined.AGGRON4 : predefined.LINA
return encodeToAddress(
// omit keys other than codeHash, args and hashType
{
codeHash: script.codeHash,
args: script.args,
hashType: script.hashType,
},
{ config: lumosConfig }
)
}

export const addressToScript = (address: string): Script => {
const prefix = address.slice(0, 3)
if (prefix !== 'ckt' && prefix !== 'ckb') {
throw new Error('Invalid address prefix')
}
const lumosConfig = prefix === 'ckt' ? predefined.AGGRON4 : predefined.LINA
return parseAddress(address, { config: lumosConfig })
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../src/utils/scriptAndAddress'
import { when } from 'jest-when'
import { AddressType } from '../../src/models/keys/address'
import { Address, AddressVersion } from '../../src/models/address'
Expand Down Expand Up @@ -237,7 +237,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', () => {
Expand All @@ -253,7 +256,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', () => {
Expand Down
53 changes: 35 additions & 18 deletions packages/neuron-wallet/tests/block-sync-renderer/queue.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Subject } from 'rxjs'
import { Tip } from '@ckb-lumos/base'
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../src/utils/scriptAndAddress'
import { AddressType } from '../../src/models/keys/address'
import SystemScriptInfo from '../../src/models/system-script-info'
import { Address, AddressVersion } from '../../src/models/address'
Expand Down Expand Up @@ -123,7 +123,7 @@ describe('queue', () => {
jest.useFakeTimers('legacy')

stubbedBlockTipsSubject = new Subject<Tip>()
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 {
Expand Down Expand Up @@ -175,11 +175,11 @@ describe('queue', () => {
return {
createBatchRequest() {
return {
exec: stubbedRPCCreateBatchRequestExecFn
exec: stubbedRPCCreateBatchRequestExecFn,
}
}
},
}
}
},
}
})
const Queue = require('../../src/block-sync-renderer/sync/queue').default
Expand Down Expand Up @@ -223,10 +223,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)
Expand All @@ -250,11 +257,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]),
SystemScriptInfo.generateSecpScript(addressInfo.blake160).computeHash().slice(0, 42),
])
)
}
})
it('checks and generate new addresses', () => {
Expand All @@ -276,10 +286,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 () => {
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-wallet/tests/controllers/multisig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { ResponseCode } from '../../src/utils/const'
import MultisigService from '../../src/services/multisig'
import MultisigController from '../../src/controllers/multisig'
import CellsService from '../../src/services/cells'
import { scriptToAddress, systemScripts } from '@nervosnetwork/ckb-sdk-utils'
import { systemScripts } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../src/utils/scriptAndAddress'

let response = 0
let dialogRes = { canceled: false, filePaths: ['./'], filePath: './' }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { scriptToAddress, systemScripts } from '@nervosnetwork/ckb-sdk-utils'
import { systemScripts } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../../src/utils/scriptAndAddress'
import { AddressType } from '../../../src/models/keys/address'
import KeyInfos from '../../setupAndTeardown/public-key-info.fixture'

Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/tests/services/cells.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getConnection } from 'typeorm'
import { scriptToAddress } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../src/utils/scriptAndAddress'
import { bytes } from '@ckb-lumos/codec'
import { initConnection } from '../../src/database/chain/ormconfig'
import OutputEntity from '../../src/database/chain/entities/output'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ 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 { serializeWitnessArgs, scriptToAddress, addressToScript } from '@nervosnetwork/ckb-sdk-utils'
import { serializeWitnessArgs, addressToScript } from '@nervosnetwork/ckb-sdk-utils'
import { scriptToAddress } from '../../../src/utils/scriptAndAddress'
import {
CapacityNotEnough,
CurrentWalletNotSet,
Expand Down
Loading

2 comments on commit 9d585fe

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

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

Packaging for test is done in 5961427528

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

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

Packaging for test is done in 5961429378

Please sign in to comment.