Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manta API: AssetMetadata upgrade #289

Merged
merged 49 commits into from
Jan 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
33e76eb
utxo protocol
SupremoUGH Nov 24, 2022
7b5f578
utxo finished
SupremoUGH Nov 24, 2022
7d2874d
sender and receiver
SupremoUGH Nov 24, 2022
5896feb
transfer mod finished
SupremoUGH Nov 24, 2022
d762ad6
wallet done
SupremoUGH Nov 25, 2022
19c49ea
mantapay config
SupremoUGH Nov 25, 2022
d5a9e62
mantapay config works
SupremoUGH Nov 25, 2022
63a3de4
tests
SupremoUGH Nov 25, 2022
b2720e2
signer base fixed
SupremoUGH Nov 29, 2022
2e1a03b
signer client
SupremoUGH Nov 29, 2022
4f9a6bb
parameters + testing
SupremoUGH Nov 29, 2022
eed927e
parameters, test, simulation and binaries
SupremoUGH Nov 29, 2022
f5d957e
benchmark
SupremoUGH Nov 29, 2022
9905cde
sdk
SupremoUGH Nov 29, 2022
4a714cf
re-exports in manta-pay
SupremoUGH Nov 29, 2022
7eda1b1
feature issue solved
SupremoUGH Nov 29, 2022
9853cdf
docs
SupremoUGH Nov 29, 2022
9fbbdf5
changelog
SupremoUGH Nov 29, 2022
c4e0eec
sample impls revised
SupremoUGH Nov 30, 2022
a451d2e
sample issue solved in tests
SupremoUGH Nov 30, 2022
83ba1dd
balance tests
SupremoUGH Nov 30, 2022
5ce37e4
DEFAULT_BRANCH changed
SupremoUGH Nov 30, 2022
ce575e7
zero signature issue tested and fixed
SupremoUGH Nov 30, 2022
7d31418
Apply suggestions from code review
SupremoUGH Dec 1, 2022
1982dd6
some comments addressed
SupremoUGH Dec 1, 2022
5b811bc
more comments addressed
SupremoUGH Dec 1, 2022
655b194
sample issue solved
SupremoUGH Dec 1, 2022
e481aec
public fields made private again
SupremoUGH Dec 1, 2022
c7b1e94
compat deleted
SupremoUGH Dec 1, 2022
6142d47
FIXME
SupremoUGH Dec 1, 2022
cc64ef9
parameters branch changed to main + feature issue solved
SupremoUGH Dec 1, 2022
563e95d
feature issue solved
SupremoUGH Dec 1, 2022
2d52252
generalised AssetMetadata to trait
SupremoUGH Dec 2, 2022
c086a87
small upgrade AssetMetadata trait
SupremoUGH Dec 2, 2022
44de3ec
NFT support
SupremoUGH Dec 2, 2022
ce92a28
changelog
SupremoUGH Dec 2, 2022
865f0a3
clippy issues
SupremoUGH Dec 2, 2022
17abb0a
now AssetMetadata is part of signer connection and signer configuration
SupremoUGH Dec 2, 2022
88a8be0
docs
SupremoUGH Dec 2, 2022
e2df72f
docs
SupremoUGH Dec 2, 2022
19ce634
merge main
SupremoUGH Dec 5, 2022
d24c707
Merge branch 'main' into feat/manta-api-assetmetadata
bhgomes Dec 7, 2022
5560192
Merge branch 'main' into feat/manta-api-assetmetadata
bhgomes Jan 10, 2023
a0e3236
chore: fix Rust upgrade warnings
bhgomes Jan 10, 2023
58baf17
chore: fix std import
bhgomes Jan 10, 2023
b938f14
Merge branch 'main' into feat/manta-api-assetmetadata
bhgomes Jan 12, 2023
a42d26b
Merge branch 'main' into feat/manta-api-assetmetadata
SupremoUGH Jan 24, 2023
bbceb0a
display value methods updated as in PR 296
SupremoUGH Jan 24, 2023
207c8c7
clippy
SupremoUGH Jan 24, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]
### Added
- [\#289](https://github.com/Manta-Network/manta-rs/pull/289) AssetMetadata upgrade and NFT support.
- [\#310](https://github.com/Manta-Network/manta-rs/pull/310) Add identity verification algorithm using ToPublic circuit
### Changed

Expand Down Expand Up @@ -47,7 +48,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
## [0.5.7] - 2022-11-04
### Added
- [\#262](https://github.com/Manta-Network/manta-rs/pull/262) Added exporting seed phrase and multiple networks support for signer.
- [#276](https://github.com/Manta-Network/manta-rs/pull/276) New circuits part 1: manta-crypto abstractions
- [\#276](https://github.com/Manta-Network/manta-rs/pull/276) New circuits part 1: manta-crypto abstractions

### Changed
- [\#274](https://github.com/Manta-Network/manta-rs/pull/274) Update TS client installer script to use release 0.5.6.
Expand Down
106 changes: 3 additions & 103 deletions manta-accounting/src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,12 @@
//! Assets
//!
//! This module defines the data structures and canonical encodings of a standard notion of "asset".
//! Assets are defined by an `AssetId` field and an `AssetValue` field. For describing an [`Asset`]
//! with a particular `AssetId` we use [`AssetMetadata`] to assign a symbol and decimals for
//! human-readable display purposes.
//! Assets are defined by an `AssetId` field and an `AssetValue` field.

#![allow(clippy::uninlined_format_args)] // NOTE: Clippy false positive https://github.com/rust-lang/rust-clippy/issues/9715 on Display implementation on Asset below

use alloc::{
collections::btree_map::{BTreeMap, Entry as BTreeMapEntry},
format,
string::{String, ToString},
vec,
vec::Vec,
};
Expand All @@ -35,12 +31,11 @@ use core::{
fmt::Debug,
hash::Hash,
iter::{self, FusedIterator},
ops::{Add, AddAssign, Deref, Div, Sub, SubAssign},
ops::{Add, AddAssign, Deref, Sub, SubAssign},
slice,
};
use derive_more::{Display, From};
use manta_crypto::{
arkworks::std,
constraint::{HasInput, Input},
eclair::{
self,
Expand All @@ -65,7 +60,7 @@ use manta_util::{
use manta_util::serde::{Deserialize, Serialize};

#[cfg(feature = "std")]
use self::std::{
use std::{
collections::hash_map::{Entry as HashMapEntry, HashMap, RandomState},
hash::BuildHasher,
};
Expand Down Expand Up @@ -1057,98 +1052,3 @@ where
}

impl<'s, I, V, M> FusedIterator for SelectionKeys<'s, I, V, M> where M: AssetMap<I, V> + ?Sized {}

/// Asset Metadata
#[cfg_attr(
feature = "serde",
derive(Deserialize, Serialize),
serde(crate = "manta_util::serde")
)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct AssetMetadata {
/// Number of Decimals
pub decimals: u32,

/// Asset Symbol
pub symbol: String,
}

impl AssetMetadata {
/// Returns a string formatting of only the `value` with `digits` fractional digits,
/// interpreted using `self` as the metadata.
#[inline]
pub fn display_value<V>(&self, value: V, digits: u32) -> String
where
for<'v> &'v V: Div<u128, Output = u128>,
V: manta_crypto::arkworks::std::fmt::Display,
V: std::ops::Sub<u128, Output = u128>,
{
let value_base_units = &value / (10u128.pow(self.decimals));
let fractional_digits =
&value / (10u128.pow(self.decimals - digits)) % (10u128.pow(digits));

let decimals: u128 = value - (value_base_units * 10u128.pow(digits));
let decimals_length: u32 = decimals.to_string().len().try_into().unwrap();
let leading_zeros = "0".repeat((digits - decimals_length).try_into().unwrap());
format!("{value_base_units}.{leading_zeros}{fractional_digits}")
}

/// Returns a string formatting of `value` with `digits` fractional digits, interpreted using
/// `self` as the metadata including the symbol.
#[inline]
pub fn display<V>(&self, value: V, digits: u32) -> String
where
for<'v> &'v V: Div<u128, Output = u128>,
V: manta_crypto::arkworks::std::fmt::Display,
V: std::ops::Sub<u128, Output = u128>,
{
format!("{} {}", self.display_value(value, digits), self.symbol)
}
}

/// Metadata Display
pub trait MetadataDisplay {
/// Returns a string representation of `self` given the asset `metadata`.
fn display(&self, metadata: &AssetMetadata) -> String;
}

/// Asset Manager
pub trait AssetManager<I> {
/// Returns the metadata associated to `id`.
fn metadata(&self, id: &I) -> Option<&AssetMetadata>;
}

/// Implements [`AssetManager`] for map types.
macro_rules! impl_asset_manager_for_maps_body {
($I:ident) => {
#[inline]
fn metadata(&self, id: &$I) -> Option<&AssetMetadata> {
self.get(id)
}
};
}

/// B-Tree Map [`AssetManager`] Implementation
pub type BTreeAssetManager<I> = BTreeMap<I, AssetMetadata>;

impl<I> AssetManager<I> for BTreeAssetManager<I>
where
I: Ord,
{
impl_asset_manager_for_maps_body! { I }
}

/// Hash Map [`AssetManager`] Implementation
#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
pub type HashAssetManager<I, S = RandomState> = HashMap<I, AssetMetadata, S>;

#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
impl<I, S> AssetManager<I> for HashAssetManager<I, S>
where
I: Eq + Hash,
S: BuildHasher + Default,
{
impl_asset_manager_for_maps_body! { I }
}
20 changes: 2 additions & 18 deletions manta-accounting/src/transfer/canonical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
// TODO: Add typing for `ProvingContext` and `VerifyingContext` against the canonical shapes.

use crate::{
asset::{self, AssetMap, AssetMetadata, MetadataDisplay},
asset::{self, AssetMap},
transfer::{
has_public_participants, internal_pair, requires_authorization, utxo::UtxoReconstruct,
Address, Asset, AssociatedData, Authorization, AuthorizationContext, Configuration,
Expand All @@ -28,7 +28,7 @@ use crate::{
TransferPost, TransferPostingKeyRef, Utxo, VerifyingContext,
},
};
use alloc::{string::String, vec::Vec};
use alloc::vec::Vec;
use core::{fmt::Debug, hash::Hash};
use manta_crypto::rand::{CryptoRng, RngCore};
use manta_util::{create_seal, seal};
Expand Down Expand Up @@ -420,22 +420,6 @@ where
{
self.value() == &Default::default()
}

/// Returns a display for the asset and address internal to `self` given the asset `metadata`.
#[inline]
pub fn display<F>(&self, metadata: &AssetMetadata, f: F) -> (String, Option<String>)
where
F: FnOnce(&Address<C>) -> String,
C::AssetValue: MetadataDisplay,
{
match self {
Self::ToPrivate(asset) => (asset.value.display(metadata), None),
Self::PrivateTransfer(asset, address) => {
(asset.value.display(metadata), Some(f(address)))
}
Self::ToPublic(asset) => (asset.value.display(metadata), None),
}
}
}

/// Transaction Kind
Expand Down
6 changes: 3 additions & 3 deletions manta-accounting/src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
//! [`Ledger`]: ledger::Connection

use crate::{
asset::{AssetList, AssetMetadata},
asset::AssetList,
transfer::{
canonical::{Transaction, TransactionKind},
Address, Asset, Configuration, IdentifiedAsset, TransferPost, UtxoAccumulatorModel,
Expand Down Expand Up @@ -372,7 +372,7 @@ where
pub async fn sign(
&mut self,
transaction: Transaction<C>,
metadata: Option<AssetMetadata>,
metadata: Option<S::AssetMetadata>,
) -> Result<SignResponse<C>, Error<C, L, S>> {
self.check(&transaction)
.map_err(Error::InsufficientBalance)?;
Expand Down Expand Up @@ -437,7 +437,7 @@ where
pub async fn post(
&mut self,
transaction: Transaction<C>,
metadata: Option<AssetMetadata>,
metadata: Option<S::AssetMetadata>,
) -> Result<L::Response, Error<C, L, S>>
where
L: ledger::Read<SyncData<C>, Checkpoint = S::Checkpoint>
Expand Down
31 changes: 19 additions & 12 deletions manta-accounting/src/wallet/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
// internally.

use crate::{
asset::{AssetMap, AssetMetadata},
asset::AssetMap,
key::{self, Account, AccountCollection, DeriveAddress, DeriveAddresses},
transfer::{
self,
Expand Down Expand Up @@ -64,6 +64,9 @@ pub trait Connection<C>
where
C: transfer::Configuration,
{
/// Asset Metadata Type
type AssetMetadata;

/// Checkpoint Type
///
/// This checkpoint is used by the signer to stay synchronized with wallet and the ledger.
Expand All @@ -85,7 +88,7 @@ where
/// Signs a transaction and returns the ledger transfer posts if successful.
fn sign(
&mut self,
request: SignRequest<C>,
request: SignRequest<Self::AssetMetadata, C>,
) -> LocalBoxFutureResult<Result<SignResponse<C>, SignError<C>>, Self::Error>;

/// Returns the [`Address`] corresponding to `self`.
Expand Down Expand Up @@ -400,30 +403,30 @@ pub type SyncResult<C, T> = Result<SyncResponse<C, T>, SyncError<T>>;
derive(Deserialize, Serialize),
serde(
bound(
deserialize = "Transaction<C>: Deserialize<'de>",
serialize = "Transaction<C>: Serialize"
deserialize = "Transaction<C>: Deserialize<'de>, A: Deserialize<'de>",
serialize = "Transaction<C>: Serialize, A: Serialize"
),
crate = "manta_util::serde",
deny_unknown_fields
)
)]
#[derive(derivative::Derivative)]
#[derivative(
Clone(bound = "Transaction<C>: Clone"),
Debug(bound = "Transaction<C>: Debug"),
Eq(bound = "Transaction<C>: Eq"),
Hash(bound = "Transaction<C>: Hash"),
PartialEq(bound = "Transaction<C>: PartialEq")
Clone(bound = "Transaction<C>: Clone, A: Clone"),
Debug(bound = "Transaction<C>: Debug, A: Debug"),
Eq(bound = "Transaction<C>: Eq, A: Eq"),
Hash(bound = "Transaction<C>: Hash, A: Hash"),
PartialEq(bound = "Transaction<C>: PartialEq, A: PartialEq")
)]
pub struct SignRequest<C>
pub struct SignRequest<A, C>
where
C: transfer::Configuration,
{
/// Transaction Data
pub transaction: Transaction<C>,

/// Asset Metadata
pub metadata: Option<AssetMetadata>,
pub metadata: Option<A>,
}

/// Signer Signing Response
Expand Down Expand Up @@ -619,6 +622,9 @@ pub trait Configuration: transfer::Configuration {
/// Asset Map Type
type AssetMap: AssetMap<Self::AssetId, Self::AssetValue, Key = Identifier<Self>>;

/// Asset Metadata Type
type AssetMetadata;

/// Random Number Generator Type
type Rng: CryptoRng + FromEntropy + RngCore;
}
Expand Down Expand Up @@ -1593,6 +1599,7 @@ impl<C> Connection<C> for Signer<C>
where
C: Configuration,
{
type AssetMetadata = C::AssetMetadata;
type Checkpoint = C::Checkpoint;
type Error = Infallible;

Expand All @@ -1610,7 +1617,7 @@ where
#[inline]
fn sign(
&mut self,
request: SignRequest<C>,
request: SignRequest<Self::AssetMetadata, C>,
) -> LocalBoxFutureResult<Result<SignResponse<C>, SignError<C>>, Self::Error> {
Box::pin(async move { Ok(self.sign(request.transaction)) })
}
Expand Down
16 changes: 8 additions & 8 deletions manta-accounting/src/wallet/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
// TODO: Generalize `PushResponse` so that we can test against more general wallet setups.

use crate::{
asset::{AssetList, AssetMetadata},
asset::AssetList,
transfer::{canonical::Transaction, Address, Asset, Configuration, TransferPost},
wallet::{
ledger,
Expand Down Expand Up @@ -493,7 +493,7 @@ where
async fn post(
&mut self,
transaction: Transaction<C>,
metadata: Option<AssetMetadata>,
metadata: Option<S::AssetMetadata>,
) -> Result<L::Response, Error<C, L, S>> {
self.wallet.post(transaction, metadata).await
}
Expand Down Expand Up @@ -611,17 +611,17 @@ where
/// [`ToPrivate`]: ActionType::ToPrivate
/// [`Skip`]: ActionType::Skip
#[inline]
async fn sample_private_transfer<A, R>(
async fn sample_private_transfer<F, R>(
&mut self,
is_self: bool,
rng: &mut R,
address: A,
address: F,
) -> MaybeAction<C, L, S>
where
C::AssetValue: SampleUniform,
L: PublicBalanceOracle<C>,
R: RngCore + ?Sized,
A: FnOnce(&mut R) -> Result<Option<Address<C>>, Error<C, L, S>>,
F: FnOnce(&mut R) -> Result<Option<Address<C>>, Error<C, L, S>>,
{
let action = if is_self {
ActionType::SelfTransfer
Expand All @@ -647,16 +647,16 @@ where
/// [`ToPrivate`]: ActionType::ToPrivate
/// [`Skip`]: ActionType::Skip
#[inline]
async fn sample_zero_private_transfer<A, R>(
async fn sample_zero_private_transfer<F, R>(
&mut self,
is_self: bool,
rng: &mut R,
address: A,
address: F,
) -> MaybeAction<C, L, S>
where
L: PublicBalanceOracle<C>,
R: RngCore + ?Sized,
A: FnOnce(&mut R) -> Result<Option<Address<C>>, Error<C, L, S>>,
F: FnOnce(&mut R) -> Result<Option<Address<C>>, Error<C, L, S>>,
{
let action = if is_self {
ActionType::SelfTransfer
Expand Down
3 changes: 2 additions & 1 deletion manta-pay/src/signer/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{
VerifyingContext,
},
key::{CoinType, KeySecret, Testnet},
signer::Checkpoint,
signer::{AssetMetadata, Checkpoint},
};
use alloc::collections::BTreeMap;
use core::{cmp, mem};
Expand Down Expand Up @@ -89,6 +89,7 @@ impl wallet::signer::Configuration for Config {
type Checkpoint = Checkpoint;
type UtxoAccumulator = UtxoAccumulator;
type AssetMap = HashAssetMap<Identifier<Self>, Self::AssetId, Self::AssetValue>;
type AssetMetadata = AssetMetadata;
type Rng = ChaCha20Rng;
}

Expand Down
Loading