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
use crate::store::contract_state::{get_contract_state_v1, CONTRACT_TYPE};
use crate::types::error::ContractError;
use crate::util::conversion_utils::convert_denom;
use crate::util::provenance_utils::{
    check_account_has_all_attributes, check_account_has_enough_denom,
};
use crate::util::validation_utils::check_funds_are_empty;
use cosmwasm_std::{DepsMut, Env, MessageInfo, Response};
use provwasm_std::types::cosmos::base::v1beta1::Coin;
use provwasm_std::types::provenance::marker::v1::{
    MsgMintRequest, MsgTransferRequest, MsgWithdrawRequest,
};
use result_extensions::ResultExtensions;

/// Invoked via the contract's execute functionality.  The function will attempt to pull [trade_amount](fund_trading#trade_amount)
/// of the deposit marker's denom from the sender's account with a marker transfer, discern how much
/// of the trading denom to which the submitted amount is equivalent, and then mint and withdraw
/// that equivalent amount into the sender's account.
///
/// # Parameters
/// * `deps` A dependencies object provided by the cosmwasm framework.  Allows access to useful
/// resources like contract internal storage and a querier to retrieve blockchain objects.
/// * `env` An environment object provided by the cosmwasm framework.  Describes the contract's
/// details, as well as blockchain information at the time of the transaction.
/// * `info` A message information object provided by the cosmwasm framework.  Describes the sender
/// of the instantiation message, as well as the funds provided as an amount during the transaction.
/// * `trade_amount` The amount of the deposit marker to pull from the sender's account in exchange
/// for trading denom.
pub fn fund_trading(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    trade_amount: u128,
) -> Result<Response, ContractError> {
    check_funds_are_empty(&info)?;
    let contract_state = get_contract_state_v1(deps.storage)?;
    check_account_has_all_attributes(
        &deps,
        &info.sender,
        &contract_state.required_deposit_attributes,
    )?;
    let conversion = convert_denom(
        trade_amount,
        &contract_state.deposit_marker,
        &contract_state.trading_marker,
    )?;
    if conversion.target_amount == 0 {
        return ContractError::InvalidFundsError {
            message: format!(
                "sent [{}{}], but that is not enough to convert to at least one [{}]",
                trade_amount,
                &contract_state.deposit_marker.name,
                &contract_state.trading_marker.name,
            ),
        }
        .to_err();
    }
    // Transfer the necessary amount from the sender (total amount requested - remainder that cannot be converted)
    let transferred_amount = trade_amount - conversion.remainder;
    check_account_has_enough_denom(
        &deps.as_ref(),
        info.sender.as_str(),
        &contract_state.deposit_marker.name,
        transferred_amount,
    )?;
    let transfer_msg = MsgTransferRequest {
        administrator: env.contract.address.to_string(),
        amount: Some(Coin {
            denom: contract_state.deposit_marker.name.to_owned(),
            amount: transferred_amount.to_string(),
        }),
        from_address: info.sender.to_string(),
        to_address: env.contract.address.to_string(),
    };
    // Mint the amount of coin to which the conversion equates
    let minted_coin = Coin {
        denom: contract_state.trading_marker.name.to_owned(),
        amount: conversion.target_amount.to_string(),
    };
    let mint_msg = MsgMintRequest {
        administrator: env.contract.address.to_string(),
        amount: Some(minted_coin.to_owned()),
    };
    // Withdraw the newly-minted coin to the sender, effectively making the trade
    let withdraw_msg = MsgWithdrawRequest {
        denom: contract_state.trading_marker.name.to_owned(),
        administrator: env.contract.address.to_string(),
        to_address: info.sender.to_string(),
        amount: vec![minted_coin.to_owned()],
    };
    Response::new()
        .add_message(transfer_msg)
        .add_message(mint_msg)
        .add_message(withdraw_msg)
        .add_attribute("action", "fund_trading")
        .add_attribute("contract_address", env.contract.address.to_string())
        .add_attribute("contract_type", CONTRACT_TYPE)
        .add_attribute("contract_name", &contract_state.contract_name)
        .add_attribute("deposit_input_denom", &contract_state.deposit_marker.name)
        .add_attribute("deposit_requested_amount", trade_amount.to_string())
        .add_attribute("deposit_actual_amount", transferred_amount.to_string())
        .add_attribute("received_denom", minted_coin.denom)
        .add_attribute("received_amount", minted_coin.amount)
        .to_ok()
}

