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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use cubist_config::bridge::Bridge;
use cubist_config::paths::{ContractFQN, Paths, TargetPaths};
use cubist_config::secret::SecretUrl;
use cubist_config::util::OrBug;
use cubist_config::{
    network::EndpointConfig, Compiler, CompilerConfig, Config, NetworkName, PreCompileManifest,
    Target,
};
use cubist_localchains::provider::Provider as CubistProvider;
use ethers::abi::Tokenize;
use ethers::prelude::transformer::TransformerMiddleware;
use ethers::prelude::*;
use ethers::providers::Provider;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::{convert::TryFrom, sync::Arc};
use tracing::debug;

use crate::core::LegacyTransformer;
use crate::target_handler::solang::SolangCompiler;
use crate::target_handler::solc::SolcCompiler;
use crate::{ContractInfo, CubistSdkError, Result, WrapperError};

type EthersContract<M> = ethers::contract::Contract<M>;

/// Deployment info for a single contract (either shim or not).
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct DeploymentInfo {
    /// Chain to which the contract was deployed
    pub target: Target,

    /// Contract address
    pub address: Address,
}

/// Per-contract manifest generated by the deployer.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct DeploymentManifest {
    /// Deployed contract
    pub contract: ContractFQN,
    /// Non-shim contract's deployment info
    #[serde(flatten)]
    pub deployment: DeploymentInfo,
    /// All of its shims' deployment infos
    pub shims: Vec<DeploymentInfo>,
}

impl DeploymentManifest {
    /// Writes the manifest to a file atomically, which guarantees
    /// that the "deployment watcher" reads it after it has been
    /// flushed.
    pub fn write_atomic(&self, path: &Path) -> Result<(), WrapperError> {
        let content = serde_json::to_string_pretty(self).map_err(|e| {
            WrapperError::JsonError(path.to_path_buf(), "DeploymentManifest".to_owned(), e)
        })?;
        let tmp_file = path.with_extension("tmp");
        let parent_dir = tmp_file.parent().unwrap();
        fs::create_dir_all(parent_dir)
            .map_err(|e| WrapperError::IOError(parent_dir.to_path_buf(), e))?;
        fs::write(&tmp_file, content)
            .map_err(|e| WrapperError::IOError(tmp_file.to_path_buf(), e))?;
        fs::rename(&tmp_file, path)
            .map_err(|e| WrapperError::IOError(tmp_file.to_path_buf(), e))?;
        Ok(())
    }
}

/// The result of a contract compilation.
pub struct CompileResult {
    /// Diagnostics spit out by the compiler.
    pub diagnostics: String,
}

/// An abstraction for a contract compiler.
pub trait ContractCompiler {
    /// Clean build artifacts.
    fn clean(&self) -> Result<()>;

    /// Compile a given contract file.
    fn compile_file(&self, file: &Path) -> Result<CompileResult>;

    /// Find all compiled contracts (on disk) originating from a given source file.
    fn find_compiled_contracts(
        &self,
        source_file: &Path,
    ) -> Result<HashMap<NetworkName, ContractInfo>>;
}

type HttpProvider = Provider<Http>;
type WsProvider = Provider<Ws>;

type Stack<M> = TransformerMiddleware<M, LegacyTransformer>;

/// Type alias for a middleware implementation over HTTP that transforms requests into legacy
/// requests and signs them. The signer sends requests directly through the HTTP provider, because
/// it only issues requests that are answered by the proxy itself, which supports EIP-1599
/// transactions.
pub type HttpStack = Stack<HttpProvider>;

/// Same as `MiddlewareStack` but over web sockets
pub type WsStack = Stack<WsProvider>;

