1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use std::{collections::HashMap, iter::repeat, sync::Arc, time::Duration};

use cubist_config::{paths::ContractFQN, util::OrBug, Config, Target};
use ethers::providers::Middleware;
use futures::future::JoinAll;

use crate::Result;

use super::{Contract, ContractInfo, HttpStack, TargetProject, TargetProjectInfo, WsStack};

type Map<K, V> = HashMap<K, V>;

/// Top-level type to use to manage configured contracts and target chains.
pub struct CubistInfo {
    /// Per-target projects.
    pub projects: Map<Target, TargetProjectInfo>,
    /// Per-target native (non-shim) contracts.
    pub contracts: Map<Target, Vec<ContractInfo>>,
    /// Per-target shim contracts.
    pub shims: Map<Target, Vec<ContractInfo>>,
    /// Underlying config.
    config: Config,
}

impl CubistInfo {
    /// Constructor
    pub fn new(config: Config) -> Result<Self> {
        let mut projects = Map::new();
        let mut contracts = Map::new();
        let mut shims = Map::new();

        for target in config.targets() {
            let proj = TargetProjectInfo::new(&config, target)?;
            projects.insert(target, proj);
        }

        for (target, proj) in &projects {
            let target_shims = proj.find_shim_contracts()?;
            shims.insert(*target, target_shims);

            let target_contracts = proj.find_contracts()?;
            contracts.insert(*target, target_contracts);
        }

        Ok(Self {
            projects,
            contracts,
            shims,
            config,
        })
    }

    /// Return all targets for which contract `fqn` has a shim.
    pub fn shim_targets<'a>(&'a self, fqn: &'a ContractFQN) -> impl Iterator<Item = Target> + '_ {
        self.shims.iter().filter_map(|(t, cs)| {
            if cs.iter().any(|c| c.fqn == *fqn) {
                Some(*t)
            } else {
                None
            }
        })
    }

    /// Return an iterator over all target-specific projects.
    pub fn projects(&self) -> impl Iterator<Item = &TargetProjectInfo> {
        self.projects.values()
    }

    /// Return project for a given target.
    pub fn project(&self, t: Target) -> Option<&TargetProjectInfo> {
        self.projects.get(&t)
    }

    /// Return an iterator over all non-shim contracts.
    pub fn contracts(&self) -> impl Iterator<Item = &ContractInfo> {
        self.contracts.values().flatten()
    }

    /// Return an iterator over all shim contracts.
    pub fn shims(&self) -> impl Iterator<Item = &ContractInfo> {
        self.shims.values().flatten()
    }

    /// Get the underlying config
    pub fn config(&self) -> &Config {
        &self.config
    }
}

/// Top-level type to use to manage configured contracts and target chains.
pub struct Cubist<M: Middleware = HttpStack> {
    /// Per-target projects.
    projects: Map<Target, Arc<TargetProject<M>>>,
    /// Per-target native (non-shim) contracts.
    contracts: Map<Target, Vec<Arc<Contract<M>>>>,
    /// Per-target shim contracts.
    shims: Map<Target, Vec<Arc<Contract<M>>>>,
    /// Underlying config.
    config: Config,
}

impl<M: Middleware> Clone for Cubist<M> {
    /// Create a new [`Cubist`] instance for the same Cubist project.
    /// [`Contract`]s returned by different [`Cubist`] instances are
    /// deployable independently of each other.
    fn clone(&self) -> Cubist<M> {
        Self::new_from_projects(self.projects.clone(), self.config.clone()).unwrap()
    }
}

macro_rules! cubist_constructor {
    ($config: expr, $ty: ty) => {{
        let mut projects = Map::new();
        for target in $config.targets() {
            let proj = TargetProjectInfo::new(&$config, target)?;
            let proj = TargetProject::<$ty>::create(proj).await?;
            projects.insert(target, Arc::new(proj));
        }
        Self::new_from_projects(projects, $config)
    }};
}

impl Cubist<HttpStack> {
    /// Create a new [`Cubist`] HTTP instance from a Cubist config.
    pub async fn new(config: Config) -> Result<Self> {
        cubist_constructor!(config, HttpStack)
    }
}

impl Cubist<WsStack> {
    /// Create a new [`Cubist`] WS instance from a Cubist config.
    pub async fn new(config: Config) -> Result<Self> {
        cubist_constructor!(config, WsStack)
    }
}

