Skip to content

Commit

Permalink
Merge pull request #64 from RGB-WG/fix/issued-supply
Browse files Browse the repository at this point in the history
Fix issued supply
  • Loading branch information
dr-orlovsky authored Jun 14, 2023
2 parents d5d40fc + 882ad6b commit a0f98cf
Show file tree
Hide file tree
Showing 19 changed files with 84 additions and 23 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ wasm-bindgen-test = "0.3"
features = [ "all" ]

[patch.crates-io]
strict_types = { git = "https://github.com/strict-types/strict-types", branch = "develop" }
strict_types = { git = "https://github.com/strict-types/strict-types" }
commit_verify = { git = "https://github.com/LNP-BP/client_side_validation" }
bp-core = { git = "https://github.com/BP-WG/bp-core" }
aluvm = { git = "https://github.com/AluVM/rust-aluvm" }
Expand Down
3 changes: 2 additions & 1 deletion src/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ pub trait InventoryWallet: Inventory {
///
/// 1. If PSBT output has BIP32 derivation information it belongs to our
/// wallet - except when it matches address from the invoice.
#[allow(clippy::result_large_err, clippy::type_complexity)]
fn pay(
&mut self,
invoice: RgbInvoice,
Expand Down Expand Up @@ -142,7 +143,7 @@ pub trait InventoryWallet: Inventory {
// NB: Here we assume that if output has derivation information it belongs to our wallet.
.bip32_derivation
.first_key_value()
.and_then(|(_, src)| src.1.into_iter().rev().skip(1).next())
.and_then(|(_, src)| src.1.into_iter().rev().nth(1))
.copied()
.map(u32::from)
.and_then(|index| u8::try_from(index).ok())
Expand Down
2 changes: 1 addition & 1 deletion src/psbt/lnpbp4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,6 @@ impl OutputLnpbp4 for Output {
let key = ProprietaryKey::lnpbp4_min_tree_depth();
let val = vec![min_depth];
let prev = self.lnpbp4_min_tree_depth();
self.proprietary.insert(key, val).and_then(|_| prev)
self.proprietary.insert(key, val).and(prev)
}
}
4 changes: 3 additions & 1 deletion src/psbt/rgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ pub enum RgbPsbtError {
InvalidTransition(SerializeError),
}

#[allow(clippy::result_large_err)]
pub trait RgbExt {
fn rgb_contract_ids(&self) -> BTreeSet<ContractId>;

Expand Down Expand Up @@ -165,7 +166,7 @@ impl RgbExt for Psbt {
prop_key.subtype == PSBT_IN_RGB_CONSUMED_BY
})
.map(|prop_key| &prop_key.key)
.filter_map(|key| ContractId::from_slice(key))
.filter_map(ContractId::from_slice)
})
.collect()
}
Expand Down Expand Up @@ -255,6 +256,7 @@ pub trait RgbInExt {
///
/// If the input already contains [`PSBT_IN_RGB_NODE_ID`] key with the given
/// `contract_id` but referencing different [`OpId`].
#[allow(clippy::result_large_err)]
fn set_rgb_consumer(
&mut self,
contract_id: ContractId,
Expand Down
2 changes: 1 addition & 1 deletion src/psbt/tapret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ impl OutputTapret for Output {
/// current crate.
fn tapret_proof(&self) -> Option<TapretPathProof> {
let data = self.proprietary.get(&ProprietaryKey::tapret_proof())?;
let vec = Confined::try_from_iter(data.into_iter().copied()).ok()?;
let vec = Confined::try_from_iter(data.iter().copied()).ok()?;
TapretPathProof::from_strict_serialized::<U16>(vec).ok()
}
}
2 changes: 1 addition & 1 deletion std/src/containers/bindle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ impl<C: BindleContent> FromStr for Bindle<C> {
return Err(BindleParseError::WrongStructure);
}
let mut header_id = None;
while let Some(line) = lines.next() {
for line in lines.by_ref() {
if line.is_empty() {
break;
}
Expand Down
9 changes: 3 additions & 6 deletions std/src/containers/consignment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,9 @@ impl<const TYPE: bool> Consignment<TYPE> {
pub fn contract_id(&self) -> ContractId { self.genesis.contract_id() }

pub fn anchored_bundle(&self, bundle_id: BundleId) -> Option<&AnchoredBundle> {
for anchored_bundle in &self.bundles {
if anchored_bundle.bundle.bundle_id() == bundle_id {
return Some(anchored_bundle);
}
}
None
self.bundles
.iter()
.find(|anchored_bundle| anchored_bundle.bundle.bundle_id() == bundle_id)
}

pub fn validation_status(&self) -> Option<&validation::Status> {
Expand Down
2 changes: 1 addition & 1 deletion std/src/interface/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ impl<Seal: ExposedSeal> OperationBuilder<Seal> {
let state = RevealedValue::new(value, &mut thread_rng());
match self.fungible.get_mut(&type_id) {
Some(assignments) => {
assignments.insert(seal.into(), state.into())?;
assignments.insert(seal.into(), state)?;
}
None => {
self.fungible
Expand Down
1 change: 1 addition & 0 deletions std/src/interface/iface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ impl ToBaid58<32> for IfaceId {
impl FromBaid58<32> for IfaceId {}

impl IfaceId {
#[allow(clippy::wrong_self_convention)]
fn to_baid58_string(&self) -> String { format!("{}", self.to_baid58()) }
}

Expand Down
1 change: 1 addition & 0 deletions std/src/interface/iimpl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ impl ToBaid58<32> for ImplId {
impl FromBaid58<32> for ImplId {}

impl ImplId {
#[allow(clippy::wrong_self_convention)]
fn to_baid58_string(&self) -> String { format!("{}", self.to_baid58()) }
}

Expand Down
54 changes: 52 additions & 2 deletions std/src/interface/rgb20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::iter::Sum;

use amplify::confinement::SmallOrdSet;
use bp::bc::stl::bitcoin_stl;
use strict_encoding::{StrictDeserialize, StrictSerialize};
use strict_types::{CompileError, LibBuilder, TypeLib};
use strict_types::{CompileError, LibBuilder, StrictVal, TypeLib};

use super::{
AssignIface, GenesisIface, GlobalIface, Iface, OwnedIface, Req, TransitionIface, VerNo,
Expand All @@ -48,6 +50,25 @@ pub const LIB_ID_RGB20: &str = "ethnic_raja_gloria_9tSQiAn1aGijb2F892JxTqcHDgmri
)]
pub struct Amount(u64);

impl StrictSerialize for Amount {}
impl StrictDeserialize for Amount {}

impl Amount {
pub fn zero() -> Self { Amount(0) }

pub fn one() -> Self { Amount(1) }

pub fn from_strict_val_unchecked(value: &StrictVal) -> Self {
value.unwrap_uint::<u64>().into()
}
}

impl Sum for Amount {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Amount::zero(), |acc, i| acc + i)
}
}

#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
#[derive(StrictType, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_RGB20)]
Expand Down Expand Up @@ -122,7 +143,7 @@ pub fn rgb20() -> Iface {
fname!("spec") => GlobalIface::required(types.get("RGBContract.DivisibleAssetSpec")),
fname!("terms") => GlobalIface::required(types.get("RGBContract.RicardianContract")),
fname!("created") => GlobalIface::required(types.get("RGBContract.Timestamp")),
fname!("issuedSupply") => GlobalIface::none_or_many(types.get("RGB20.Amount")),
fname!("issuedSupply") => GlobalIface::one_or_many(types.get("RGB20.Amount")),
fname!("burnedSupply") => GlobalIface::none_or_many(types.get("RGB20.Amount")),
fname!("replacedSupply") => GlobalIface::none_or_many(types.get("RGB20.Amount")),
},
Expand Down Expand Up @@ -296,6 +317,35 @@ impl Rgb20 {
.expect("RGB20 interface requires global `spec`")[0];
DivisibleAssetSpec::from_strict_val_unchecked(strict_val)
}

pub fn total_issued_supply(&self) -> Amount {
self.0
.global("issuedSupply")
.expect("RGB20 interface requires global `issuedSupply`")
.iter()
.map(Amount::from_strict_val_unchecked)
.sum()
}

pub fn total_burned_supply(&self) -> Amount {
self.0
.global("burnedSupply")
.unwrap_or_default()
.iter()
.map(Amount::from_strict_val_unchecked)
.sum()
}

pub fn total_replaced_supply(&self) -> Amount {
self.0
.global("replacedSupply")
.unwrap_or_default()
.iter()
.map(Amount::from_strict_val_unchecked)
.sum()
}

pub fn total_supply(&self) -> Amount { self.total_issued_supply() - self.total_burned_supply() }
}

#[cfg(test)]
Expand Down
5 changes: 4 additions & 1 deletion std/src/persistence/inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ pub enum InventoryInconsistency {
Stash(StashInconsistency),
}

#[allow(clippy::result_large_err)]
pub trait Inventory: Deref<Target = Self::Stash> {
type Stash: Stash;
/// Error type which must indicate problems on data retrieval.
Expand Down Expand Up @@ -406,6 +407,7 @@ pub trait Inventory: Deref<Target = Self::Stash> {
fn store_seal_secret(&mut self, seal: GraphSeal) -> Result<(), InventoryError<Self::Error>>;
fn seal_secrets(&mut self) -> Result<BTreeSet<GraphSeal>, InventoryError<Self::Error>>;

#[allow(clippy::type_complexity)]
fn export_contract(
&mut self,
contract_id: ContractId,
Expand All @@ -420,6 +422,7 @@ pub trait Inventory: Deref<Target = Self::Stash> {
// TODO: Add known sigs to the bindle
}

#[allow(clippy::type_complexity)]
fn transfer(
&mut self,
contract_id: ContractId,
Expand Down Expand Up @@ -507,7 +510,7 @@ pub trait Inventory: Deref<Target = Self::Stash> {
.entry(id)
.or_insert(self.anchored_bundle(id)?.clone())
.bundle
.reveal_transition(&transition)?;
.reveal_transition(transition)?;
}

let genesis = self.genesis(contract_id)?;
Expand Down
1 change: 1 addition & 0 deletions std/src/persistence/stock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl DerefMut for Stock {
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.hoard }
}

#[allow(clippy::result_large_err)]
impl Stock {
fn consume_consignment<R: ResolveHeight, const TYPE: bool>(
&mut self,
Expand Down
2 changes: 1 addition & 1 deletion std/src/stl/mime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl MediaType {
///
/// Panics is the provided string is an invalid type specifier.
pub fn with(s: &'static str) -> Self {
let (ty, subty) = s.split_once("/").expect("invalid static media type string");
let (ty, subty) = s.split_once('/').expect("invalid static media type string");
MediaType {
ty: MediaRegName::from(ty),
subtype: if subty == "*" {
Expand Down
3 changes: 2 additions & 1 deletion std/src/stl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@
// limitations under the License.

mod specs;
#[allow(clippy::module_inception)]
mod stl;
mod error;
mod mime;
mod chain;

pub use chain::ProofOfReserves;
pub(self) use error::Error;
pub use mime::MediaType;
pub use mime::{MediaRegName, MediaType};
pub use specs::{
AssetNaming, Details, DivisibleAssetSpec, Name, Precision, RicardianContract, Ticker, Timestamp,
};
Expand Down
3 changes: 1 addition & 2 deletions std/src/stl/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,8 +330,7 @@ impl AssetNaming {
ticker: Ticker::from_str(&ticker).expect("invalid asset ticker"),
name: Name::from_str(&name).expect("invalid asset name"),
details: details
.as_ref()
.map(String::as_str)
.as_deref()
.map(Details::from_str)
.transpose()
.expect("invalid asset details"),
Expand Down
5 changes: 5 additions & 0 deletions std/src/stl/stl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ pub fn rgb_contract_stl() -> TypeLib {
#[derive(Debug)]
pub struct StandardTypes(SymbolicSys);

impl Default for StandardTypes {
fn default() -> Self { StandardTypes::new() }
}

impl StandardTypes {
pub fn new() -> Self {
Self::try_with([std_stl(), bitcoin_stl(), rgb_contract_stl()])
Expand All @@ -67,6 +71,7 @@ impl StandardTypes {
.expect("error in standard RGBContract type system")
}

#[allow(clippy::result_large_err)]
fn try_with(libs: impl IntoIterator<Item = TypeLib>) -> Result<Self, Error> {
let mut builder = SystemBuilder::new();
for lib in libs.into_iter() {
Expand Down
4 changes: 2 additions & 2 deletions std/tests/data/rgb20.rgba
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
-----BEGIN RGB INTERFACE-----
Id: 7Rrqv5iVnTv3DquiK7FJmdVBy1nNYBuSbkXpXRunwZzy
Id: BR2fhPEKPtsjoEz2PDpBV4o24HCjvD1Dk4nHnaRx94fQ
Name: RGB20

AAVSR0IyMAYMYnVybmVkU3VwcGx5AYiMWGVjOvE7lbfNGo2K8trB3BQLl3JR2dTa
88dRHI6EAAEHY3JlYXRlZAFZbno6DqNlnhAw8YtNZaO5E+5YUAf8914Lts3BacHA
OwEADGlzc3VlZFN1cHBseQGIjFhlYzrxO5W3zRqNivLawdwUC5dyUdnU2vPHURyO
hAABDnJlcGxhY2VkU3VwcGx5AYiMWGVjOvE7lbfNGo2K8trB3BQLl3JR2dTa88dR
hAEBDnJlcGxhY2VkU3VwcGx5AYiMWGVjOvE7lbfNGo2K8trB3BQLl3JR2dTa88dR
HI6EAAEEc3BlYwGZYk235CaSmVSTLt/I0melUpcCKTzVq8BWTm8iWzP68QEABXRl
cm1zARjLlG8Sk88YDp143MZbxZtHL//+rfv1jbGYzIMo9ksBAQAFCmFzc2V0T3du
ZXICAAABCWJ1cm5FcG9jaAEBAAAJYnVyblJpZ2h0AQEAARJpbmZsYXRpb25BbGxv
Expand Down

0 comments on commit a0f98cf

Please sign in to comment.