/// Metadata about a project target a single chain.
pub struct TargetProjectInfo {
    /// Target chain (e.g., "avalanche", "polygon", etc.)
    pub target: Target,
    /// Compiler to use to compile `source_contracts` (e.g., "solc", "solang", etc.)
    pub compiler: Compiler,
    /// The compiler configuration to use for compiling contracts
    compiler_config: CompilerConfig,
    /// Well-known paths for the whole app
    pub paths: Paths,
    /// Per-target well-known paths
    pub target_paths: TargetPaths,
    /// Optional network configuration (for deployment).
    pub network_config: Option<EndpointConfig>,
    /// Manifest containing paths to source contracts and generated shims.
    manifest: PreCompileManifest,
}

/// Generic project targeting a single chain either via HTTP or WS.
pub struct TargetProject<M: Middleware = HttpStack> {
    /// Project for this chain
    project: TargetProjectInfo,
    /// Provider for this chain.
    provider: Arc<M>,
}

/// Instances of [`TargetProject`] can be automatically dereferenced
/// to [`TargetProjectInfo`].
impl<M: Middleware> std::ops::Deref for TargetProject<M> {
    type Target = TargetProjectInfo;

    fn deref(&self) -> &Self::Target {
        &self.project
    }
}

async fn wrap<M: JsonRpcClient>(provider: Provider<M>) -> Result<Stack<Provider<M>>, WrapperError> {
    let provider = provider.interval(Duration::from_millis(50));

    // Use the first account for all requests if it exists
    // TODO(#261): Allow configuration to override it
    let address = provider
        .get_accounts()
        .await
        .map_err(|e| WrapperError::ProviderError("get_accounts".to_owned(), e.to_string()))?
        .get(0)
        .copied();

    let provider = match address {
        Some(address) => provider.with_sender(address),
        None => provider,
    };

    // TODO(#261): Allow configuration to override gas price
    let gas_price = provider
        .get_gas_price()
        .await
        .map_err(|e| WrapperError::ProviderError("get_gas_price".to_owned(), e.to_string()))?;
    Ok(TransformerMiddleware::new(
        provider,
        LegacyTransformer { gas_price },
    ))
}

/// Factory method for creating an ethers provider over HTTP
async fn create_provider_http(url: &SecretUrl) -> Result<HttpStack, WrapperError> {
    let http_scheme = to_http_scheme(url.scheme());
    let exposed_url = url
        .expose_url_and_update(Some(http_scheme), None, None)
        .map_err(WrapperError::ConfigError)?;

    let provider = HttpProvider::try_from(exposed_url.as_str()).map_err(WrapperError::UrlError)?;

    wrap(provider).await
}

/// Factory method for creating an ethers provider over WS
async fn create_provider_ws(url: &SecretUrl) -> Result<WsStack, WrapperError> {
    let ws_scheme = to_ws_scheme(url.scheme());
    let exposed_url = url
        .expose_url_and_update(Some(ws_scheme), None, None)
        .map_err(WrapperError::ConfigError)?;
    let provider = WsProvider::connect(exposed_url.as_str())
        .await
        .map_err(|e| WrapperError::ProviderError("connect".to_owned(), e.to_string()))?;
    wrap(provider).await
}

impl TargetProjectInfo {
    /// Creates a [`TargetProject`] for that target.
    pub fn new(cubist_config: &Config, target: Target) -> Result<Self> {
        let paths = cubist_config.paths();
        let my_paths = paths
            .try_for_target(target)
            .ok_or(CubistSdkError::MissingTarget(target))?
            .to_owned();
        let manifest = PreCompileManifest::from_file(&my_paths.manifest)
            .map_err(|e| CubistSdkError::MissingManifest(target, e))?;
        let contracts = cubist_config.contracts();
        let target_config = contracts
            .targets
            .get(&target)
            .ok_or(CubistSdkError::MissingTarget(target))?;
        let network_config = cubist_config.network_for_target(target);
        Ok(TargetProjectInfo {
            paths,
            target_paths: my_paths,
            compiler: target_config.compiler,
            compiler_config: cubist_config.get_compiler_config(),
            target,
            network_config,
            manifest,
        })
    }
}

