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
use dharitri_codec::{
    CodecFrom, EncodeErrorHandler, TopDecode, TopEncode, TopEncodeMulti, TopEncodeMultiOutput,
};

use super::{
    fungible_token_mapper::DEFAULT_ISSUE_CALLBACK_NAME,
    token_mapper::{
        read_token_id, store_token_id, StorageTokenWrapper, TOKEN_ID_ALREADY_SET_ERR_MSG,
    },
    StorageMapper,
};
use crate::{
    abi::{TypeAbi, TypeName},
    api::{CallTypeApi, ErrorApiImpl, StorageMapperApi},
    contract_base::{BlockchainWrapper, SendWrapper},
    dct::{
        DCTSystemSmartContractProxy, MetaTokenProperties, NonFungibleTokenProperties,
        SemiFungibleTokenProperties,
    },
    storage::StorageKey,
    types::{
        BigUint, CallbackClosure, ContractCall, DctTokenData, DctTokenPayment, DctTokenType,
        ManagedAddress, ManagedBuffer, ManagedType, TokenIdentifier,
    },
};

const INVALID_TOKEN_TYPE_ERR_MSG: &[u8] = b"Invalid token type for NonFungible issue";

pub struct NonFungibleTokenMapper<SA>
where
    SA: StorageMapperApi + CallTypeApi,
{
    key: StorageKey<SA>,
    token_id: TokenIdentifier<SA>,
}

impl<SA> StorageMapper<SA> for NonFungibleTokenMapper<SA>
where
    SA: StorageMapperApi + CallTypeApi,
{
    fn new(base_key: StorageKey<SA>) -> Self {
        Self {
            token_id: read_token_id(base_key.as_ref()),
            key: base_key,
        }
    }
}

impl<SA> StorageTokenWrapper<SA> for NonFungibleTokenMapper<SA>
where
    SA: StorageMapperApi + CallTypeApi,
{
    fn get_storage_key(&self) -> crate::types::ManagedRef<SA, StorageKey<SA>> {
        self.key.as_ref()
    }

    fn get_token_id(&self) -> TokenIdentifier<SA> {
        self.token_id.clone()
    }

    fn get_token_id_ref(&self) -> &TokenIdentifier<SA> {
        &self.token_id
    }

    fn set_token_id(&mut self, token_id: TokenIdentifier<SA>) {
        store_token_id(self, &token_id);
        self.token_id = token_id;
    }
}