#[cfg(test)]
mod tests {
    use crate::execute::fund_trading::fund_trading;
    use crate::store::contract_state::CONTRACT_TYPE;
    use crate::test::attribute_extractor::AttributeExtractor;
    use crate::test::test_constants::{
        DEFAULT_CONTRACT_NAME, DEFAULT_DEPOSIT_DENOM_NAME, DEFAULT_REQUIRED_DEPOSIT_ATTRIBUTE,
        DEFAULT_TRADING_DENOM_NAME,
    };
    use crate::test::test_instantiate::{test_instantiate, test_instantiate_with_msg};
    use crate::types::denom::Denom;
    use crate::types::error::ContractError;
    use crate::types::msg::InstantiateMsg;
    use cosmwasm_std::testing::{message_info, mock_env, MOCK_CONTRACT_ADDR};
    use cosmwasm_std::{coins, Addr, AnyMsg, CosmosMsg};
    use provwasm_mocks::{
        mock_provenance_dependencies, mock_provenance_dependencies_with_custom_querier,
        MockProvenanceQuerier,
    };
    use provwasm_std::types::cosmos::bank::v1beta1::{QueryBalanceRequest, QueryBalanceResponse};
    use provwasm_std::types::cosmos::base::v1beta1::Coin;
    use provwasm_std::types::provenance::attribute::v1::{
        Attribute, AttributeType, QueryAttributesRequest, QueryAttributesResponse,
    };
    use provwasm_std::types::provenance::marker::v1::{
        MsgMintRequest, MsgTransferRequest, MsgWithdrawRequest,
    };

    #[test]
    fn provided_funds_should_cause_an_error() {
        let mut deps = mock_provenance_dependencies();
        let error = fund_trading(
            deps.as_mut(),
            mock_env(),
            message_info(&Addr::unchecked("some-sender"), &coins(10, "nhash")),
            10,
        )
        .expect_err("an error should be emitted when coin is provided");
        assert!(
            matches!(error, ContractError::InvalidFundsError { .. },),
            "unexpected error type encountered when providing funds",
        );
    }

    #[test]
    fn missing_contract_state_should_cause_an_error() {
        let mut deps = mock_provenance_dependencies();
        let error = fund_trading(
            deps.as_mut(),
            mock_env(),
            message_info(&Addr::unchecked("some-sender"), &[]),
            10,
        )
        .expect_err("an error should be emitted when no contract state exists");
        assert!(
            matches!(error, ContractError::StorageError { .. },),
            "unexpected error type encountered when no contract storage exists",
        );
    }

    #[test]
    fn sender_missing_required_amount_should_cause_an_error() {
        let mut querier = MockProvenanceQuerier::new(&[]);
        QueryBalanceRequest::mock_response(
            &mut querier,
            QueryBalanceResponse {
                balance: Some(Coin {
                    amount: "9".to_string(),
                    denom: DEFAULT_DEPOSIT_DENOM_NAME.to_string(),
                }),
            },
        );
        QueryAttributesRequest::mock_response(
            &mut querier,
            QueryAttributesResponse {
                account: "sender".to_string(),
                attributes: vec![Attribute {
                    name: DEFAULT_REQUIRED_DEPOSIT_ATTRIBUTE.to_string(),
                    value: vec![],
                    attribute_type: AttributeType::String as i32,
                    address: "addr".to_string(),
                    expiration_date: None,
                }],
                pagination: None,
            },
        );
        let mut deps = mock_provenance_dependencies_with_custom_querier(querier);
        test_instantiate(deps.as_mut());
        let error = fund_trading(deps.as_mut(), mock_env(), message_info(&Addr::unchecked("some-sender"), &[]), 10)
            .expect_err("an error should occur when the sender tries to trade more funds than are available to them");
        assert!(
            matches!(error, ContractError::InvalidAccountError { .. }),
            "unexpected error type encountered when the sender tries to trade too much: {error:?}",
        );
    }

    #[test]
    fn sender_missing_required_attribute_should_cause_an_error() {
        let mut querier = MockProvenanceQuerier::new(&[]);
        QueryBalanceRequest::mock_response(
            &mut querier,
            QueryBalanceResponse {
                balance: Some(Coin {
                    amount: "10".to_string(),
                    denom: DEFAULT_DEPOSIT_DENOM_NAME.to_string(),
                }),
            },
        );
        QueryAttributesRequest::mock_response(
            &mut querier,
            QueryAttributesResponse {
                account: "some-sender".to_string(),
                attributes: vec![],
                pagination: None,
            },
        );
        let mut deps = mock_provenance_dependencies_with_custom_querier(querier);
        test_instantiate(deps.as_mut());
        let error = fund_trading(
            deps.as_mut(),
            mock_env(),
            message_info(&Addr::unchecked("some-sender"), &[]),
            10,
        )
        .expect_err("an error should occur when the sender does not have a required attribute");
        assert!(
            matches!(error, ContractError::InvalidAccountError { .. },),
            "unexpected error when account is missing required attributes",
        );
    }