impl TargetProjectInfo {
    /// Connect to the endpoint using HTTP
    pub async fn connect(self) -> Result<TargetProject<HttpStack>> {
        TargetProject::<HttpStack>::create(self).await
    }

    /// Connect to the endpoint using Web Sockets
    pub async fn connect_ws(self) -> Result<TargetProject<WsStack>> {
        TargetProject::<WsStack>::create(self).await
    }

    /// Return absolute paths to all contract files.
    pub fn contract_files(&self) -> impl Iterator<Item = PathBuf> + '_ {
        self.manifest
            .contract_files()
            .map(|rel| self.target_paths.contracts.join(rel))
    }

    /// Clean build artifacts
    pub fn clean(&self) -> Result<()> {
        self.compiler().clean()
    }

    /// Compile a contract file.
    pub fn compile_file(&self, file: &Path) -> Result<CompileResult> {
        self.compiler().compile_file(file)
    }

    /// Whether contract `cc` is allowed to call contract `dep` (i.e.,
    /// whether `dep` is a dependency of `cc`)
    pub fn is_dependency(&self, cc: &ContractInfo, dep: &ContractInfo) -> bool {
        self.manifest.is_dependency(&cc.fqn, &dep.fqn)
    }

    /// Find all shim contracts generated for this chain.
    pub fn find_shim_contracts(&self) -> Result<Vec<ContractInfo>> {
        let mut result = Vec::new();
        for source_file in self.manifest.shim_files() {
            for contract in self.find_compiled_contracts(source_file)?.into_values() {
                result.push(contract);
            }
        }
        Ok(result)
    }

    /// Find all (non-shim) contracts targeting this chain.
    pub fn find_contracts(&self) -> Result<Vec<ContractInfo>> {
        let mut result = Vec::new();
        for source_file in self.manifest.contract_files() {
            for contract in self.find_compiled_contracts(source_file)?.into_values() {
                result.push(contract);
            }
        }
        Ok(result)
    }

    /// Find a non-shim contract targeting this chain by its name.
    pub fn contract(&self, name: &str) -> Result<Option<ContractInfo>> {
        let c = self
            .find_contracts()?
            .into_iter()
            .find(|c| c.fqn.name == name);
        Ok(c)
    }

    /// Find a shim contract targeting for chain by its name.
    pub fn shim_contract(&self, name: &str) -> Result<Option<ContractInfo>> {
        let c = self
            .find_shim_contracts()?
            .into_iter()
            .find(|c| c.fqn.name == name);
        Ok(c)
    }

    /// Creates a new instance of a compiler.
    fn compiler(&self) -> Box<dyn ContractCompiler> {
        match self.compiler {
            Compiler::Solc => {
                Box::new(SolcCompiler::new(&self.compiler_config, &self.target_paths))
            }
            Compiler::Solang => Box::new(SolangCompiler),
        }
    }

    /// Find all compiled contracts (on disk) originating from a given source file.
    fn find_compiled_contracts(&self, source_file: &Path) -> Result<HashMap<String, ContractInfo>> {
        self.compiler().find_compiled_contracts(source_file)
    }

    /// Create a cubist localchains provider ([`CubistProvider`]) from a
    /// given [`EndpointConfig`] then return that provider's endpoint url.
    pub fn endpoint_url(&self) -> Result<SecretUrl> {
        let provider: Box<dyn CubistProvider> = self
            .network_config
            .as_ref()
            .ok_or(CubistSdkError::MissingNetworkConfig(self.target))?
            .clone()
            .try_into()?;
        Ok(provider.url())
    }
}

macro_rules! project_constructor {
    ($project: expr, $provider_fn: expr) => {{
        let url = $project.endpoint_url()?;
        let provider = $provider_fn(&url).await.map_err(|e| {
            CubistSdkError::CreateClientError($project.target.clone(), url, Some(e))
        })?;
        Ok(Self::new($project, provider))
    }};
}

