diff --git a/packages/ckb-sdk-utils/__tests__/ckb-utils.test.js b/packages/ckb-sdk-utils/__tests__/ckb-utils.test.js index a917f098..05464278 100644 --- a/packages/ckb-sdk-utils/__tests__/ckb-utils.test.js +++ b/packages/ckb-sdk-utils/__tests__/ckb-utils.test.js @@ -128,15 +128,9 @@ describe('scriptToHash', () => { script: { codeHash: '0x0000000000000000000000000000000000000000000000000000000000000000', args: [], + hashType: 'data', }, - scriptHash: 'c371c8d6a0aed6018e91202d047c35055cfb0228e6709f1cd1d5f756525628b9', - }, - 'Script with default hash type of data': { - script: { - codeHash: '0x0000000000000000000000000000000000000000000000000000000000000000', - args: ['0x01'], - }, - scriptHash: 'cd5b0c29b8f5528d3a75e3918576db4d962a1d4b315dff7d3c50818cc373b3f5', + scriptHash: 'bd7e6000ffb8e983a6023809037e0c4cedbc983637c46d74621fd28e5f15fe4f', }, 'Script with hash type of data': { script: { @@ -144,7 +138,7 @@ describe('scriptToHash', () => { args: ['0x01'], hashType: 'data', }, - scriptHash: 'cd5b0c29b8f5528d3a75e3918576db4d962a1d4b315dff7d3c50818cc373b3f5', + scriptHash: '5a2b913dfb1b79136fc72a575fd8e93ae080b504463c0066fea086482bfc3a94', }, 'Script with hash type of type': { script: { @@ -152,7 +146,7 @@ describe('scriptToHash', () => { args: ['0x01'], hashType: 'type', }, - scriptHash: '7bc53ae03b219a1cb520fce8ac2299092958147db23d92d3a97b3a9dec748d94', + scriptHash: '3d7e565f3831955f0f5cfecdadddeef7e0d106af84ceb0c2f4dbb6ddff88c9bc', }, } test.each(Object.keys(fixtures))('%s', fixtureName => { diff --git a/packages/ckb-sdk-utils/src/index.ts b/packages/ckb-sdk-utils/src/index.ts index 03b859f0..8028ede6 100644 --- a/packages/ckb-sdk-utils/src/index.ts +++ b/packages/ckb-sdk-utils/src/index.ts @@ -1,5 +1,6 @@ import * as util from 'util' import crypto from './crypto' +import { serializeScript } from './serialization' export * from './address' export * from './serialization' @@ -43,22 +44,11 @@ export const utf8ToBytes = (str: string) => textEncoder.encode(str) export const utf8ToHex = (str: string) => bytesToHex(utf8ToBytes(str)) -export const scriptToHash = ({ codeHash = '', args = [], hashType = 'data' }: CKBComponents.Script) => { +export const scriptToHash = (script: CKBComponents.Script) => { + if (!script) throw new Error('Script is required') + const serializedScript = serializeScript(script) const s = blake2b(32, null, null, PERSONAL) - if (codeHash) { - s.update(hexToBytes(codeHash.replace(/^0x/, ''))) - } - - if (hashType === 'data') { - s.update(Buffer.from([0x0])) - } else { - s.update(Buffer.from([0x1])) - } - - if (args && args.length) { - args.forEach(arg => (typeof arg === 'string' ? s.update(hexToBytes(arg)) : s.update(arg))) - } - + s.update(hexToBytes(serializedScript)) const digest = s.digest('hex') return digest as string }