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
use std::{
    convert::{TryFrom, TryInto},
    ops::Deref,
};

use crate::{assets::AssetName, AssetNameList, MapAssetNameToNonZeroInt64, PolicyId, PolicyIdList};
use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue};

use cml_core_wasm::{impl_wasm_cbor_json_api, impl_wasm_conversions, impl_wasm_map};

use super::Coin;

impl_wasm_map!(
    cml_chain::assets::AssetName,
    Coin,
    AssetName,
    Coin,
    AssetNameList,
    MapAssetNameToCoin,
    false,
    true,
    false,
    true
);

#[wasm_bindgen]
impl AssetName {
    /**
     * Create an AssetName from raw bytes. 64 byte maximum.
     */
    pub fn from_bytes(bytes: Vec<u8>) -> Result<AssetName, JsError> {
        cml_chain::assets::AssetName::try_from(bytes)
            .map(Into::into)
            .map_err(Into::into)
    }

    /**
     * Create an AssetName from utf8 string. 64 byte (not char!) maximum.
     */
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(utf8_str: &str) -> Result<AssetName, JsError> {
        cml_chain::assets::AssetName::try_from(utf8_str)
            .map(Into::into)
            .map_err(Into::into)
    }

    /**
     * AssetName as a utf8 string if it's possible. Will error if the asset is not utf8
     */
    pub fn to_str(&self) -> Result<String, JsError> {
        self.as_ref()
            .try_into()
            .map(str::to_owned)
            .map_err(Into::into)
    }
}

#[derive(Clone, Debug)]
#[wasm_bindgen]
pub struct MultiAsset(cml_chain::assets::MultiAsset);

#[wasm_bindgen]
impl MultiAsset {
    pub fn new() -> Self {
        Self(cml_chain::assets::MultiAsset::default())
    }

    pub fn policy_count(&self) -> usize {
        self.0.len()
    }

    pub fn insert_assets(
        &mut self,
        policy_id: &PolicyId,
        assets: &MapAssetNameToCoin,
    ) -> Option<MapAssetNameToCoin> {
        self.0
            .insert(policy_id.clone().into(), assets.clone().into())
            .map(Into::into)
    }

    pub fn get_assets(&self, key: &PolicyId) -> Option<MapAssetNameToCoin> {
        self.0.deref().get(key.as_ref()).map(|v| v.clone().into())
    }

    /// Get the value of policy_id:asset_name if it exists.
    pub fn get(&self, policy_id: &PolicyId, asset: &AssetName) -> Option<Coin> {
        self.0.get(policy_id.as_ref(), asset.as_ref())
    }

    /// Set the value of policy_id:asset_name to value.
    /// Returns the previous value, or None if it didn't exist
    pub fn set(&mut self, policy_id: &PolicyId, asset: &AssetName, value: Coin) -> Option<Coin> {
        self.0
            .set(policy_id.clone().into(), asset.clone().into(), value)
    }

    pub fn keys(&self) -> PolicyIdList {
        PolicyIdList(self.0.iter().map(|(k, _v)| *k).collect::<Vec<_>>())
    }

    /// Adds to multiassets together, checking value bounds.
    /// Does not modify self, and instead returns the result.
    pub fn checked_add(&self, rhs: &MultiAsset) -> Result<MultiAsset, JsError> {
        self.0
            .checked_add(rhs.as_ref())
            .map(Into::into)
            .map_err(Into::into)
    }

    /// Subtracts rhs from this multiasset.
    /// This does not modify self, and instead returns the result.
    /// If this would cause there to be fewer than 0 of a given asset
    /// an error will be returned.
    /// Use clamped_sub if you need to only try to remove assets when they exist
    /// and ignore them when they don't.
    pub fn checked_sub(&self, rhs: &MultiAsset) -> Result<MultiAsset, JsError> {
        self.0
            .checked_sub(rhs.as_ref())
            .map(Into::into)
            .map_err(Into::into)
    }

    /// Sybtracts rhs from this multiasset.
    /// If this would cause there to be 0 or fewer of a given asset
    /// it will simply be removed entirely from the result.
    pub fn clamped_sub(&self, rhs: &MultiAsset) -> Self {
        use cml_chain::assets::ClampedSub;
        self.0.clamped_sub(rhs.as_ref()).into()
    }
}