impl TargetProject<HttpStack> {
    /// Factory method for connections over HTTP
    pub async fn create(project: TargetProjectInfo) -> Result<Self> {
        project_constructor!(project, create_provider_http)
    }
}

impl TargetProject<WsStack> {
    /// Factory method for connections over Web Sockets
    pub async fn create(project: TargetProjectInfo) -> Result<Self> {
        project_constructor!(project, create_provider_ws)
    }
}

impl<M: Middleware> TargetProject<M> {
    /// Constructor
    pub fn new(project: TargetProjectInfo, provider: M) -> Self {
        Self {
            project,
            provider: Arc::new(provider),
        }
    }

    /// Create new or return existing deployer for this project.
    pub fn provider(&self) -> Arc<M> {
        Arc::clone(&self.provider)
    }

    /// Retrieve all accounts used on this target.
    pub async fn accounts(&self) -> Result<Vec<Address>> {
        let acc = self
            .provider
            .get_accounts()
            .await
            .map_err(|e| CubistSdkError::AccountsError(self.target, format!("{e}")))?;
        Ok(acc)
    }

    /// Return default sender
    pub async fn sender(&self) -> Result<Address> {
        self.provider.default_sender().ok_or_else(|| {
            CubistSdkError::AccountsError(self.target, "No default sender".to_owned())
        })
    }

    /// Deploy a contract.
    pub async fn deploy<T: Tokenize>(
        &self,
        contract: &ContractInfo,
        constructor_args: T,
    ) -> Result<ethers::contract::Contract<M>> {
        let factory = ContractFactory::new(
            contract.abi.to_owned(),
            contract.bytes.to_owned(),
            self.provider(),
        );

        let deploy_err = |e: ContractError<M>| {
            CubistSdkError::DeployError(contract.fqn.clone(), self.target, e.to_string())
        };

        let deployer = factory.deploy(constructor_args).map_err(deploy_err)?;

        // TODO: the user should be able to specify 'gas' setting; otherwise, leave it empty
        //       instead of calling 'estimate_gas', because the estimation can be wrong

        let (deployed, receipt) = deployer.send_with_receipt().await.map_err(deploy_err)?;
        debug!(
            "Deployed {} to {} at {}",
            contract.fqn.name,
            self.target,
            deployed.address()
        );

        self.save_receipt(&contract.fqn, deployed.address(), &receipt)
            .await?;

        Ok(deployed)
    }

    /// Initialize a given contract with a given address
    pub fn at(&self, contract: &ContractInfo, address: Address) -> EthersContract<M> {
        debug!(
            "Initialized {}@{} to {address}",
            contract.fqn.name, self.target,
        );
        EthersContract::new(address, contract.abi.clone(), self.provider())
    }

    /// Initialize a given contract from its deployment receipt.
    /// Succeeds only if there is exactly one corresponding deployment receipt found.
    pub async fn deployed(&self, contract: &ContractInfo) -> Result<EthersContract<M>> {
        let receipts = self.find_receipts(&contract.fqn).await?;
        if receipts.is_empty() {
            Err(CubistSdkError::LoadContractNoReceipts(
                contract.fqn.clone(),
                self.target,
            ))
        } else if receipts.len() > 1 {
            Err(CubistSdkError::LoadContractTooManyReceipts(
                contract.fqn.clone(),
                self.target,
            ))
        } else {
            let rec = receipts.get(0).unwrap();
            Ok(self.at(
                contract,
                rec.contract_address
                    .expect("Transaction receipt should contain contract address"),
            ))
        }
    }

