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

Update to Strict-Type 1.4.x #255

Merged
merged 5 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
420 changes: 221 additions & 199 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 6 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,12 @@ bitcoin = { version = "0.29.2", features = ["base64"] }
bitcoin_hashes = "0.12.0"
bitcoin_scripts = "0.10.0-alpha.2"
bitcoin_blockchain = "0.10.0-alpha.2"
bp-core = "0.10.4"
commit_verify = "0.10.3"
bp-core = { version = "0.10.4", features = ["stl"] }
commit_verify = { version = "0.10.3", features = ["stl"] }
bp-seals = "0.10.4"
indexmap = "1.9.3"
carbonado = "0.3.1"
console_error_panic_hook = "0.1.7"
# directories = "4.0.1"
miniscript_crate = { package = "miniscript", version = "9.0.1", features = [
"compiler",
] }
Expand Down Expand Up @@ -72,23 +71,20 @@ psbt = { version = "0.10.0-alpha.2", features = [
"construct",
] }
regex = "1.7.0"
reqwest = { version = "0.11.16", features = ["json"] }
reqwest = { version = "0.11.18", features = ["json"] }
rgb-contracts = { version = "0.10.0-beta.2", default-features = false, features = [
"log",
] }
rgb-wallet = { version = "0.10.2" }
rgb-std = { version = "0.10.2" }

# rgb_wallet_bp = { version = "0.10.2-backport", package = "rgb-wallet", path = "../rgb-wallet" }
# rgb_std_bp = { version = "0.10.2-backport", package = "rgb-std", path = "../rgb-wallet/std" }

rgb-schemata = { version = "0.10.0-beta.1" }
serde = "1.0.152"
serde_json = "1.0.91"
postcard = { version = "1.0.4", features = ["alloc"] }
serde-encrypt = "0.7.0"
strict_types = "1.3.0"
strict_encoding = "2.3.0"
strict_types = "1.4.1"
strict_encoding = "2.4.1"
tokio = { version = "1.28.2", features = ["macros", "sync"] }

