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
//! The different back ends for the interface generator. Each supported relay provider has an
//! associated backend. The back ends process interface information and generate interface and
//! configuration files.
use crate::gen::common::Result;
use crate::gen::interface::file::FileInterfaces;
use cubist_config::bridge::{Bridge, ContractBridge};
use cubist_config::util::OrBug;
use cubist_config::{BridgeProvider, ContractName, Target};
use cubist_util::tera::TeraEmbed;
use ethers::types::Address;
use lazy_static::lazy_static;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;
use tera::{Context, Tera};

use super::APPROVE_CALLER_METHOD_NAME;

#[derive(RustEmbed)]
#[folder = "$CARGO_MANIFEST_DIR/templates"]
struct CubeTemplates;
impl TeraEmbed for CubeTemplates {}

lazy_static! {
    /// The codegen templates
    pub static ref TEMPLATES: Tera = CubeTemplates::tera_from_prefix("");
}

/// Metadata associated with an artifact generated by a back end. The metadata that we store
/// depends on the type of artifact.
pub enum ArtifactMetadata {
    /// No additional metadata
    Empty,
    /// The contracts that this artifact contains shims for
    ContractShims {
        /// The name of the artifact
        source_file: PathBuf,
        /// The contract shims in the artifact
        contracts: Vec<ContractName>,
    },
}

/// An artifact generated by a back end (e.g., an interface contract or a configuration file)
pub struct Artifact {
    /// The chain that this artifact is associated with
    target: Target,
    /// The name of this artifact
    name: PathBuf,
    /// The content of this artifact
    content: String,
    /// The type-dependent metadata associated with the generated artifact
    metadata: ArtifactMetadata,
}

impl Artifact {
    /// Returns the target chain for this artifact
    pub fn target(&self) -> Target {
        self.target
    }

    /// Returns the name of this artifact
    pub fn name(&self) -> &PathBuf {
        &self.name
    }

    /// Returns the content of this artifact
    pub fn content(&self) -> &String {
        &self.content
    }

    /// Returns the metadata of this artifact
    pub fn metadata(&self) -> &ArtifactMetadata {
        &self.metadata
    }
}

/// A back end that processes interface information and returns a list of artifacts
pub trait Backend {
    /// The name of the back end
    fn name(&self) -> &'static str;
    /// Names of NPM packages that the generated implementation requires.
    fn npm_dependencies(&self) -> Vec<String>;
    /// Processes a single interface file
    fn process(&self, file: &FileInterfaces) -> Result<Vec<Artifact>>;
}

impl dyn Backend {
    /// Factory method for creating a backend from a [`BridgeProvider`].
    pub fn create(provider: &BridgeProvider) -> Box<Self> {
        match provider {
            BridgeProvider::Cubist => Box::new(CubistBackend),
            BridgeProvider::Axelar => Box::new(AxelarBackend),
        }
    }
}

impl From<&BridgeProvider> for Box<dyn Backend> {
    fn from(provider: &BridgeProvider) -> Self {
        <dyn Backend>::create(provider)
    }
}

/// The back end for the Cubist relayer
pub struct CubistBackend;

impl Backend for CubistBackend {
    fn name(&self) -> &'static str {
        "cubist"
    }

    fn npm_dependencies(&self) -> Vec<String> {
        vec![]
    }

    fn process(&self, file: &FileInterfaces) -> Result<Vec<Artifact>> {
        let file_name = file.get_source_file();
        let mut result = vec![];

        // Generate the bridge configuration file
        let contracts: Vec<ContractBridge> = file
            .interfaces
            .iter()
            .map(|contract| {
                let functions = contract
                    .get_functions()
                    .iter()
                    .map(|function| {
                        (
                            function.name().clone(),
                            format!(
                                "__cubist_event_{}_{}",
                                contract.get_contract_name(),
                                function.name()
                            ),
                        )
                    })
                    .collect::<BTreeMap<_, _>>();
                ContractBridge::new(contract.get_contract_name().clone(), functions)
            })
            .collect();
        let bridge = Bridge::new(
            file.get_source_file().clone(),
            file.get_sender_target(),
            file.get_receiver_target(),
            contracts,
        );
        result.push(Artifact {
            target: file.get_sender_target(),
            name: file_name.with_extension("bridge.json"),
            content: serde_json::to_string_pretty(&bridge).or_bug("Serializing bridge file"),
            metadata: ArtifactMetadata::Empty,
        });

        // Generate the interface file
        let mut context = Context::new();
        let contract_shims: Vec<String> = file
            .interfaces
            .iter()
            .map(|contract| contract.get_contract_name().clone())
            .collect();
        context.insert("file", file);
        context.insert("APPROVE_CALLER_METHOD_NAME", APPROVE_CALLER_METHOD_NAME);
        result.push(Artifact {
            target: file.get_sender_target(),
            name: file_name.clone(),
            content: TEMPLATES
                .render("cubist_sender.tpl", &context)
                .or_bug("Rendering 'cubist_sender' template"),
            metadata: ArtifactMetadata::ContractShims {
                source_file: file.get_source_file().clone(),
                contracts: contract_shims,
            },
        });

        Ok(result)
    }
}

/// Per-target manifest file that the Axelar relayer produces
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AxelarManifest {
    /// Chain target
    pub name: Target,
    /// Chain id
    pub chain_id: u32,
    /// Gateway contract address
    pub gateway: Address,
    /// Gas receiver contract address
    pub gas_receiver: Address,
    /// Deployer contract address
    pub const_address_deployer: Address,
}

/// The back end for the Axelar relayer
pub struct AxelarBackend;

const AXELAR_NPM_PACKAGE: &str = "@axelar-network/axelar-gmp-sdk-solidity";

impl Backend for AxelarBackend {
    fn name(&self) -> &'static str {
        "axelar"
    }

    fn npm_dependencies(&self) -> Vec<String> {
        vec![AXELAR_NPM_PACKAGE.to_string()]
    }

    fn process(&self, file: &FileInterfaces) -> Result<Vec<Artifact>> {
        let file_name = file.get_source_file();
        let mut result = vec![];

        let mut context = Context::new();
        context.insert("file", file);
        context.insert("axelar_package", AXELAR_NPM_PACKAGE);

        // Generate the receiver file
        result.push(Artifact {
            target: file.get_receiver_target(),
            name: file_name.with_extension("receiver.sol"),
            content: TEMPLATES
                .render("axelar_receiver.tpl", &context)
                .or_bug("Rendering 'axelar_receiver' template"),
            metadata: ArtifactMetadata::Empty,
        });
        // Generate the sender file
        let contract_shims: Vec<String> = file
            .interfaces
            .iter()
            .map(|contract| contract.get_contract_name().clone())
            .collect();
        result.push(Artifact {
            target: file.get_sender_target(),
            name: file_name.clone(),
            content: TEMPLATES
                .render("axelar_sender.tpl", &context)
                .or_bug("Rendering 'axelar_sender' template"),
            metadata: ArtifactMetadata::ContractShims {
                source_file: file.get_source_file().clone(),
                contracts: contract_shims,
            },
        });
        Ok(result)
    }
}