impl<SA> NonFungibleTokenMapper<SA>
where
    SA: StorageMapperApi + CallTypeApi,
{
    /// Important: If you use custom callback, remember to save the token ID in the callback!
    /// If you want to use default callbacks, import the default_issue_callbacks::DefaultIssueCallbacksModule from dharitri-wasm-modules
    /// and pass None for the opt_callback argument
    pub fn issue(
        &self,
        token_type: DctTokenType,
        issue_cost: BigUint<SA>,
        token_display_name: ManagedBuffer<SA>,
        token_ticker: ManagedBuffer<SA>,
        num_decimals: usize,
        opt_callback: Option<CallbackClosure<SA>>,
    ) -> ! {
        if !self.is_empty() {
            SA::error_api_impl().signal_error(TOKEN_ID_ALREADY_SET_ERR_MSG);
        }

        let callback = match opt_callback {
            Some(cb) => cb,
            None => self.default_callback_closure_obj(),
        };
        let contract_call = match token_type {
            DctTokenType::NonFungible => {
                Self::nft_issue(issue_cost, token_display_name, token_ticker)
            },
            DctTokenType::SemiFungible => {
                Self::sft_issue(issue_cost, token_display_name, token_ticker)
            },
            DctTokenType::Meta => {
                Self::meta_issue(issue_cost, token_display_name, token_ticker, num_decimals)
            },
            _ => SA::error_api_impl().signal_error(INVALID_TOKEN_TYPE_ERR_MSG),
        };

        contract_call
            .async_call()
            .with_callback(callback)
            .call_and_exit();
    }

    /// Important: If you use custom callback, remember to save the token ID in the callback!
    /// If you want to use default callbacks, import the default_issue_callbacks::DefaultIssueCallbacksModule from dharitri-wasm-modules
    /// and pass None for the opt_callback argument
    pub fn issue_and_set_all_roles(
        &self,
        token_type: DctTokenType,
        issue_cost: BigUint<SA>,
        token_display_name: ManagedBuffer<SA>,
        token_ticker: ManagedBuffer<SA>,
        num_decimals: usize,
        opt_callback: Option<CallbackClosure<SA>>,
    ) -> ! {
        if !self.is_empty() {
            SA::error_api_impl().signal_error(TOKEN_ID_ALREADY_SET_ERR_MSG);
        }
        if token_type == DctTokenType::Fungible || token_type == DctTokenType::Invalid {
            SA::error_api_impl().signal_error(INVALID_TOKEN_TYPE_ERR_MSG);
        }

        let system_sc_proxy = DCTSystemSmartContractProxy::<SA>::new_proxy_obj();
        let callback = match opt_callback {
            Some(cb) => cb,
            None => self.default_callback_closure_obj(),
        };

        system_sc_proxy
            .issue_and_set_all_roles(
                issue_cost,
                token_display_name,
                token_ticker,
                token_type,
                num_decimals,
            )
            .async_call()
            .with_callback(callback)
            .call_and_exit();
    }

    fn default_callback_closure_obj(&self) -> CallbackClosure<SA> {
        let initial_caller = BlockchainWrapper::<SA>::new().get_caller();
        let cb_name = DEFAULT_ISSUE_CALLBACK_NAME;

        let mut cb_closure = CallbackClosure::new(cb_name.into());
        cb_closure.push_endpoint_arg(&initial_caller);
        cb_closure.push_endpoint_arg(&self.key.buffer);

        cb_closure
    }

    fn nft_issue(
        issue_cost: BigUint<SA>,
        token_display_name: ManagedBuffer<SA>,
        token_ticker: ManagedBuffer<SA>,
    ) -> ContractCall<SA, ()> {
        let system_sc_proxy = DCTSystemSmartContractProxy::<SA>::new_proxy_obj();
        system_sc_proxy.issue_non_fungible(
            issue_cost,
            &token_display_name,
            &token_ticker,
            NonFungibleTokenProperties::default(),
        )
    }

    fn sft_issue(
        issue_cost: BigUint<SA>,
        token_display_name: ManagedBuffer<SA>,
        token_ticker: ManagedBuffer<SA>,
    ) -> ContractCall<SA, ()> {
        let system_sc_proxy = DCTSystemSmartContractProxy::<SA>::new_proxy_obj();
        system_sc_proxy.issue_semi_fungible(
            issue_cost,
            &token_display_name,
            &token_ticker,
            SemiFungibleTokenProperties::default(),
        )
    }

    fn meta_issue(
        issue_cost: BigUint<SA>,
        token_display_name: ManagedBuffer<SA>,
        token_ticker: ManagedBuffer<SA>,
        num_decimals: usize,
    ) -> ContractCall<SA, ()> {
        let system_sc_proxy = DCTSystemSmartContractProxy::<SA>::new_proxy_obj();
        let properties = MetaTokenProperties {
            num_decimals,
            ..Default::default()
        };

        system_sc_proxy.register_meta_dct(
            issue_cost,
            &token_display_name,
            &token_ticker,
            properties,
        )
    }

    pub fn nft_create<T: TopEncode>(
        &self,
        amount: BigUint<SA>,
        attributes: &T,
    ) -> DctTokenPayment<SA> {
        let send_wrapper = SendWrapper::<SA>::new();
        let token_id = self.get_token_id();

        let token_nonce = send_wrapper.dct_nft_create_compact(&token_id, &amount, attributes);

        DctTokenPayment::new(token_id, token_nonce, amount)
    }

    pub fn nft_create_named<T: TopEncode>(
        &self,
        amount: BigUint<SA>,
        name: &ManagedBuffer<SA>,
        attributes: &T,
    ) -> DctTokenPayment<SA> {
        let send_wrapper = SendWrapper::<SA>::new();
        let token_id = self.get_token_id();

        let token_nonce =
            send_wrapper.dct_nft_create_compact_named(&token_id, &amount, name, attributes);

        DctTokenPayment::new(token_id, token_nonce, amount)
    }

    pub fn nft_create_and_send<T: TopEncode>(
        &self,
        to: &ManagedAddress<SA>,
        amount: BigUint<SA>,
        attributes: &T,
    ) -> DctTokenPayment<SA> {
        let payment = self.nft_create(amount, attributes);
        self.send_payment(to, &payment);

        payment
    }

    pub fn nft_create_and_send_named<T: TopEncode>(
        &self,
        to: &ManagedAddress<SA>,
        amount: BigUint<SA>,
        name: &ManagedBuffer<SA>,
        attributes: &T,
    ) -> DctTokenPayment<SA> {
        let payment = self.nft_create_named(amount, name, attributes);
        self.send_payment(to, &payment);

        payment
    }

    pub fn nft_add_quantity(&self, token_nonce: u64, amount: BigUint<SA>) -> DctTokenPayment<SA> {
        let send_wrapper = SendWrapper::<SA>::new();
        let token_id = self.get_token_id();

        send_wrapper.dct_local_mint(&token_id, token_nonce, &amount);

        DctTokenPayment::new(token_id, token_nonce, amount)
    }

    pub fn nft_add_quantity_and_send(
        &self,
        to: &ManagedAddress<SA>,
        token_nonce: u64,
        amount: BigUint<SA>,
    ) -> DctTokenPayment<SA> {
        let payment = self.nft_add_quantity(token_nonce, amount);
        self.send_payment(to, &payment);

        payment
    }

    pub fn nft_burn(&self, token_nonce: u64, amount: &BigUint<SA>) {
        let send_wrapper = SendWrapper::<SA>::new();
        let token_id = self.get_token_id_ref();

        send_wrapper.dct_local_burn(token_id, token_nonce, amount);
    }

    pub fn get_all_token_data(&self, token_nonce: u64) -> DctTokenData<SA> {
        let b_wrapper = BlockchainWrapper::new();
        let own_sc_address = Self::get_sc_address();
        let token_id = self.get_token_id_ref();

        b_wrapper.get_dct_token_data(&own_sc_address, token_id, token_nonce)
    }

    pub fn get_balance(&self, token_nonce: u64) -> BigUint<SA> {
        let b_wrapper = BlockchainWrapper::new();
        let own_sc_address = Self::get_sc_address();
        let token_id = self.get_token_id_ref();

        b_wrapper.get_dct_balance(&own_sc_address, token_id, token_nonce)
    }

    pub fn get_token_attributes<T: TopDecode>(&self, token_nonce: u64) -> T {
        let token_data = self.get_all_token_data(token_nonce);
        token_data.decode_attributes()
    }

    fn send_payment(&self, to: &ManagedAddress<SA>, payment: &DctTokenPayment<SA>) {
        let send_wrapper = SendWrapper::<SA>::new();
        send_wrapper.direct_dct(
            to,
            &payment.token_identifier,
            payment.token_nonce,
            &payment.amount,
        );
    }
}

impl<SA> TopEncodeMulti for NonFungibleTokenMapper<SA>
where
    SA: StorageMapperApi + CallTypeApi,
{
    fn multi_encode_or_handle_err<O, H>(&self, output: &mut O, h: H) -> Result<(), H::HandledErr>
    where
        O: TopEncodeMultiOutput,
        H: EncodeErrorHandler,
    {
        if self.is_empty() {
            output.push_single_value(&ManagedBuffer::<SA>::new(), h)
        } else {
            output.push_single_value(&self.get_token_id(), h)
        }
    }
}

impl<SA> CodecFrom<NonFungibleTokenMapper<SA>> for TokenIdentifier<SA> where
    SA: StorageMapperApi + CallTypeApi
{
}

impl<SA> TypeAbi for NonFungibleTokenMapper<SA>
where
    SA: StorageMapperApi + CallTypeApi,
{
    fn type_name() -> TypeName {
        TokenIdentifier::<SA>::type_name()
    }

    fn provide_type_descriptions<TDC: crate::abi::TypeDescriptionContainer>(accumulator: &mut TDC) {
        TokenIdentifier::<SA>::provide_type_descriptions(accumulator);
    }

    fn is_variadic() -> bool {
        false
    }
}