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
use abstract_std::ibc::{IbcResponseMsg, ModuleIbcMsg};
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, Storage};
use cw2::{ContractVersion, CONTRACT};
use cw_storage_plus::Item;

use super::handler::Handler;
use crate::{std::objects::dependency::StaticDependency, AbstractSdkError, AbstractSdkResult};

pub type ModuleId = &'static str;
/// Version of the contract in str format.
pub type VersionString = &'static str;
pub type ModuleMetadata = Option<&'static str>;

// ANCHOR: init
/// Function signature for an instantiate handler.
pub type InstantiateHandlerFn<Module, CustomInitMsg, Error> =
    fn(DepsMut, Env, MessageInfo, Module, CustomInitMsg) -> Result<Response, Error>;
// ANCHOR_END: init

// ANCHOR: exec
/// Function signature for an execute handler.
pub type ExecuteHandlerFn<Module, CustomExecMsg, Error> =
    fn(DepsMut, Env, MessageInfo, Module, CustomExecMsg) -> Result<Response, Error>;
// ANCHOR_END: exec

// ANCHOR: query
/// Function signature for a query handler.
pub type QueryHandlerFn<Module, CustomQueryMsg, Error> =
    fn(Deps, Env, &Module, CustomQueryMsg) -> Result<Binary, Error>;
// ANCHOR_END: query

// ANCHOR: ibc
/// Function signature for an IBC callback handler.
pub type IbcCallbackHandlerFn<Module, Error> =
    fn(DepsMut, Env, MessageInfo, Module, IbcResponseMsg) -> Result<Response, Error>;
// ANCHOR_END: ibc

// ANCHOR: module_ibc
/// Function signature for an Module to Module IBC handler.
pub type ModuleIbcHandlerFn<Module, Error> =
    fn(DepsMut, Env, Module, ModuleIbcMsg) -> Result<Response, Error>;
// ANCHOR_END: module_ibc

// ANCHOR: mig
/// Function signature for a migrate handler.
pub type MigrateHandlerFn<Module, CustomMigrateMsg, Error> =
    fn(DepsMut, Env, Module, CustomMigrateMsg) -> Result<Response, Error>;
// ANCHOR_END: mig

// ANCHOR: rec
/// Function signature for a receive handler.
pub type ReceiveHandlerFn<Module, ReceiveMsg, Error> =
    fn(DepsMut, Env, MessageInfo, Module, ReceiveMsg) -> Result<Response, Error>;
// ANCHOR_END: rec

// ANCHOR: sudo
/// Function signature for a sudo handler.
pub type SudoHandlerFn<Module, CustomSudoMsg, Error> =
    fn(DepsMut, Env, Module, CustomSudoMsg) -> Result<Response, Error>;
// ANCHOR_END: sudo

// ANCHOR: reply
/// Function signature for a reply handler.
pub type ReplyHandlerFn<Module, Error> = fn(DepsMut, Env, Module, Reply) -> Result<Response, Error>;
// ANCHOR_END: reply

/// There can be two locations where reply handlers are added.
/// 1. Base implementation of the contract.
/// 2. Custom implementation of the contract.
const MAX_REPLY_COUNT: usize = 2;

/// Abstract generic contract
pub struct AbstractContract<Module: Handler + 'static, Error: From<AbstractSdkError> + 'static> {
    /// Static info about the contract, used for migration
    pub(crate) info: (ModuleId, VersionString, ModuleMetadata),
    /// On-chain storage of the same info.
    pub(crate) version: Item<'static, ContractVersion>,
    /// Modules that this contract depends on.
    pub(crate) dependencies: &'static [StaticDependency],
    /// Handler of instantiate messages.
    pub(crate) instantiate_handler:
        Option<InstantiateHandlerFn<Module, <Module as Handler>::CustomInitMsg, Error>>,
    /// Handler of execute messages.
    pub(crate) execute_handler:
        Option<ExecuteHandlerFn<Module, <Module as Handler>::CustomExecMsg, Error>>,
    /// Handler of query messages.
    pub(crate) query_handler:
        Option<QueryHandlerFn<Module, <Module as Handler>::CustomQueryMsg, Error>>,
    /// Handler for migrations.
    pub(crate) migrate_handler:
        Option<MigrateHandlerFn<Module, <Module as Handler>::CustomMigrateMsg, Error>>,
    /// Handler for sudo messages.
    pub(crate) sudo_handler: Option<SudoHandlerFn<Module, <Module as Handler>::SudoMsg, Error>>,
    /// List of reply handlers per reply ID.
    pub reply_handlers: [&'static [(u64, ReplyHandlerFn<Module, Error>)]; MAX_REPLY_COUNT],
    /// Handler of `Receive variant Execute messages.
    pub(crate) receive_handler:
        Option<ReceiveHandlerFn<Module, <Module as Handler>::ReceiveMsg, Error>>,
    /// IBC callbacks handlers following an IBC action, per callback ID.
    pub(crate) ibc_callback_handlers:
        &'static [(&'static str, IbcCallbackHandlerFn<Module, Error>)],
    /// Module IBC handler for passing messages between a module on different chains.
    pub(crate) module_ibc_handler: Option<ModuleIbcHandlerFn<Module, Error>>,
}

