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
#![allow(clippy::field_reassign_with_default)] // This is triggered in `#[derive(JsonSchema)]`

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use cosmwasm_std::{to_binary, Binary, CosmosMsg, Addr, StdResult, Uint128, WasmMsg};

use crate::{state::RESPONSE_BLOCK_SIZE, msg::space_pad};

/// Snip1155ReceiveMsg should be de/serialized under `Snip1155Receive()` variant in a HandleMsg
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub struct Snip1155ReceiveMsg {
    /// the address that sent the `Send` or `BatchSend` message
    pub sender: Addr,
    /// unique token_id `String`
    pub token_id: String,
    /// the previous owner of the tokens being transferred
    pub from: Addr,
    /// amount of tokens being transferred
    pub amount: Uint128,
    /// optional memo
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    /// optional message
    pub msg: Option<Binary>,
}

impl Snip1155ReceiveMsg {
    pub fn new(
        sender: Addr,
        token_id: String,
        from: Addr,
        amount: Uint128,
        memo: Option<String>,
        msg: Option<Binary>,
    ) -> Self {
        Self {
            sender,
            token_id,
            from,
            amount,
            memo,
            msg,
        }
    }

    /// serializes the message, and pads it to 256 bytes
    pub fn into_binary(self) -> StdResult<Binary> {
        let msg = ReceiverHandleMsg::Snip1155Receive(self);
        let mut data = to_binary(&msg)?;
        space_pad(RESPONSE_BLOCK_SIZE, &mut data.0);
        Ok(data)
    }

    /// creates a cosmos_msg sending this struct to the named contract
    pub fn into_cosmos_msg(
        self,
        code_hash: String,
        contract_addr: Addr,
    ) -> StdResult<CosmosMsg> {
        let msg = self.into_binary()?;
        let execute = WasmMsg::Execute {
            msg,
            code_hash,
            contract_addr: contract_addr.to_string(),
            funds: vec![],
        };
        Ok(execute.into())
    }
}

// This is just a helper to properly serialize the above message
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum ReceiverHandleMsg {
    Snip1155Receive(Snip1155ReceiveMsg),
}