    #[test]
    fn conversion_producing_no_output_denom_should_cause_an_error() {
        let mut querier = MockProvenanceQuerier::new(&[]);
        QueryBalanceRequest::mock_response(
            &mut querier,
            QueryBalanceResponse {
                balance: Some(Coin {
                    amount: "10".to_string(),
                    denom: DEFAULT_DEPOSIT_DENOM_NAME.to_string(),
                }),
            },
        );
        QueryAttributesRequest::mock_response(
            &mut querier,
            QueryAttributesResponse {
                account: "sender".to_string(),
                attributes: vec![Attribute {
                    name: DEFAULT_REQUIRED_DEPOSIT_ATTRIBUTE.to_string(),
                    value: vec![],
                    attribute_type: AttributeType::String as i32,
                    address: "addr".to_string(),
                    expiration_date: None,
                }],
                pagination: None,
            },
        );
        let mut deps = mock_provenance_dependencies_with_custom_querier(querier);
        // Setup trading marker to have a smaller precision than deposit, which will cause a single
        // digit conversion to fail
        test_instantiate_with_msg(
            deps.as_mut(),
            InstantiateMsg {
                deposit_marker: Denom::new("denom1", 2),
                trading_marker: Denom::new("denom2", 1),
                ..InstantiateMsg::default()
            },
        );
        let error = fund_trading(
            deps.as_mut(),
            mock_env(),
            message_info(&Addr::unchecked("sender"), &[]),
            9,
        )
        .expect_err("a conversion that does not produce any trading denom should fail");
        let _expected_err =
            "sent [9denom1], but that is not enough to convert to at least one [denom2]"
                .to_string();
        assert!(
            matches!(
                error,
                ContractError::InvalidFundsError {
                    message: _expected_err,
                },
            ),
            "unexpected error occurred when invalid conversion occurs",
        );
    }