impl<Module, Error: From<AbstractSdkError>> AbstractContract<Module, Error>
where
    Module: Handler,
{
    /// Creates a new customizable abstract contract.
    pub const fn new(name: ModuleId, version: VersionString, metadata: ModuleMetadata) -> Self {
        Self {
            info: (name, version, metadata),
            version: CONTRACT,
            ibc_callback_handlers: &[],
            reply_handlers: [&[], &[]],
            dependencies: &[],
            execute_handler: None,
            receive_handler: None,
            migrate_handler: None,
            sudo_handler: None,
            instantiate_handler: None,
            query_handler: None,
            module_ibc_handler: None,
        }
    }
    /// Gets the cw2 version of the contract.
    pub fn version(&self, store: &dyn Storage) -> AbstractSdkResult<ContractVersion> {
        self.version.load(store).map_err(Into::into)
    }
    /// Gets the static info of the contract.
    pub fn info(&self) -> (ModuleId, VersionString, ModuleMetadata) {
        self.info
    }
    /// add dependencies to the contract
    pub const fn with_dependencies(mut self, dependencies: &'static [StaticDependency]) -> Self {
        self.dependencies = dependencies;
        self
    }
    /// Add reply handlers to the contract.
    pub const fn with_replies(
        mut self,
        reply_handlers: [&'static [(u64, ReplyHandlerFn<Module, Error>)]; MAX_REPLY_COUNT],
    ) -> Self {
        self.reply_handlers = reply_handlers;
        self
    }

    /// add IBC callback handler to contract
    pub const fn with_ibc_callbacks(
        mut self,
        callbacks: &'static [(&'static str, IbcCallbackHandlerFn<Module, Error>)],
    ) -> Self {
        self.ibc_callback_handlers = callbacks;
        self
    }

    /// add IBC callback handler to contract
    pub const fn with_module_ibc(
        mut self,
        module_handler: ModuleIbcHandlerFn<Module, Error>,
    ) -> Self {
        self.module_ibc_handler = Some(module_handler);
        self
    }

    /// Add instantiate handler to the contract.
    pub const fn with_instantiate(
        mut self,
        instantiate_handler: InstantiateHandlerFn<
            Module,
            <Module as Handler>::CustomInitMsg,
            Error,
        >,
    ) -> Self {
        self.instantiate_handler = Some(instantiate_handler);
        self
    }

    /// Add query handler to the contract.
    pub const fn with_migrate(
        mut self,
        migrate_handler: MigrateHandlerFn<Module, <Module as Handler>::CustomMigrateMsg, Error>,
    ) -> Self {
        self.migrate_handler = Some(migrate_handler);
        self
    }

    /// Add sudo handler to the contract.
    pub const fn with_sudo(
        mut self,
        sudo_handler: SudoHandlerFn<Module, <Module as Handler>::SudoMsg, Error>,
    ) -> Self {
        self.sudo_handler = Some(sudo_handler);
        self
    }

    /// Add receive handler to the contract.
    pub const fn with_receive(
        mut self,
        receive_handler: ReceiveHandlerFn<Module, <Module as Handler>::ReceiveMsg, Error>,
    ) -> Self {
        self.receive_handler = Some(receive_handler);
        self
    }

    /// Add execute handler to the contract.
    pub const fn with_execute(
        mut self,
        execute_handler: ExecuteHandlerFn<Module, <Module as Handler>::CustomExecMsg, Error>,
    ) -> Self {
        self.execute_handler = Some(execute_handler);
        self
    }

    /// Add query handler to the contract.
    pub const fn with_query(
        mut self,
        query_handler: QueryHandlerFn<Module, <Module as Handler>::CustomQueryMsg, Error>,
    ) -> Self {
        self.query_handler = Some(query_handler);
        self
    }
}

#[cfg(test)]
mod test {
    use cosmwasm_std::Empty;
    use speculoos::assert_that;

    use super::*;

    #[cosmwasm_schema::cw_serde]
    struct MockInitMsg;

    #[cosmwasm_schema::cw_serde]
    struct MockExecMsg;