impl<M: Middleware> Cubist<M> {
    /// Create a new [`Cubist`] instance from a set of per-target-chain projects
    pub fn new_from_projects(
        projects: HashMap<Target, Arc<TargetProject<M>>>,
        config: Config,
    ) -> Result<Self> {
        let mut contracts = Map::new();
        let mut shims = Map::new();

        // pass 1: create shim contracts for each target
        for (target, proj) in &projects {
            let target_shims = proj
                .find_shim_contracts()?
                .into_iter()
                .map(|cc| Arc::new(Contract::shim(Arc::clone(proj), cc)))
                .collect::<Vec<_>>();
            shims.insert(*target, target_shims);
        }

        let find_shims = |cc: &ContractInfo| {
            shims
                .iter()
                .filter_map(|(target, shims)| {
                    shims
                        .iter()
                        .find(|shim| shim.meta.fqn == cc.fqn)
                        .map(|shim| (*target, Arc::clone(shim)))
                })
                .collect::<HashMap<_, _>>()
        };

        // pass 2: create non-shim contracts for each target (each of which receives all of its shims)
        for (target, proj) in &projects {
            let target_shims = shims.get(target).or_bug("Shims for target missing");
            let target_contracts = proj
                .find_contracts()?
                .into_iter()
                .map(|cc| {
                    Arc::new(Contract::new(
                        Arc::clone(proj),
                        find_shims(&cc),
                        target_shims
                            .iter()
                            .filter(|shim| proj.is_dependency(&cc, &shim.meta))
                            .map(Clone::clone)
                            .collect::<Vec<_>>(),
                        cc,
                    ))
                })
                .collect::<Vec<_>>();
            contracts.insert(*target, target_contracts);
        }

        Ok(Cubist {
            projects,
            contracts,
            shims,
            config,
        })
    }

    /// Returns a future that completes once all initialized contracts in
    /// this project have been bridged (in which case the result is
    /// `true`) or when the timeout (of 10s by default) expires (in
    /// which case the result is `false`).
    ///
    /// # Arguments
    /// * `delays` - how long to wait between retries (defaults to 100ms for 100 times)
    pub async fn when_bridged(&self, delays: Option<Vec<Duration>>) -> bool {
        let delays =
            delays.unwrap_or_else(|| repeat(Duration::from_millis(100)).take(100).collect());
        self.contracts()
            .filter(|c| c.is_deployed())
            .collect::<Vec<_>>()
            .iter()
            .map(|c| c.when_bridged(&delays))
            .collect::<JoinAll<_>>()
            .await
            .iter()
            .all(|b| *b)
    }

    /// Find a (non-shim) contract by its name.
    pub fn contract(&self, name: &str) -> Option<Arc<Contract<M>>> {
        for tc in self.contracts.values() {
            for c in tc {
                if c.meta.fqn.name == name {
                    return Some(Arc::clone(c));
                }
            }
        }
        None
    }

    /// Find a contract for a target given whether it's a shim and its fully qualified name.
    pub fn find_contract(
        &self,
        target: Target,
        is_shim: bool,
        fqn: &ContractFQN,
    ) -> Option<Arc<Contract<M>>> {
        (if is_shim {
            &self.shims
        } else {
            &self.contracts
        })
        .get(&target)
        .and_then(|contracts| contracts.iter().find(|c| c.meta.fqn == *fqn))
        .map(Arc::clone)
    }

    /// Return an iterator over all target-specific projects.
    pub fn projects(&self) -> impl Iterator<Item = Arc<TargetProject<M>>> + '_ {
        self.projects.values().map(Arc::clone)
    }

    /// Return project for a given target.
    pub fn project(&self, t: Target) -> Option<Arc<TargetProject<M>>> {
        self.projects.get(&t).map(Arc::clone)
    }

    /// Return an iterator over all non-shim contracts.
    pub fn contracts(&self) -> impl Iterator<Item = Arc<Contract<M>>> + '_ {
        self.contracts.values().flatten().map(Arc::clone)
    }

    /// Get the underlying contract map.
    pub fn contract_map(&self) -> Map<Target, Vec<Arc<Contract<M>>>> {
        self.contracts.clone()
    }

    /// Return an iterator over all shim contracts.
    pub fn shims(&self) -> impl Iterator<Item = Arc<Contract<M>>> + '_ {
        self.shims.values().flatten().map(Arc::clone)
    }

    /// Get the underlying config
    pub fn config(&self) -> &Config {
        &self.config
    }
}