impl_wasm_conversions!(cml_chain::assets::MultiAsset, MultiAsset);

#[derive(Clone, Debug)]
#[wasm_bindgen]
pub struct Mint(cml_chain::assets::Mint);

#[wasm_bindgen]
impl Mint {
    pub fn new() -> Self {
        Self(cml_chain::assets::Mint::default())
    }

    pub fn policy_count(&self) -> usize {
        self.0.len()
    }

    pub fn insert_assets(
        &mut self,
        policy_id: &PolicyId,
        assets: &MapAssetNameToNonZeroInt64,
    ) -> Option<MapAssetNameToNonZeroInt64> {
        self.0
            .insert(policy_id.clone().into(), assets.clone().into())
            .map(Into::into)
    }

    pub fn get_assets(&self, key: &PolicyId) -> Option<MapAssetNameToNonZeroInt64> {
        self.0.deref().get(key.as_ref()).map(|v| v.clone().into())
    }

    /// Get the value of policy_id:asset_name if it exists.
    pub fn get(&self, policy_id: &PolicyId, asset: &AssetName) -> Option<i64> {
        self.0.get(policy_id.as_ref(), asset.as_ref())
    }

    /// Set the value of policy_id:asset_name to value.
    /// Returns the previous value, or None if it didn't exist
    pub fn set(&mut self, policy_id: &PolicyId, asset: &AssetName, value: i64) -> Option<i64> {
        self.0
            .set(policy_id.clone().into(), asset.clone().into(), value)
    }

    pub fn keys(&self) -> PolicyIdList {
        PolicyIdList(self.0.iter().map(|(k, _v)| *k).collect::<Vec<_>>())
    }

    /// Adds two mints together, checking value bounds.
    /// Does not modify self, and instead returns the result.
    pub fn checked_add(&self, rhs: &Mint) -> Result<Mint, JsError> {
        self.0
            .checked_add(rhs.as_ref())
            .map(Into::into)
            .map_err(Into::into)
    }

    /// Subtracts rhs from this mint.
    /// This does not modify self, and instead returns the result.
    pub fn checked_sub(&self, rhs: &Mint) -> Result<Mint, JsError> {
        self.0
            .checked_sub(rhs.as_ref())
            .map(Into::into)
            .map_err(Into::into)
    }

    /// Returns the multiasset where only positive (minting) entries are present
    pub fn as_positive_multiasset(&self) -> MultiAsset {
        self.0.as_positive_multiasset().into()
    }

    /// Returns the multiasset where only negative (burning) entries are present
    pub fn as_negative_multiasset(&self) -> MultiAsset {
        self.0.as_negative_multiasset().into()
    }
}

impl_wasm_conversions!(cml_chain::assets::Mint, Mint);

#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct Value(cml_chain::assets::Value);

impl_wasm_cbor_json_api!(Value);

#[wasm_bindgen]
impl Value {
    pub fn from_coin(coin: Coin) -> Self {
        cml_chain::assets::Value::from(coin).into()
    }

    pub fn new(coin: Coin, multiasset: &MultiAsset) -> Self {
        cml_chain::assets::Value::new(coin, multiasset.clone().into()).into()
    }

    pub fn coin(&self) -> Coin {
        self.0.coin
    }

    pub fn multi_asset(&self) -> MultiAsset {
        self.0.multiasset.clone().into()
    }

    pub fn zero() -> Value {
        cml_chain::assets::Value::zero().into()
    }

    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }

    pub fn has_multiassets(&self) -> bool {
        self.0.has_multiassets()
    }

    pub fn checked_add(&self, rhs: &Value) -> Result<Value, JsError> {
        self.0
            .checked_add(rhs.as_ref())
            .map(Into::into)
            .map_err(Into::into)
    }

    /// Subtract ADA and/or assets
    /// Removes an asset from the list if the result is 0 or less
    /// Does not modify this object, instead the result is returned
    /// None is returned if there would be integer underflow
    pub fn checked_sub(&self, rhs: &Value) -> Result<Value, JsError> {
        self.0
            .checked_sub(rhs.as_ref())
            .map(Into::into)
            .map_err(Into::into)
    }

    pub fn clamped_sub(&self, rhs: &Value) -> Value {
        self.0.clamped_sub(rhs.as_ref()).into()
    }
}

impl_wasm_conversions!(cml_chain::assets::Value, Value);