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
use crate::{
    gateway::GatewayABIConfig, light_client::LightClientHeartbeat, ChainId, ExecutionVendor,
    GatewayActivity, GatewayGenesisConfig, GatewayType, GatewayVendor, SpeedMode, TokenInfo,
};
use codec::{Decode, Encode};
use frame_support::dispatch::{DispatchResult, DispatchResultWithPostInfo};
use frame_system::pallet_prelude::{BlockNumberFor, OriginFor};
use scale_info::TypeInfo;
use sp_core::{H160, H256};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
use t3rn_abi::sfx_abi::SFXAbi;
use t3rn_types::sfx::{SecurityLvl, Sfx4bId};

use crate::circuit::AdaptiveTimeout;
use circuit_runtime_types::AssetId;
use t3rn_types::fsx::TargetId;

/// A hash based on encoding the complete XdnsRecord
pub type XdnsRecordId = [u8; 4];

/// A hash based on encoding the Gateway ID
pub type XdnsGatewayId<T> = <T as frame_system::Config>::Hash;

pub trait PalletAssetsOverlay<T: frame_system::Config, Balance> {
    fn contains_asset(asset_id: &AssetId) -> bool;

    fn force_create_asset(
        origin: OriginFor<T>,
        asset_id: AssetId,
        admin: <T as frame_system::Config>::AccountId,
        is_sufficient: bool,
        min_balance: Balance,
    ) -> DispatchResult;

    fn mint(
        origin: OriginFor<T>,
        asset_id: AssetId,
        user: <T as frame_system::Config>::AccountId,
        amount: Balance,
    ) -> DispatchResult;

    fn burn(
        origin: OriginFor<T>,
        asset_id: AssetId,
        user: <T as frame_system::Config>::AccountId,
        amount: Balance,
    ) -> DispatchResult;

    fn destroy(origin: OriginFor<T>, asset_id: &AssetId) -> DispatchResultWithPostInfo;
}

#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct Parachain {
    // gateway_id of relaychain
    pub relay_chain_id: ChainId,
    // parachain_id
    pub id: AssetId,
}

#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct EpochEstimate<BlockNumber> {
    pub local: BlockNumber,

    pub remote: BlockNumber,

    pub moving_average_local: BlockNumber,

    pub moving_average_remote: BlockNumber,
}

/// A preliminary representation of a xdns_record in the onchain registry.
#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct TokenRecord {
    /// Its token AssetId, assume u32
    pub token_id: AssetId,

    /// Link to the gateway token is whitelisted on.
    pub gateway_id: [u8; 4],

    /// Token properties - decimals, symbol, name
    pub token_props: TokenInfo,
}

/// A preliminary representation of a xdns_record in the onchain registry.
#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct GatewayRecord<AccountId> {
    /// Gateway 4b Id
    pub gateway_id: ChainId,

    /// Verification Vendor / Light Client or internal (XCM/XBI)
    pub verification_vendor: GatewayVendor,

    /// Type of execution layer, e.g. EVM for polygon and ethereum
    pub execution_vendor: ExecutionVendor,

    /// Default encoding for the gateway
    pub codec: t3rn_abi::Codec,

    /// Optional owner
    pub registrant: Option<AccountId>,

    /// Leave empty if there's no escrow capabilities on the remote gateway
    pub escrow_account: Option<AccountId>,

    /// Methods enabled to be called on the remote target: (Sfx4bId, Option<PalletIndexMemo>)
    pub allowed_side_effects: Vec<(Sfx4bId, Option<u8>)>,
}

#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct FullGatewayRecord<AccountId> {
    pub gateway_record: GatewayRecord<AccountId>,
    pub tokens: Vec<TokenRecord>,
}