    #[test]
    fn successful_parameters_should_produce_a_result() {
        let mut querier = MockProvenanceQuerier::new(&[]);
        QueryBalanceRequest::mock_response(
            &mut querier,
            QueryBalanceResponse {
                balance: Some(Coin {
                    amount: "103".to_string(),
                    denom: DEFAULT_DEPOSIT_DENOM_NAME.to_string(),
                }),
            },
        );
        QueryAttributesRequest::mock_response(
            &mut querier,
            QueryAttributesResponse {
                account: "sender".to_string(),
                attributes: vec![Attribute {
                    name: DEFAULT_REQUIRED_DEPOSIT_ATTRIBUTE.to_string(),
                    value: vec![],
                    attribute_type: AttributeType::String as i32,
                    address: "addr".to_string(),
                    expiration_date: None,
                }],
                pagination: None,
            },
        );
        let mut deps = mock_provenance_dependencies_with_custom_querier(querier);
        // Setup the trading marker to have a smaller precision than the deposit, requiring some
        // remainder to be returned.  Ex:
        // Sender wants to send 103, which equates to 1.03.  However, trading marker has a precision
        // of 1, which will convert to 10 (aka 1.0).  The 3 will be dropped and be a remaining value
        // for the sender
        test_instantiate_with_msg(
            deps.as_mut(),
            InstantiateMsg {
                deposit_marker: Denom::new(DEFAULT_DEPOSIT_DENOM_NAME, 2),
                trading_marker: Denom::new(DEFAULT_TRADING_DENOM_NAME, 1),
                ..InstantiateMsg::default()
            },
        );
        let response = fund_trading(
            deps.as_mut(),
            mock_env(),
            message_info(&Addr::unchecked("sender"), &[]),
            103,
        )
        .expect("proper circumstances should derive a successful result");
        assert_eq!(
            3,
            response.messages.len(),
            "expected the response to include three messages",
        );
        response.messages.iter().for_each(|msg| match &msg.msg {
            CosmosMsg::Any(AnyMsg { type_url, value }) => match type_url.as_str() {
                "/provenance.marker.v1.MsgTransferRequest" => {
                    let req = MsgTransferRequest::try_from(value.to_owned())
                        .expect("the value should properly deserialize to a transfer request");
                    assert_eq!(
                        MOCK_CONTRACT_ADDR,
                        req.administrator,
                        "the contract address should be set as the administrator of the transfer request",
                    );
                    let coin = req.amount.expect("expected the amount to be set on the transfer request");
                    assert_eq!(
                        100.to_string(),
                        coin.amount,
                        "the correct amount of funds should be taken from the sender",
                    );
                    assert_eq!(
                        DEFAULT_DEPOSIT_DENOM_NAME,
                        coin.denom,
                        "the correct denom should be taken from the sender",
                    );
                    assert_eq!(
                        "sender",
                        req.from_address,
                        "the sender should be the from_address",
                    );
                    assert_eq!(
                        MOCK_CONTRACT_ADDR,
                        req.to_address,
                        "the contract should be the to_address",
                    );
                }
                "/provenance.marker.v1.MsgMintRequest" => {
                    let req = MsgMintRequest::try_from(value.to_owned())
                        .expect("the value should properly deserialize to a mint request");
                    assert_eq!(
                        MOCK_CONTRACT_ADDR,
                        req.administrator,
                        "the administrator of the mint msg should be the contract",
                    );
                    let coin = req.amount.expect("expected the amount to be set on the mint request");
                    assert_eq!(
                        10.to_string(),
                        coin.amount,
                        "the amount minted should equate to the amount after the precision conversion",
                    );
                    assert_eq!(
                        DEFAULT_TRADING_DENOM_NAME,
                        coin.denom,
                        "the denom minted should be the trading denom",
                    );
                }
                "/provenance.marker.v1.MsgWithdrawRequest" => {
                    let req = MsgWithdrawRequest::try_from(value.to_owned())
                        .expect("expected the msg to be a withdraw request");
                    assert_eq!(
                        DEFAULT_TRADING_DENOM_NAME,
                        req.denom,
                        "the withdraw request should withdraw from the trading marker",
                    );
                    assert_eq!(
                        MOCK_CONTRACT_ADDR,
                        req.administrator,
                        "the withdraw request should use the contract address as the administrator",
                    );
                    assert_eq!(
                        "sender",
                        req.to_address,
                        "the withdraw request should send the coin to the sender",
                    );
                    assert_eq!(
                        1,
                        req.amount.len(),
                        "the amount field should have a single coin",
                    );
                    let coin = req.amount.first().unwrap();
                    assert_eq!(
                        10.to_string(),
                        coin.amount,
                        "the withdrawn amount should be the upconverted denom",
                    );
                    assert_eq!(
                        DEFAULT_TRADING_DENOM_NAME,
                        coin.denom,
                        "the withdrawn denom should be the trading denom",
                    );
                }
                url => panic!("unexpected type url in emitted msg: {url}"),
            },
            msg => panic!("unexpected message emitted: {msg:?}"),
        });
        assert_eq!(
            9,
            response.attributes.len(),
            "expected nine attributes to be emitted",
        );
        response.assert_attribute("action", "fund_trading");
        response.assert_attribute("contract_address", MOCK_CONTRACT_ADDR);
        response.assert_attribute("contract_type", CONTRACT_TYPE);
        response.assert_attribute("contract_name", DEFAULT_CONTRACT_NAME);
        response.assert_attribute("deposit_input_denom", DEFAULT_DEPOSIT_DENOM_NAME);
        response.assert_attribute("deposit_requested_amount", "103");
        response.assert_attribute("deposit_actual_amount", "100");
        response.assert_attribute("received_denom", DEFAULT_TRADING_DENOM_NAME);
        response.assert_attribute("received_amount", "10");
    }

    #[test]
    fn request_that_does_not_need_full_amount_expected_succeeds() {
        let mut querier = MockProvenanceQuerier::new(&[]);
        QueryBalanceRequest::mock_response(
            &mut querier,
            QueryBalanceResponse {
                balance: Some(Coin {
                    amount: "200".to_string(),
                    denom: DEFAULT_DEPOSIT_DENOM_NAME.to_string(),
                }),
            },
        );
        QueryAttributesRequest::mock_response(
            &mut querier,
            QueryAttributesResponse {
                account: "sender".to_string(),
                attributes: vec![Attribute {
                    name: DEFAULT_REQUIRED_DEPOSIT_ATTRIBUTE.to_string(),
                    value: vec![],
                    attribute_type: AttributeType::String as i32,
                    address: "addr".to_string(),
                    expiration_date: None,
                }],
                pagination: None,
            },
        );
        let mut deps = mock_provenance_dependencies_with_custom_querier(querier);
        // Setup the trading marker to have a smaller precision than the deposit, requiring some
        // remainder to be returned.  Ex:
        // Sender wants to send 250, which equates to 2.50.  They don't actually have 250, but they
        // do have 200, which is allowed.  This should be allowed to proceed.
        test_instantiate_with_msg(
            deps.as_mut(),
            InstantiateMsg {
                deposit_marker: Denom::new(DEFAULT_DEPOSIT_DENOM_NAME, 3),
                trading_marker: Denom::new(DEFAULT_TRADING_DENOM_NAME, 1),
                ..InstantiateMsg::default()
            },
        );
        fund_trading(
            deps.as_mut(),
            mock_env(),
            message_info(&Addr::unchecked("sender"), &[]),
            250,
        )
        .expect("proper circumstances should derive a successful result");
    }
}