    /// Try to find and load bridge metadata for this contract.
    /// The bridge metadata file is expected to be co-located with the contract's source file.
    pub fn load_bridge(&self, cc: &ContractInfo) -> Result<Bridge> {
        let bridge_file = self.target_paths.for_bridge(&cc.fqn.file);
        let load_bridge_error =
            |e| CubistSdkError::LoadBridgeError(cc.fqn.clone(), bridge_file.clone(), e);
        let json = fs::read_to_string(&bridge_file)
            .map_err(|e| WrapperError::IOError(bridge_file.clone(), e))
            .map_err(load_bridge_error)?;
        let bridge = serde_json::from_str::<Bridge>(&json)
            .map_err(|e| WrapperError::JsonError(bridge_file.clone(), "Bridge".to_owned(), e))
            .map_err(load_bridge_error)?;
        Ok(bridge)
    }

    async fn save_receipt(
        &self,
        contract: &ContractFQN,
        address: Address,
        receipt: &TransactionReceipt,
    ) -> Result<()> {
        let path = self
            .target_paths
            .for_deployment_receipt(contract, address.as_fixed_bytes());
        let parent_dir = path.parent().or_bug("Must have a parent dir");

        async {
            tokio::fs::create_dir_all(parent_dir).await?;
            let content = serde_json::to_string_pretty(receipt)
                .or_bug("Serializing deployment receipt to json");
            tokio::fs::write(&path, content).await?;
            Ok(())
        }
        .await
        .map_err(|e| WrapperError::IOError(path.clone(), e))
        .map_err(|e| CubistSdkError::SaveDeploymentReceiptError(path.clone(), e))?;

        debug!("Saved deployment receipt to {}", path.display());
        Ok(())
    }

    async fn find_receipts(&self, contract: &ContractFQN) -> Result<Vec<TransactionReceipt>> {
        let dir = self.target_paths.deployment_receipts_dir(contract);
        if !dir.is_dir() {
            return Ok(vec![]);
        }
        let to_err =
            |e: WrapperError| CubistSdkError::DeserializeDeploymentReceiptError(dir.clone(), e);
        let mut receipts = vec![];
        let mut read_result = tokio::fs::read_dir(&dir)
            .await
            .map_err(|e| WrapperError::IOError(dir.clone(), e))
            .map_err(to_err)?;
        while let Some(dir_ent) = read_result
            .next_entry()
            .await
            .map_err(|e| WrapperError::IOError(dir.clone(), e))
            .map_err(to_err)?
        {
            let rec_path = dir_ent.path();
            if !rec_path.is_file() {
                continue;
            }
            // we don't expect anything other than valid transaction receipt files in this dir
            let contents = tokio::fs::read_to_string(&rec_path)
                .await
                .map_err(|e| WrapperError::IOError(rec_path.clone(), e))
                .map_err(to_err)?;
            let tr = serde_json::from_str::<TransactionReceipt>(&contents)
                .map_err(|e| {
                    WrapperError::JsonError(
                        rec_path.to_path_buf(),
                        "TransactionReceipt".to_owned(),
                        e,
                    )
                })
                .map_err(to_err)?;
            debug!(
                "Found receipt '{}' for contract {contract}",
                rec_path.display()
            );
            receipts.push(tr);
        }
        Ok(receipts)
    }
}

/// Creates a new instance of a validator. A validator is used to check whether source files are
/// error free before they are handed off to the rest of our pipeline.
fn validator(
    compiler: Compiler,
    compiler_config: &CompilerConfig,
) -> Result<Box<dyn ContractCompiler>> {
    match compiler {
        Compiler::Solc => Ok(Box::new(SolcCompiler::new_validator(compiler_config))),
        Compiler::Solang => todo!(),
    }
}

/// Validates a source file.
pub fn validate_file(
    compiler: Compiler,
    compiler_config: &CompilerConfig,
    file: &Path,
) -> Result<()> {
    validator(compiler, compiler_config)?.compile_file(file)?;
    Ok(())
}

fn to_http_scheme(scheme: &str) -> &str {
    match scheme {
        "ws" => "http",
        "wss" => "https",
        s => s,
    }
}

fn to_ws_scheme(scheme: &str) -> &str {
    match scheme {
        "http" => "ws",
        "httpss" => "wss",
        s => s,
    }
}