/// A preliminary representation of a xdns_record in the onchain registry.
#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct XdnsRecord<AccountId> {
    /// SCALE-encoded url string on where given Consensus System can be accessed
    pub url: Vec<u8>,

    pub gateway_abi: GatewayABIConfig,

    pub gateway_genesis: GatewayGenesisConfig,

    /// Gateway Vendor
    pub gateway_vendor: GatewayVendor,

    /// Gateway Type
    pub gateway_type: GatewayType,

    /// Gateway Id
    pub gateway_id: ChainId,

    pub parachain: Option<Parachain>,

    /// Gateway System Properties
    pub gateway_sys_props: TokenInfo,

    pub registrant: Option<AccountId>,

    /// Leave empty if there's no escrow capabilities on the remote gateway
    pub security_coordinates: Vec<u8>,

    pub last_finalized: Option<u64>,

    /// Methods enabled to be called on the remote target
    pub allowed_side_effects: Vec<Sfx4bId>,
}

impl<AccountId: Encode> XdnsRecord<AccountId> {
    pub fn new_from_primitives(
        url: Vec<u8>,
        gateway_abi: GatewayABIConfig,
        modules_encoded: Option<Vec<u8>>,
        extrinsics_version: u8,
        genesis_hash: Vec<u8>,
        gateway_id: ChainId,
        parachain: Option<Parachain>,
        gateway_vendor: GatewayVendor,
        gateway_type: GatewayType,
        gateway_sys_props: TokenInfo,
        registrant: Option<AccountId>,
        security_coordinates: Vec<u8>,
        last_finalized: Option<u64>,
        allowed_side_effects: Vec<Sfx4bId>,
    ) -> Self {
        let gateway_genesis = GatewayGenesisConfig {
            modules_encoded,
            extrinsics_version,
            genesis_hash,
        };

        XdnsRecord {
            url,
            gateway_abi,
            gateway_genesis,
            gateway_vendor,
            gateway_type,
            gateway_id,
            parachain,
            gateway_sys_props,
            registrant,
            security_coordinates,
            last_finalized,
            allowed_side_effects,
        }
    }

    pub fn new(
        url: Vec<u8>,
        gateway_id: ChainId,
        parachain: Option<Parachain>,
        gateway_abi: GatewayABIConfig,
        gateway_vendor: GatewayVendor,
        gateway_type: GatewayType,
        gateway_genesis: GatewayGenesisConfig,
        gateway_sys_props: TokenInfo,
        security_coordinates: Vec<u8>,
        allowed_side_effects: Vec<Sfx4bId>,
    ) -> Self {
        XdnsRecord {
            url,
            gateway_id,
            parachain,
            gateway_abi,
            gateway_vendor,
            gateway_type,
            gateway_genesis,
            gateway_sys_props,
            registrant: None,
            security_coordinates,
            last_finalized: None,
            allowed_side_effects,
        }
    }

    pub fn assign_registrant(&mut self, registrant: AccountId) {
        self.registrant = Some(registrant)
    }

    /// Function that generates an XdnsRecordId hash based on the gateway id
    pub fn generate_id<T: frame_system::Config>(&self) -> XdnsRecordId {
        self.gateway_id
    }

    pub fn set_last_finalized(&mut self, last_finalized: u64) {
        self.last_finalized = Some(last_finalized)
    }
}

pub trait Xdns<T: frame_system::Config, Balance> {
    fn fetch_gateways() -> Vec<GatewayRecord<T::AccountId>>;

    fn get_slowest_verifier_target(
        all_targets: Vec<TargetId>,
        speed_mode: &SpeedMode,
        emergency_offset: BlockNumberFor<T>,
    ) -> Option<(
        GatewayVendor,
        TargetId,
        BlockNumberFor<T>,
        BlockNumberFor<T>,
    )>;

    fn estimate_adaptive_timeout_on_slowest_target(
        target_ids: Vec<ChainId>,
        speed_mode: &SpeedMode,
        emergency_offset: BlockNumberFor<T>,
    ) -> AdaptiveTimeout<BlockNumberFor<T>, TargetId>;

    fn register_new_token(
        origin: &T::RuntimeOrigin,
        token_id: AssetId,
        token_props: TokenInfo,
    ) -> DispatchResult;