    #[cosmwasm_schema::cw_serde]
    struct MockQueryMsg;

    #[cosmwasm_schema::cw_serde]
    struct MockMigrateMsg;

    #[cosmwasm_schema::cw_serde]
    struct MockReceiveMsg;

    #[cosmwasm_schema::cw_serde]
    struct MockSudoMsg;

    use thiserror::Error;

    #[derive(Error, Debug, PartialEq)]
    pub enum MockError {
        #[error("{0}")]
        Sdk(#[from] AbstractSdkError),
    }

    struct MockModule;

    type MockAppContract = AbstractContract<MockModule, MockError>;

    impl Handler for MockModule {
        type Error = MockError;
        type CustomInitMsg = MockInitMsg;
        type CustomExecMsg = MockExecMsg;
        type CustomQueryMsg = MockQueryMsg;
        type CustomMigrateMsg = MockMigrateMsg;
        type ReceiveMsg = MockReceiveMsg;
        type SudoMsg = MockSudoMsg;

        fn contract(&self) -> &AbstractContract<Self, Self::Error> {
            unimplemented!()
        }
    }

    #[test]
    fn test_info() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default());
        let (name, version, metadata) = contract.info();
        assert_that!(&name).is_equal_to("test_contract");
        assert_that!(&version).is_equal_to("0.1.0");
        assert_that!(metadata).is_equal_to(ModuleMetadata::default());
    }

    #[test]
    fn test_with_empty() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_dependencies(&[]);

        assert!(contract.reply_handlers.iter().all(|x| x.is_empty()));

        assert!(contract.dependencies.is_empty());
        assert!(contract.ibc_callback_handlers.is_empty());
        assert!(contract.instantiate_handler.is_none());
        assert!(contract.receive_handler.is_none());
        assert!(contract.execute_handler.is_none());
        assert!(contract.query_handler.is_none());
        assert!(contract.migrate_handler.is_none());
    }

    #[test]
    fn test_with_dependencies() {
        const VERSION: &str = "0.1.0";
        const DEPENDENCY: StaticDependency = StaticDependency::new("test", &[VERSION]);
        const DEPENDENCIES: &[StaticDependency] = &[DEPENDENCY];

        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_dependencies(DEPENDENCIES);

        assert_that!(contract.dependencies[0].clone()).is_equal_to(DEPENDENCY);
    }

    #[test]
    fn test_with_instantiate() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_instantiate(|_, _, _, _, _| {
                Ok(Response::default().add_attribute("test", "instantiate"))
            });

        assert!(contract.instantiate_handler.is_some());
    }

    #[test]
    fn test_with_receive() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_receive(|_, _, _, _, _| Ok(Response::default().add_attribute("test", "receive")));

        assert!(contract.receive_handler.is_some());
    }

    #[test]
    fn test_with_sudo() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_sudo(|_, _, _, _| Ok(Response::default().add_attribute("test", "sudo")));

        assert!(contract.sudo_handler.is_some());
    }

    #[test]
    fn test_with_execute() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_execute(|_, _, _, _, _| Ok(Response::default().add_attribute("test", "execute")));

        assert!(contract.execute_handler.is_some());
    }

    #[test]
    fn test_with_query() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_query(|_, _, _, _| Ok(cosmwasm_std::to_json_binary(&Empty {}).unwrap()));

        assert!(contract.query_handler.is_some());
    }

    #[test]
    fn test_with_migrate() {
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_migrate(|_, _, _, _| Ok(Response::default().add_attribute("test", "migrate")));

        assert!(contract.migrate_handler.is_some());
    }

    #[test]
    fn test_with_reply_handlers() {
        const REPLY_ID: u64 = 50u64;
        const HANDLER: ReplyHandlerFn<MockModule, MockError> =
            |_, _, _, _| Ok(Response::default().add_attribute("test", "reply"));
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_replies([&[(REPLY_ID, HANDLER)], &[]]);

        assert_that!(contract.reply_handlers[0][0].0).is_equal_to(REPLY_ID);
        assert!(contract.reply_handlers[1].is_empty());
    }

    #[test]
    fn test_with_ibc_callback_handlers() {
        const IBC_ID: &str = "aoeu";
        const HANDLER: IbcCallbackHandlerFn<MockModule, MockError> =
            |_, _, _, _, _| Ok(Response::default().add_attribute("test", "ibc"));
        let contract = MockAppContract::new("test_contract", "0.1.0", ModuleMetadata::default())
            .with_ibc_callbacks(&[(IBC_ID, HANDLER)]);

        assert_that!(contract.ibc_callback_handlers[0].0).is_equal_to(IBC_ID);
    }
}