ckb_sdk/types/
script_group.rs

1use std::fmt;
2
3use ckb_types::packed::Script;
4use serde_derive::{Deserialize, Serialize};
5
6/// A script group is defined as scripts that share the same hash.
7///
8/// A script group will only be executed once per transaction, the
9/// script itself should check against all inputs/outputs in its group
10/// if needed.
11#[derive(Clone, Eq, PartialEq, Debug)]
12pub struct ScriptGroup {
13    /// The script.
14    ///
15    /// A script group is a group of input and output cells that share the same script.
16    pub script: Script,
17    /// The script group type.
18    pub group_type: ScriptGroupType,
19    /// Indices of input cells.
20    pub input_indices: Vec<usize>,
21    /// Indices of output cells.
22    pub output_indices: Vec<usize>,
23}
24
25impl ScriptGroup {
26    /// Creates a new script group struct.
27    pub fn new(script: &Script, group_type: ScriptGroupType) -> Self {
28        Self {
29            group_type,
30            script: script.to_owned(),
31            input_indices: vec![],
32            output_indices: vec![],
33        }
34    }
35
36    /// Creates a lock script group.
37    pub fn from_lock_script(script: &Script) -> Self {
38        Self::new(script, ScriptGroupType::Lock)
39    }
40
41    /// Creates a type script group.
42    pub fn from_type_script(script: &Script) -> Self {
43        Self::new(script, ScriptGroupType::Type)
44    }
45}
46
47/// The script group type.
48///
49/// A cell can have a lock script and an optional type script. Even they reference the same script,
50/// lock script and type script will not be grouped together.
51#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
52#[serde(rename_all = "snake_case")]
53pub enum ScriptGroupType {
54    /// Lock script group.
55    Lock,
56    /// Type script group.
57    Type,
58}
59
60impl fmt::Display for ScriptGroupType {
61    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62        match self {
63            ScriptGroupType::Lock => write!(f, "Lock"),
64            ScriptGroupType::Type => write!(f, "Type"),
65        }
66    }
67}