    fn link_token_to_gateway(
        token_id: AssetId,
        gateway_id: [u8; 4],
        token_props: TokenInfo,
    ) -> DispatchResult;

    fn override_token(
        token_id: AssetId,
        gateway_id: [u8; 4],
        token_props: TokenInfo,
    ) -> DispatchResult;

    fn list_available_mint_assets(gateway_id: TargetId) -> Vec<TokenRecord>;
    fn check_asset_is_mintable(gateway_id: TargetId, asset_id: AssetId) -> bool;
    fn mint(asset_id: AssetId, user: T::AccountId, amount: Balance) -> DispatchResult;
    fn burn(asset_id: AssetId, user: T::AccountId, amount: Balance) -> DispatchResult;
    fn is_target_active(gateway_id: TargetId, security_lvl: &SecurityLvl) -> bool;
    fn get_remote_order_contract_address(gateway_id: TargetId) -> Result<H256, DispatchError>;
    fn get_remote_bidding_contract_address(gateway_id: TargetId) -> Result<H256, DispatchError>;
    fn get_token_by_eth_address(
        gateway_id: TargetId,
        eth_address: H160,
    ) -> Result<TokenRecord, DispatchError>;

    fn get_self_token_id() -> AssetId;

    fn add_new_gateway(
        gateway_id: [u8; 4],
        verification_vendor: GatewayVendor,
        execution_vendor: ExecutionVendor,
        codec: t3rn_abi::Codec,
        registrant: Option<T::AccountId>,
        escrow_account: Option<T::AccountId>,
        allowed_side_effects: Vec<([u8; 4], Option<u8>)>,
    ) -> DispatchResult;

    fn override_gateway(
        gateway_id: [u8; 4],
        verification_vendor: GatewayVendor,
        execution_vendor: ExecutionVendor,
        codec: t3rn_abi::Codec,
        registrant: Option<T::AccountId>,
        escrow_account: Option<T::AccountId>,
        allowed_side_effects: Vec<([u8; 4], Option<u8>)>,
    ) -> DispatchResult;

    fn extend_sfx_abi(
        origin: OriginFor<T>,
        gateway_id: ChainId,
        sfx_4b_id: Sfx4bId,
        sfx_expected_abi: SFXAbi,
    ) -> DispatchResult;

    fn override_sfx_abi(gateway_id: ChainId, new_sfx_abi: Vec<(Sfx4bId, SFXAbi)>)
        -> DispatchResult;

    fn get_all_sfx_abi(gateway_id: &ChainId) -> Vec<(Sfx4bId, SFXAbi)>;

    fn get_sfx_abi(gateway_id: &ChainId, sfx_4b_id: Sfx4bId) -> Option<SFXAbi>;

    fn add_escrow_account(
        origin: OriginFor<T>,
        gateway_id: ChainId,
        escrow_account: T::AccountId,
    ) -> DispatchResult;

    fn allowed_side_effects(gateway_id: &ChainId) -> Vec<([u8; 4], Option<u8>)>;

    fn get_gateway_max_security_lvl(chain_id: &ChainId) -> SecurityLvl;

    fn get_verification_vendor(chain_id: &ChainId) -> Result<GatewayVendor, DispatchError>;

    fn get_target_codec(chain_id: &ChainId) -> Result<t3rn_abi::Codec, DispatchError>;

    fn get_escrow_account(chain_id: &ChainId) -> Result<Vec<u8>, DispatchError>;

    fn fetch_full_gateway_records() -> Vec<FullGatewayRecord<T::AccountId>>;

    fn read_last_activity_overview() -> Vec<GatewayActivity<BlockNumberFor<T>>>;

    fn read_last_activity(gateway_id: ChainId) -> Option<GatewayActivity<BlockNumberFor<T>>>;

    fn verify_active(
        gateway_id: &ChainId,
        max_acceptable_heartbeat_offset: BlockNumberFor<T>,
        security_lvl: &SecurityLvl,
    ) -> Result<LightClientHeartbeat<T>, DispatchError>;
}