ckb_sdk/types/
script_id.rs1use std::convert::TryFrom;
2use std::fmt;
3
4use crate::constants::{DAO_TYPE_HASH, TYPE_ID_CODE_HASH};
5use ckb_types::{core::ScriptHashType, packed::Script, prelude::*, H256};
6
7#[derive(Clone, Hash, Eq, PartialEq, Debug, Default)]
8pub struct ScriptId {
9 pub code_hash: H256,
10 pub hash_type: ScriptHashType,
11}
12
13impl ScriptId {
14 pub const fn new(code_hash: H256, hash_type: ScriptHashType) -> ScriptId {
15 ScriptId {
16 code_hash,
17 hash_type,
18 }
19 }
20 pub fn new_data(code_hash: H256) -> ScriptId {
21 Self::new(code_hash, ScriptHashType::Data)
22 }
23 pub const fn new_data1(code_hash: H256) -> ScriptId {
24 Self::new(code_hash, ScriptHashType::Data1)
25 }
26 pub const fn new_type(code_hash: H256) -> ScriptId {
27 Self::new(code_hash, ScriptHashType::Type)
28 }
29
30 pub fn is_type_id(&self) -> bool {
31 self.code_hash == TYPE_ID_CODE_HASH && self.hash_type == ScriptHashType::Type
32 }
33
34 pub fn is_dao(&self) -> bool {
35 self.code_hash == DAO_TYPE_HASH && self.hash_type == ScriptHashType::Type
36 }
37
38 pub fn dummy_type_id_script(&self) -> Script {
40 Script::new_builder()
41 .code_hash(self.code_hash.pack())
42 .hash_type(self.hash_type)
43 .args(<[u8]>::pack(&[0u8; 32]))
44 .build()
45 }
46}
47
48impl From<&Script> for ScriptId {
49 fn from(script: &Script) -> ScriptId {
50 let code_hash: H256 = script.code_hash().unpack();
51 let hash_type = ScriptHashType::try_from(script.hash_type()).expect("hash type");
52 ScriptId {
53 code_hash,
54 hash_type,
55 }
56 }
57}
58
59impl fmt::Display for ScriptId {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(
62 f,
63 "code_hash={:?}, hash_type={:?}",
64 self.code_hash, self.hash_type
65 )
66 }
67}