[target.'cfg(target_arch = "wasm32")'.dependencies]
Expand Down Expand Up @@ -137,3 +133,4 @@ rgb-contracts = { git = "https://github.com/crisdut/rgb", branch = "release/bmc-
rgb-schemata = { git = "https://github.com/crisdut/rgbsc", branch = "release/bmc-v0.6" }
rgb-wallet = { git = "https://github.com/crisdut/rgb-wallet", branch = "release/bmc-v0.6" }
rgb-std = { git = "https://github.com/crisdut/rgb-wallet", branch = "release/bmc-v0.6" }
rgb-core = { git = "https://github.com/crisdut/rgb-core" }
5 changes: 1 addition & 4 deletions src/bitcoin/psbt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ pub async fn sign_psbt(
blockchain.broadcast(&tx).await?;

let txid = tx.txid();
let tx = blockchain
.get_tx(&txid)
.await
.expect("tx that was just broadcasted now exists");
let tx = blockchain.get_tx(&txid).await?;

let mut sent = 0;
let mut received = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub const NOSTR_PATH: &str = "m/44h/1237h/0h";

// Magic number for versioning descriptors
pub const DIBA_DESCRIPTOR_VERSION: u8 = 0;
pub const DIBA_MAGIC_NO: [u8; 4] = [b'D', b'I', b'B', b'A'];
pub const DIBA_MAGIC_NO: [u8; 4] = *b"DIBA";
pub const DIBA_DESCRIPTOR: [u8; 5] = [
DIBA_MAGIC_NO[0],
DIBA_MAGIC_NO[1],
Expand Down
19 changes: 8 additions & 11 deletions src/rgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,10 +426,7 @@ pub async fn transfer_asset(sk: &str, request: RgbTransferRequest) -> Result<Rgb
let psbt_hex = psbt.to_string();
let consig = RgbTransferResponse {
consig_id: transfer.bindle_id().to_string(),
consig: transfer
.to_strict_serialized::<U16>()
.expect("invalid transfer serialization")
.to_hex(),
consig: transfer.to_strict_serialized::<U16>()?.to_hex(),
psbt: psbt_hex,
commit: commit_hex,
};
Expand Down Expand Up @@ -529,7 +526,7 @@ pub async fn list_contracts(sk: &str) -> Result<ContractsResponse> {

let mut contracts = vec![];

for contract_id in stock.contract_ids().expect("invalid contracts state") {
for contract_id in stock.contract_ids()? {
let resp = extract_contract_by_id(contract_id, &mut stock, &mut resolver, &mut wallet)?;
contracts.push(resp);
}
Expand All @@ -548,10 +545,10 @@ pub async fn list_interfaces(sk: &str) -> Result<InterfacesResponse> {
let stock = retrieve_stock(sk, ASSETS_STOCK).await?;

let mut interfaces = vec![];
for schema_id in stock.schema_ids().expect("invalid schemas state") {
let schema = stock.schema(schema_id).expect("invalid schemas state");
for schema_id in stock.schema_ids()? {
let schema = stock.schema(schema_id)?;
for (iface_id, iimpl) in schema.clone().iimpls.into_iter() {
let face = stock.iface_by_id(iface_id).expect("invalid iface state");
let face = stock.iface_by_id(iface_id)?;

let item = InterfaceDetail {
name: face.name.to_string(),
Expand All @@ -569,11 +566,11 @@ pub async fn list_schemas(sk: &str) -> Result<SchemasResponse> {
let stock = retrieve_stock(sk, ASSETS_STOCK).await?;

let mut schemas = vec![];
for schema_id in stock.schema_ids().expect("invalid schemas state") {
let schema = stock.schema(schema_id).expect("invalid schemas state");
for schema_id in stock.schema_ids()? {
let schema = stock.schema(schema_id)?;
let mut ifaces = vec![];
for (iface_id, _) in schema.clone().iimpls.into_iter() {
let face = stock.iface_by_id(iface_id).expect("invalid iface state");
let face = stock.iface_by_id(iface_id)?;
ifaces.push(face.name.to_string());
}
schemas.push(SchemaDetail {
Expand Down
45 changes: 14 additions & 31 deletions src/rgb/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,9 @@ where
.expect("invalid contract data")
.to_base32(),
bech32::Variant::Bech32m,
)
.expect("invalid contract data");
let contract_strict = contract_bindle
.to_strict_serialized::<0xFFFFFF>()
.expect("invalid contract data")
.to_hex();
)?;

let contract_strict = contract_bindle.to_strict_serialized::<0xFFFFFF>()?.to_hex();

let contract_iface = stock
.contract_iface(contract_bindle.contract_id(), iface_id.to_owned())
Expand Down Expand Up @@ -148,37 +145,24 @@ where
for (index, (_, global_assign)) in contract_genesis.genesis.assignments.iter().enumerate() {
let idx = index as u16;
if global_assign.is_fungible() {
if let Some(reveal) = global_assign
.as_fungible_state_at(idx)
.expect("fail retrieve fungible data")
{
if let Some(reveal) = global_assign.as_fungible_state_at(idx)? {
supply += reveal.value.as_u64();
}
} else if global_assign.is_structured()
&& global_assign
.as_structured_state_at(idx)
.expect("fail retrieve structured data")
.is_some()
&& global_assign.as_structured_state_at(idx)?.is_some()
{
supply += 1;
}
}

let genesis = contract_genesis.genesis.clone();
let genesis_strict = genesis
.to_strict_serialized::<0xFFFFFF>()
.expect("invalid genesis data")
.to_hex();
let genesis_strict = genesis.to_strict_serialized::<0xFFFFFF>()?.to_hex();

let genesis_legacy = encode(
"rgb",
genesis
.to_strict_serialized::<0xFFFFFF>()
.expect("invalid contract data")
.to_base32(),
genesis.to_strict_serialized::<0xFFFFFF>()?.to_base32(),
bech32::Variant::Bech32m,
)
.expect("invalid contract data");
)?;

let genesis_formats = GenesisFormats {
legacy: genesis_legacy,
Expand All @@ -190,7 +174,10 @@ where
let mut meta = none!();
let ty: FieldName = FieldName::from("tokens");
if contract_iface.global(ty.clone()).is_ok() {
let type_id = contract_iface.iface.global_type(&ty).expect("");
let type_id = contract_iface
.iface
.global_type(&ty)
.expect("no global type id");

let type_schema = contract_iface
.state
Expand All @@ -217,16 +204,12 @@ where
if let Some(preview) = token_data.preview {
media = MediaInfo {
ty: preview.ty.to_string(),
source: String::from_utf8(preview.data.to_inner()).expect("invalid data"),
source: String::from_utf8(preview.data.to_inner())?,
};
}

let single = ContractMetadata::UDA(UDADetail {
token_index: token_data
.index
.to_string()
.parse()
.expect("invalid token_index"),
token_index: token_data.index.to_string().parse()?,
ticker: ticker.clone(),
name: name.clone(),
description: description.clone(),
Expand Down
53 changes: 26 additions & 27 deletions src/rgb/issue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ use rgbstd::contract::GenesisSeal;
use rgbstd::interface::rgb21::{Allocation, EmbeddedMedia, OwnedFraction, TokenData, TokenIndex};
use rgbstd::resolvers::ResolveHeight;
use rgbstd::stl::{
DivisibleAssetSpec, MediaType, Name, Precision, RicardianContract, Ticker, Timestamp,
Amount, ContractData, DivisibleAssetSpec, MediaType, Name, Precision, RicardianContract,
Ticker, Timestamp,
};
use rgbstd::validation::ResolveTx;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};

use rgbstd::containers::Contract;
use rgbstd::interface::{rgb20, rgb21, BuilderError, ContractBuilder};
Expand Down Expand Up @@ -48,16 +50,12 @@ where
T: ResolveHeight + ResolveTx,
T::Error: 'static,
{
let iface_name = match TypeName::from_str(iface) {
Ok(name) => name,
_ => return Err(IssueError::Forge(BuilderError::InterfaceMismatch)),
};
let iface_name = TypeName::from_str(iface)
.map_err(|_| IssueError::Forge(BuilderError::InterfaceMismatch))?;

let binding = stock.to_owned();
let iface = match binding.iface_by_name(&iface_name) {
Ok(name) => name,
_ => return Err(IssueError::Forge(BuilderError::InterfaceMismatch)),
};
let iface = stock
.iface_by_name(&iface_name)
.map_err(|_| IssueError::Forge(BuilderError::InterfaceMismatch))?;

if ticker.len() < 3 || ticker.len() > 8 || ticker.chars().any(|c| c < 'A' && c > 'Z') {
return Err(IssueError::InvalidTicker("Ticker must be between 3 and 8 chars, contain no spaces and consist only of capital letters".to_string()));
Expand All @@ -80,21 +78,16 @@ where
_ => return Err(IssueError::ContractNotfound(iface.name.to_string())),
};

let resp = match contract_issued {
Ok(resp) => resp,
Err(err) => return Err(IssueError::Forge(err)),
};
let resp = contract_issued.map_err(IssueError::Forge)?;
let contract_id = resp.contract_id().to_string();

let resp = match resp.clone().validate(resolver) {
Ok(resp) => resp,
Err(_err) => return Err(IssueError::ContractInvalid(resp.contract_id().to_string())),
};
let resp = resp
.validate(resolver)
.map_err(|_| IssueError::ContractInvalid(contract_id.clone()))?;

stock
.import_contract(resp.clone(), resolver)
.or(Err(IssueError::ImportContract(
resp.contract_id().to_string(),
)))?;
.or(Err(IssueError::ImportContract(contract_id)))?;

Ok(resp)
}
Expand All @@ -118,7 +111,8 @@ fn issue_fungible_asset(
let description: &'static str = Box::leak(description.to_string().into_boxed_str());
let precision = Precision::try_from(precision).expect("invalid precision");
let spec = DivisibleAssetSpec::new(ticker, name, precision);
let terms = RicardianContract::new(description);
let terms = RicardianContract::from_str(description).expect("invalid terms");
let contract_data = ContractData { terms, media: None };
let created = Timestamp::default();
// Issuer State
let seal = ExplicitSeal::<Txid>::from_str(seal).expect("invalid seal definition");
Expand All @@ -131,9 +125,11 @@ fn issue_fungible_asset(
.expect("invalid spec")
.add_global_state("created", created)
.expect("invalid created")
.add_global_state("terms", terms)
.add_global_state("data", contract_data)
.expect("invalid contract text")
.add_fungible_state("beneficiary", seal, supply)
.add_global_state("issuedSupply", Amount::from(supply))
.expect("invalid issued supply")
.add_fungible_state("assetOwner", seal, supply)
.expect("invalid asset amount")
.issue_contract()
.expect("contract doesn't fit schema requirements");
Expand Down Expand Up @@ -161,8 +157,11 @@ fn issue_uda_asset(
let description: &'static str = Box::leak(description.to_string().into_boxed_str());
let precision = Precision::try_from(precision).expect("invalid precision");
let spec = DivisibleAssetSpec::new(ticker, name, precision);
let terms = RicardianContract::new(description);
let created = Timestamp::default();
let terms = RicardianContract::from_str(description).expect("invalid terms");
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("invalid");
let created =
Timestamp::from_str(&since_the_epoch.as_secs_f32().to_string()).expect("invalid timestamp");
let fraction = OwnedFraction::from_inner(supply);

let mut tokens_data = vec![];
Expand Down Expand Up @@ -242,7 +241,7 @@ fn issue_uda_asset(

for allocation in allocations {
contract = contract
.add_data_state("beneficiary", seal, allocation)
.add_data_state("assetOwner", seal, allocation)
.expect("invalid asset blob");
}

Expand Down
10 changes: 1 addition & 9 deletions src/rgb/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use std::{collections::HashMap, str::FromStr};

use bitcoin::Address;
use bitcoin_scripts::address::AddressCompat;
use bp::Outpoint;
use rgb::{interface::OutpointFilter, RgbWallet, TerminalPath};
use rgb::{RgbWallet, TerminalPath};

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -40,10 +39,3 @@ pub struct AddressTerminal {
pub address: AddressCompat,
pub terminal: TerminalPath,
}

pub struct EmptyFilter {}
impl OutpointFilter for EmptyFilter {
fn include_outpoint(&self, _outpoint: Outpoint) -> bool {
true
}
}
7 changes: 2 additions & 5 deletions src/rgb/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use std::{
};
use strict_encoding::tn;

use crate::rgb::structs::EmptyFilter;
use crate::rgb::{resolvers::ResolveSpent, structs::AddressTerminal};
use crate::structs::{AllocationDetail, AllocationValue, UDAPosition, WatcherDetail};

Expand Down Expand Up @@ -311,14 +310,13 @@ where
};

sync_wallet(iface_index, wallet, resolver);
let empty = EmptyFilter {};
let mut details = vec![];
for contract_id in stock.contract_ids()? {
let iface = stock.iface_by_name(&tn!(iface_name))?;
if let Ok(contract) = stock.contract_iface(contract_id, iface.iface_id()) {
let mut owners = vec![];
for owned in &contract.iface.assignments {
if let Ok(allocations) = contract.fungible(owned.name.clone(), Some(&empty)) {
if let Ok(allocations) = contract.fungible(owned.name.clone(), &None) {
for allocation in allocations {
let txid = bitcoin::Txid::from_str(&allocation.owner.txid.to_hex())
.expect("invalid txid");
Expand Down Expand Up @@ -400,7 +398,6 @@ pub fn allocations_by_contract<T>(
where
T: ResolveSpent + Resolver,
{
let empty = EmptyFilter {};
let iface_name = match iface_index {
20 => "RGB20",
21 => "RGB21",
Expand All @@ -412,7 +409,7 @@ where
if let Ok(contract) = stock.contract_iface(contract_id, iface.iface_id()) {
sync_wallet(iface_index, wallet, resolver);
for owned in &contract.iface.assignments {
if let Ok(allocations) = contract.fungible(owned.name.clone(), Some(&empty)) {
if let Ok(allocations) = contract.fungible(owned.name.clone(), &None) {
for allocation in allocations {
let txid = bitcoin::Txid::from_str(&allocation.owner.txid.to_hex())
.expect("invalid txid");
Expand Down
1 change: 1 addition & 0 deletions src/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ impl UDAPosition {
pub fn with(uda: AllocationUDA) -> Self {
UDAPosition {
token_index: uda
.clone()
.token_id()
.to_string()
.parse()
Expand Down
Loading