use js_export_macro::js_export;
use miden_client::Word as NativeWord;
use miden_client::account::AccountId as NativeAccountId;
use miden_client::asset::{Asset as NativeAsset, FungibleAsset as FungibleAssetNative};
use super::account_id::AccountId;
use super::word::Word;
use crate::platform::{JsErr, from_str_err, js_u64_to_u64, u64_to_js_u64};
#[derive(Clone, Copy)]
#[js_export]
pub struct FungibleAsset(FungibleAssetNative);
#[js_export]
impl FungibleAsset {
#[js_export(constructor)]
pub fn new(faucet_id: &AccountId, amount: JsU64) -> Result<FungibleAsset, JsErr> {
FungibleAsset::new_inner(faucet_id, js_u64_to_u64(amount))
}
pub fn amount(&self) -> JsU64 {
u64_to_js_u64(self.0.amount().as_u64())
}
#[js_export(js_name = "faucetId")]
pub fn faucet_id(&self) -> AccountId {
self.0.faucet_id().into()
}
#[js_export(js_name = "intoWord")]
pub fn into_word(&self) -> Word {
let native_word: NativeWord = self.0.to_value_word();
native_word.into()
}
}
impl FungibleAsset {
pub(crate) fn new_inner(faucet_id: &AccountId, amount: u64) -> Result<FungibleAsset, JsErr> {
let native_faucet_id: NativeAccountId = faucet_id.into();
let native_asset = FungibleAssetNative::new(native_faucet_id, amount)
.map_err(|e| from_str_err(&format!("Failed to create FungibleAsset: {e}")))?;
Ok(FungibleAsset(native_asset))
}
}
impl From<FungibleAsset> for NativeAsset {
fn from(fungible_asset: FungibleAsset) -> Self {
fungible_asset.0.into()
}
}
impl From<&FungibleAsset> for NativeAsset {
fn from(fungible_asset: &FungibleAsset) -> Self {
fungible_asset.0.into()
}
}
impl From<FungibleAssetNative> for FungibleAsset {
fn from(native_asset: FungibleAssetNative) -> Self {
FungibleAsset(native_asset)
}
}
impl From<&FungibleAssetNative> for FungibleAsset {
fn from(native_asset: &FungibleAssetNative) -> Self {
FungibleAsset(*native_asset)
}
}
impl_napi_from_value!(FungibleAsset);