Struct cardano_serialization_lib::MultiAsset
source · pub struct MultiAsset(_);
Implementations§
source§impl MultiAsset
impl MultiAsset
pub fn from_bytes(bytes: Vec<u8>) -> Result<MultiAsset, DeserializeError>
source§impl MultiAsset
impl MultiAsset
pub fn from_hex(hex_str: &str) -> Result<MultiAsset, DeserializeError>
source§impl MultiAsset
impl MultiAsset
source§impl MultiAsset
impl MultiAsset
sourcepub fn new() -> Self
pub fn new() -> Self
Examples found in repository?
src/lib.rs (line 3588)
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
fn as_multiasset(&self, is_positive: bool) -> MultiAsset {
self.0.iter().fold(MultiAsset::new(), |res, e : &(PolicyID, MintAssets) | {
let assets: Assets = (e.1).0.iter().fold(Assets::new(), |res, e| {
let mut assets = res;
if e.1.is_positive() == is_positive {
let amount = match is_positive {
true => e.1.as_positive(),
false => e.1.as_negative(),
};
assets.insert(&e.0, &amount.unwrap());
}
assets
});
let mut ma = res;
if !assets.0.is_empty() {
ma.insert(&e.0, &assets);
}
ma
})
}
More examples
src/tx_builder/batch_tools/asset_categorizer.rs (line 200)
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
pub(crate) fn build_value(&self, used_utxos: &HashSet<UtxoIndex>, tx_output_proposal: &TxOutputProposal)
-> Result<Value, JsError> {
let mut value = Value::new(&tx_output_proposal.total_ada);
if tx_output_proposal.used_assets.is_empty() {
return Ok(value);
}
let mut multiasset = MultiAsset::new();
for (policy_index, assets) in &tx_output_proposal.grouped_assets {
for asset_index in assets {
let mut asset_coins = Coin::zero();
for utxo in used_utxos {
if let Some(coins) = self.assets_amounts[asset_index.0].get(utxo) {
asset_coins = asset_coins.checked_add(coins)?;
}
}
multiasset.set_asset(&self.policies[policy_index.0], &self.assets[asset_index.0].1, asset_coins);
}
}
value.set_multiasset(&multiasset);
Ok(value)
}
src/tx_builder.rs (line 1384)
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
pub fn add_change_if_needed(&mut self, address: &Address) -> Result<bool, JsError> {
let fee = match &self.fee {
None => self.min_fee(),
// generating the change output involves changing the fee
Some(_x) => {
return Err(JsError::from_str(
"Cannot calculate change if fee was explicitly specified",
))
}
}?;
// note: can't add plutus data or data hash and script to change
// because we don't know how many change outputs will need to be created
let plutus_data: Option<DataOption> = None;
let script_ref: Option<ScriptRef> = None;
let input_total = self.get_total_input()?;
let output_total = self.get_total_output()?;
let shortage = get_input_shortage(&input_total, &output_total, &fee)?;
if let Some(shortage) = shortage {
return Err(JsError::from_str(&format!("Insufficient input in transaction. {}", shortage)));
}
use std::cmp::Ordering;
match &input_total.partial_cmp(&output_total.checked_add(&Value::new(&fee))?) {
Some(Ordering::Equal) => {
// recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
self.set_fee(&input_total.checked_sub(&output_total)?.coin());
Ok(false)
}
Some(Ordering::Less) => Err(JsError::from_str("Insufficient input in transaction")),
Some(Ordering::Greater) => {
fn has_assets(ma: Option<MultiAsset>) -> bool {
ma.map(|assets| assets.len() > 0).unwrap_or(false)
}
let change_estimator = input_total.checked_sub(&output_total)?;
if has_assets(change_estimator.multiasset()) {
fn will_adding_asset_make_output_overflow(
output: &TransactionOutput,
current_assets: &Assets,
asset_to_add: (PolicyID, AssetName, BigNum),
max_value_size: u32,
data_cost: &DataCost,
) -> Result<bool, JsError> {
let (policy, asset_name, value) = asset_to_add;
let mut current_assets_clone = current_assets.clone();
current_assets_clone.insert(&asset_name, &value);
let mut amount_clone = output.amount.clone();
let mut val = Value::new(&Coin::zero());
let mut ma = MultiAsset::new();
ma.insert(&policy, ¤t_assets_clone);
val.set_multiasset(&ma);
amount_clone = amount_clone.checked_add(&val)?;
// calculate minADA for more precise max value size
let mut calc = MinOutputAdaCalculator::new_empty(data_cost)?;
calc.set_amount(&val);
let min_ada = calc.calculate_ada()?;
amount_clone.set_coin(&min_ada);
Ok(amount_clone.to_bytes().len() > max_value_size as usize)
}
fn pack_nfts_for_change(
max_value_size: u32,
data_cost: &DataCost,
change_address: &Address,
change_estimator: &Value,
plutus_data: &Option<DataOption>,
script_ref: &Option<ScriptRef>,
) -> Result<Vec<MultiAsset>, JsError> {
// we insert the entire available ADA temporarily here since that could potentially impact the size
// as it could be 1, 2 3 or 4 bytes for Coin.
let mut change_assets: Vec<MultiAsset> = Vec::new();
let mut base_coin = Value::new(&change_estimator.coin());
base_coin.set_multiasset(&MultiAsset::new());
let mut output = TransactionOutput {
address: change_address.clone(),
amount: base_coin.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
};
// If this becomes slow on large TXs we can optimize it like the following
// to avoid cloning + reserializing the entire output.
// This would probably be more relevant if we use a smarter packing algorithm
// which might need to compare more size differences than greedy
//let mut bytes_used = output.to_bytes().len();
// a greedy packing is done here to avoid an exponential bin-packing
// which in most cases likely shouldn't be the difference between
// having an extra change output or not unless there are gigantic
// differences in NFT policy sizes
for (policy, assets) in change_estimator.multiasset().unwrap().0.iter() {
// for simplicity we also don't split assets within a single policy since
// you would need to have a very high amoun of assets (which add 1-36 bytes each)
// in a single policy to make a difference. In the future if this becomes an issue
// we can change that here.
// this is the other part of the optimization but we need to take into account
// the difference between CBOR encoding which can change which happens in two places:
// a) length within assets of one policy id
// b) length of the entire multiasset
// so for simplicity we will just do it the safe, naive way unless
// performance becomes an issue.
//let extra_bytes = policy.to_bytes().len() + assets.to_bytes().len() + 2 + cbor_len_diff;
//if bytes_used + extra_bytes <= max_value_size as usize {
let mut old_amount = output.amount.clone();
let mut val = Value::new(&Coin::zero());
let mut next_nft = MultiAsset::new();
let asset_names = assets.keys();
let mut rebuilt_assets = Assets::new();
for n in 0..asset_names.len() {
let asset_name = asset_names.get(n);
let value = assets.get(&asset_name).unwrap();
if will_adding_asset_make_output_overflow(
&output,
&rebuilt_assets,
(policy.clone(), asset_name.clone(), value),
max_value_size,
data_cost,
)? {
// if we got here, this means we will run into a overflow error,
// so we want to split into multiple outputs, for that we...
// 1. insert the current assets as they are, as this won't overflow
next_nft.insert(policy, &rebuilt_assets);
val.set_multiasset(&next_nft);
output.amount = output.amount.checked_add(&val)?;
change_assets.push(output.amount.multiasset().unwrap());
// 2. create a new output with the base coin value as zero
base_coin = Value::new(&Coin::zero());
base_coin.set_multiasset(&MultiAsset::new());
output = TransactionOutput {
address: change_address.clone(),
amount: base_coin.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
};
// 3. continue building the new output from the asset we stopped
old_amount = output.amount.clone();
val = Value::new(&Coin::zero());
next_nft = MultiAsset::new();
rebuilt_assets = Assets::new();
}
rebuilt_assets.insert(&asset_name, &value);
}
next_nft.insert(policy, &rebuilt_assets);
val.set_multiasset(&next_nft);
output.amount = output.amount.checked_add(&val)?;
// calculate minADA for more precise max value size
let mut amount_clone = output.amount.clone();
let mut calc = MinOutputAdaCalculator::new_empty(data_cost)?;
calc.set_amount(&val);
let min_ada = calc.calculate_ada()?;
amount_clone.set_coin(&min_ada);
if amount_clone.to_bytes().len() > max_value_size as usize {
output.amount = old_amount;
break;
}
}
change_assets.push(output.amount.multiasset().unwrap());
Ok(change_assets)
}
let mut change_left = input_total.checked_sub(&output_total)?;
let mut new_fee = fee.clone();
// we might need multiple change outputs for cases where the change has many asset types
// which surpass the max UTXO size limit
let utxo_cost = self.config.utxo_cost();
let mut calc = MinOutputAdaCalculator::new_empty(&utxo_cost)?;
if let Some(data) = &plutus_data {
match data {
DataOption::DataHash(data_hash) => calc.set_data_hash(data_hash),
DataOption::Data(datum) => calc.set_plutus_data(datum),
};
}
if let Some(script_ref) = &script_ref {
calc.set_script_ref(script_ref);
}
let minimum_utxo_val = calc.calculate_ada()?;
while let Some(Ordering::Greater) = change_left
.multiasset
.as_ref()
.map_or_else(|| None, |ma| ma.partial_cmp(&MultiAsset::new()))
{
let nft_changes = pack_nfts_for_change(
self.config.max_value_size,
&utxo_cost,
address,
&change_left,
&plutus_data.clone(),
&script_ref.clone(),
)?;
if nft_changes.len() == 0 {
// this likely should never happen
return Err(JsError::from_str("NFTs too large for change output"));
}
// we only add the minimum needed (for now) to cover this output
let mut change_value = Value::new(&Coin::zero());
for nft_change in nft_changes.iter() {
change_value.set_multiasset(&nft_change);
let mut calc = MinOutputAdaCalculator::new_empty(&utxo_cost)?;
//TODO add precise calculation
let mut fake_change = change_value.clone();
fake_change.set_coin(&change_left.coin);
calc.set_amount(&fake_change);
if let Some(data) = &plutus_data {
match data {
DataOption::DataHash(data_hash) => {
calc.set_data_hash(data_hash)
}
DataOption::Data(datum) => calc.set_plutus_data(datum),
};
}
if let Some(script_ref) = &script_ref {
calc.set_script_ref(script_ref);
}
let min_ada = calc.calculate_ada()?;
change_value.set_coin(&min_ada);
let change_output = TransactionOutput {
address: address.clone(),
amount: change_value.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
};
// increase fee
let fee_for_change = self.fee_for_output(&change_output)?;
new_fee = new_fee.checked_add(&fee_for_change)?;
if change_left.coin() < min_ada.checked_add(&new_fee)? {
return Err(JsError::from_str("Not enough ADA leftover to include non-ADA assets in a change address"));
}
change_left = change_left.checked_sub(&change_value)?;
self.add_output(&change_output)?;
}
}
change_left = change_left.checked_sub(&Value::new(&new_fee))?;
// add potentially a separate pure ADA change output
let left_above_minimum = change_left.coin.compare(&minimum_utxo_val) > 0;
if self.config.prefer_pure_change && left_above_minimum {
let pure_output = TransactionOutput {
address: address.clone(),
amount: change_left.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
};
let additional_fee = self.fee_for_output(&pure_output)?;
let potential_pure_value =
change_left.checked_sub(&Value::new(&additional_fee))?;
let potential_pure_above_minimum =
potential_pure_value.coin.compare(&minimum_utxo_val) > 0;
if potential_pure_above_minimum {
new_fee = new_fee.checked_add(&additional_fee)?;
change_left = Value::zero();
self.add_output(&TransactionOutput {
address: address.clone(),
amount: potential_pure_value.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
})?;
}
}
self.set_fee(&new_fee);
// add in the rest of the ADA
if !change_left.is_zero() {
self.outputs.0.last_mut().unwrap().amount = self
.outputs
.0
.last()
.unwrap()
.amount
.checked_add(&change_left)?;
}
Ok(true)
} else {
let mut calc = MinOutputAdaCalculator::new_empty(&self.config.utxo_cost())?;
calc.set_amount(&change_estimator);
if let Some(data) = &plutus_data {
match data {
DataOption::DataHash(data_hash) => calc.set_data_hash(data_hash),
DataOption::Data(datum) => calc.set_plutus_data(datum),
};
}
if let Some(script_ref) = &script_ref {
calc.set_script_ref(script_ref);
}
let min_ada = calc.calculate_ada()?;
// no-asset case so we have no problem burning the rest if there is no other option
fn burn_extra(
builder: &mut TransactionBuilder,
burn_amount: &BigNum,
) -> Result<bool, JsError> {
// recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
builder.set_fee(burn_amount);
Ok(false) // not enough input to covert the extra fee from adding an output so we just burn whatever is left
}
match change_estimator.coin() >= min_ada {
false => burn_extra(self, &change_estimator.coin()),
true => {
// check how much the fee would increase if we added a change output
let fee_for_change = self.fee_for_output(&TransactionOutput {
address: address.clone(),
amount: change_estimator.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
})?;
let new_fee = fee.checked_add(&fee_for_change)?;
match change_estimator.coin()
>= min_ada.checked_add(&Value::new(&new_fee).coin())?
{
false => burn_extra(self, &change_estimator.coin()),
true => {
// recall: min_fee assumed the fee was the maximum possible so we definitely have enough input to cover whatever fee it ends up being
self.set_fee(&new_fee);
self.add_output(&TransactionOutput {
address: address.clone(),
amount: change_estimator
.checked_sub(&Value::new(&new_fee.clone()))?,
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
})?;
Ok(true)
}
}
}
}
}
}
None => Err(JsError::from_str(
"missing input or output for some native asset",
)),
}
}
src/utils.rs (line 437)
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
pub fn checked_add(&self, rhs: &Value) -> Result<Value, JsError> {
use std::collections::btree_map::Entry;
let coin = self.coin.checked_add(&rhs.coin)?;
let multiasset = match (&self.multiasset, &rhs.multiasset) {
(Some(lhs_multiasset), Some(rhs_multiasset)) => {
let mut multiasset = MultiAsset::new();
for ma in &[lhs_multiasset, rhs_multiasset] {
for (policy, assets) in &ma.0 {
for (asset_name, amount) in &assets.0 {
match multiasset.0.entry(policy.clone()) {
Entry::Occupied(mut assets) => {
match assets.get_mut().0.entry(asset_name.clone()) {
Entry::Occupied(mut assets) => {
let current = assets.get_mut();
*current = current.checked_add(&amount)?;
}
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(amount.clone());
}
}
}
Entry::Vacant(entry) => {
let mut assets = Assets::new();
assets.0.insert(asset_name.clone(), amount.clone());
entry.insert(assets);
}
}
}
}
}
Some(multiasset)
}
(None, None) => None,
(Some(ma), None) => Some(ma.clone()),
(None, Some(ma)) => Some(ma.clone()),
};
Ok(Value { coin, multiasset })
}
pub fn checked_sub(&self, rhs_value: &Value) -> Result<Value, JsError> {
let coin = self.coin.checked_sub(&rhs_value.coin)?;
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Ok(Value { coin, multiasset })
}
pub fn clamped_sub(&self, rhs_value: &Value) -> Value {
let coin = self.coin.clamped_sub(&rhs_value.coin);
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Value { coin, multiasset }
}
/// note: values are only partially comparable
pub fn compare(&self, rhs_value: &Value) -> Option<i8> {
match self.partial_cmp(&rhs_value) {
None => None,
Some(std::cmp::Ordering::Equal) => Some(0),
Some(std::cmp::Ordering::Less) => Some(-1),
Some(std::cmp::Ordering::Greater) => Some(1),
}
}
}
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
use std::cmp::Ordering::*;
fn compare_assets(
lhs: &Option<MultiAsset>,
rhs: &Option<MultiAsset>,
) -> Option<std::cmp::Ordering> {
match (lhs, rhs) {
(None, None) => Some(Equal),
(None, Some(rhs_assets)) => MultiAsset::new().partial_cmp(&rhs_assets),
(Some(lhs_assets), None) => lhs_assets.partial_cmp(&MultiAsset::new()),
(Some(lhs_assets), Some(rhs_assets)) => lhs_assets.partial_cmp(&rhs_assets),
}
}
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
the number of unique policy IDs in the multiasset
Examples found in repository?
More examples
src/utils.rs (line 411)
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
pub fn is_zero(&self) -> bool {
self.coin.is_zero()
&& self
.multiasset
.as_ref()
.map(|m| m.len() == 0)
.unwrap_or(true)
}
pub fn coin(&self) -> Coin {
self.coin
}
pub fn set_coin(&mut self, coin: &Coin) {
self.coin = coin.clone();
}
pub fn multiasset(&self) -> Option<MultiAsset> {
self.multiasset.clone()
}
pub fn set_multiasset(&mut self, multiasset: &MultiAsset) {
self.multiasset = Some(multiasset.clone());
}
pub fn checked_add(&self, rhs: &Value) -> Result<Value, JsError> {
use std::collections::btree_map::Entry;
let coin = self.coin.checked_add(&rhs.coin)?;
let multiasset = match (&self.multiasset, &rhs.multiasset) {
(Some(lhs_multiasset), Some(rhs_multiasset)) => {
let mut multiasset = MultiAsset::new();
for ma in &[lhs_multiasset, rhs_multiasset] {
for (policy, assets) in &ma.0 {
for (asset_name, amount) in &assets.0 {
match multiasset.0.entry(policy.clone()) {
Entry::Occupied(mut assets) => {
match assets.get_mut().0.entry(asset_name.clone()) {
Entry::Occupied(mut assets) => {
let current = assets.get_mut();
*current = current.checked_add(&amount)?;
}
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(amount.clone());
}
}
}
Entry::Vacant(entry) => {
let mut assets = Assets::new();
assets.0.insert(asset_name.clone(), amount.clone());
entry.insert(assets);
}
}
}
}
}
Some(multiasset)
}
(None, None) => None,
(Some(ma), None) => Some(ma.clone()),
(None, Some(ma)) => Some(ma.clone()),
};
Ok(Value { coin, multiasset })
}
pub fn checked_sub(&self, rhs_value: &Value) -> Result<Value, JsError> {
let coin = self.coin.checked_sub(&rhs_value.coin)?;
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Ok(Value { coin, multiasset })
}
pub fn clamped_sub(&self, rhs_value: &Value) -> Value {
let coin = self.coin.clamped_sub(&rhs_value.coin);
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Value { coin, multiasset }
}
sourcepub fn insert(&mut self, policy_id: &PolicyID, assets: &Assets) -> Option<Assets>
pub fn insert(&mut self, policy_id: &PolicyID, assets: &Assets) -> Option<Assets>
set (and replace if it exists) all assets with policy {policy_id} to a copy of {assets}
Examples found in repository?
src/lib.rs (line 3602)
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
fn as_multiasset(&self, is_positive: bool) -> MultiAsset {
self.0.iter().fold(MultiAsset::new(), |res, e : &(PolicyID, MintAssets) | {
let assets: Assets = (e.1).0.iter().fold(Assets::new(), |res, e| {
let mut assets = res;
if e.1.is_positive() == is_positive {
let amount = match is_positive {
true => e.1.as_positive(),
false => e.1.as_negative(),
};
assets.insert(&e.0, &amount.unwrap());
}
assets
});
let mut ma = res;
if !assets.0.is_empty() {
ma.insert(&e.0, &assets);
}
ma
})
}
More examples
src/tx_builder.rs (line 1386)
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
fn will_adding_asset_make_output_overflow(
output: &TransactionOutput,
current_assets: &Assets,
asset_to_add: (PolicyID, AssetName, BigNum),
max_value_size: u32,
data_cost: &DataCost,
) -> Result<bool, JsError> {
let (policy, asset_name, value) = asset_to_add;
let mut current_assets_clone = current_assets.clone();
current_assets_clone.insert(&asset_name, &value);
let mut amount_clone = output.amount.clone();
let mut val = Value::new(&Coin::zero());
let mut ma = MultiAsset::new();
ma.insert(&policy, ¤t_assets_clone);
val.set_multiasset(&ma);
amount_clone = amount_clone.checked_add(&val)?;
// calculate minADA for more precise max value size
let mut calc = MinOutputAdaCalculator::new_empty(data_cost)?;
calc.set_amount(&val);
let min_ada = calc.calculate_ada()?;
amount_clone.set_coin(&min_ada);
Ok(amount_clone.to_bytes().len() > max_value_size as usize)
}
fn pack_nfts_for_change(
max_value_size: u32,
data_cost: &DataCost,
change_address: &Address,
change_estimator: &Value,
plutus_data: &Option<DataOption>,
script_ref: &Option<ScriptRef>,
) -> Result<Vec<MultiAsset>, JsError> {
// we insert the entire available ADA temporarily here since that could potentially impact the size
// as it could be 1, 2 3 or 4 bytes for Coin.
let mut change_assets: Vec<MultiAsset> = Vec::new();
let mut base_coin = Value::new(&change_estimator.coin());
base_coin.set_multiasset(&MultiAsset::new());
let mut output = TransactionOutput {
address: change_address.clone(),
amount: base_coin.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
};
// If this becomes slow on large TXs we can optimize it like the following
// to avoid cloning + reserializing the entire output.
// This would probably be more relevant if we use a smarter packing algorithm
// which might need to compare more size differences than greedy
//let mut bytes_used = output.to_bytes().len();
// a greedy packing is done here to avoid an exponential bin-packing
// which in most cases likely shouldn't be the difference between
// having an extra change output or not unless there are gigantic
// differences in NFT policy sizes
for (policy, assets) in change_estimator.multiasset().unwrap().0.iter() {
// for simplicity we also don't split assets within a single policy since
// you would need to have a very high amoun of assets (which add 1-36 bytes each)
// in a single policy to make a difference. In the future if this becomes an issue
// we can change that here.
// this is the other part of the optimization but we need to take into account
// the difference between CBOR encoding which can change which happens in two places:
// a) length within assets of one policy id
// b) length of the entire multiasset
// so for simplicity we will just do it the safe, naive way unless
// performance becomes an issue.
//let extra_bytes = policy.to_bytes().len() + assets.to_bytes().len() + 2 + cbor_len_diff;
//if bytes_used + extra_bytes <= max_value_size as usize {
let mut old_amount = output.amount.clone();
let mut val = Value::new(&Coin::zero());
let mut next_nft = MultiAsset::new();
let asset_names = assets.keys();
let mut rebuilt_assets = Assets::new();
for n in 0..asset_names.len() {
let asset_name = asset_names.get(n);
let value = assets.get(&asset_name).unwrap();
if will_adding_asset_make_output_overflow(
&output,
&rebuilt_assets,
(policy.clone(), asset_name.clone(), value),
max_value_size,
data_cost,
)? {
// if we got here, this means we will run into a overflow error,
// so we want to split into multiple outputs, for that we...
// 1. insert the current assets as they are, as this won't overflow
next_nft.insert(policy, &rebuilt_assets);
val.set_multiasset(&next_nft);
output.amount = output.amount.checked_add(&val)?;
change_assets.push(output.amount.multiasset().unwrap());
// 2. create a new output with the base coin value as zero
base_coin = Value::new(&Coin::zero());
base_coin.set_multiasset(&MultiAsset::new());
output = TransactionOutput {
address: change_address.clone(),
amount: base_coin.clone(),
plutus_data: plutus_data.clone(),
script_ref: script_ref.clone(),
};
// 3. continue building the new output from the asset we stopped
old_amount = output.amount.clone();
val = Value::new(&Coin::zero());
next_nft = MultiAsset::new();
rebuilt_assets = Assets::new();
}
rebuilt_assets.insert(&asset_name, &value);
}
next_nft.insert(policy, &rebuilt_assets);
val.set_multiasset(&next_nft);
output.amount = output.amount.checked_add(&val)?;
// calculate minADA for more precise max value size
let mut amount_clone = output.amount.clone();
let mut calc = MinOutputAdaCalculator::new_empty(data_cost)?;
calc.set_amount(&val);
let min_ada = calc.calculate_ada()?;
amount_clone.set_coin(&min_ada);
if amount_clone.to_bytes().len() > max_value_size as usize {
output.amount = old_amount;
break;
}
}
change_assets.push(output.amount.multiasset().unwrap());
Ok(change_assets)
}
sourcepub fn get(&self, policy_id: &PolicyID) -> Option<Assets>
pub fn get(&self, policy_id: &PolicyID) -> Option<Assets>
all assets under {policy_id}, if any exist, or else None (undefined in JS)
Examples found in repository?
More examples
src/tx_builder.rs (line 461)
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
pub fn add_inputs_from(
&mut self,
inputs: &TransactionUnspentOutputs,
strategy: CoinSelectionStrategyCIP2,
) -> Result<(), JsError> {
let available_inputs = &inputs.0.clone();
let mut input_total = self.get_total_input()?;
let mut output_total = self
.get_total_output()?
.checked_add(&Value::new(&self.min_fee()?))?;
match strategy {
CoinSelectionStrategyCIP2::LargestFirst => {
if self
.outputs
.0
.iter()
.any(|output| output.amount.multiasset.is_some())
{
return Err(JsError::from_str("Multiasset values not supported by LargestFirst. Please use LargestFirstMultiAsset"));
}
self.cip2_largest_first_by(
available_inputs,
&mut (0..available_inputs.len()).collect(),
&mut input_total,
&mut output_total,
|value| Some(value.coin),
)?;
}
CoinSelectionStrategyCIP2::RandomImprove => {
if self
.outputs
.0
.iter()
.any(|output| output.amount.multiasset.is_some())
{
return Err(JsError::from_str("Multiasset values not supported by RandomImprove. Please use RandomImproveMultiAsset"));
}
use rand::Rng;
let mut rng = rand::thread_rng();
let mut available_indices =
(0..available_inputs.len()).collect::<BTreeSet<usize>>();
self.cip2_random_improve_by(
available_inputs,
&mut available_indices,
&mut input_total,
&mut output_total,
|value| Some(value.coin),
&mut rng,
true,
)?;
// Phase 3: add extra inputs needed for fees (not covered by CIP-2)
// We do this at the end because this new inputs won't be associated with
// a specific output, so the improvement algorithm we do above does not apply here.
while input_total.coin < output_total.coin {
if available_indices.is_empty() {
return Err(JsError::from_str("UTxO Balance Insufficient[x]"));
}
let i = *available_indices
.iter()
.nth(rng.gen_range(0..available_indices.len()))
.unwrap();
available_indices.remove(&i);
let input = &available_inputs[i];
let input_fee = self.fee_for_input(
&input.output.address,
&input.input,
&input.output.amount,
)?;
self.add_input(&input.output.address, &input.input, &input.output.amount);
input_total = input_total.checked_add(&input.output.amount)?;
output_total = output_total.checked_add(&Value::new(&input_fee))?;
}
}
CoinSelectionStrategyCIP2::LargestFirstMultiAsset => {
// indices into {available_inputs} for inputs that contain {policy_id}:{asset_name}
let mut available_indices = (0..available_inputs.len()).collect::<Vec<usize>>();
// run largest-fist by each asset type
if let Some(ma) = output_total.multiasset.clone() {
for (policy_id, assets) in ma.0.iter() {
for (asset_name, _) in assets.0.iter() {
self.cip2_largest_first_by(
available_inputs,
&mut available_indices,
&mut input_total,
&mut output_total,
|value| value.multiasset.as_ref()?.get(policy_id)?.get(asset_name),
)?;
}
}
}
// add in remaining ADA
self.cip2_largest_first_by(
available_inputs,
&mut available_indices,
&mut input_total,
&mut output_total,
|value| Some(value.coin),
)?;
}
CoinSelectionStrategyCIP2::RandomImproveMultiAsset => {
use rand::Rng;
let mut rng = rand::thread_rng();
let mut available_indices =
(0..available_inputs.len()).collect::<BTreeSet<usize>>();
// run random-improve by each asset type
if let Some(ma) = output_total.multiasset.clone() {
for (policy_id, assets) in ma.0.iter() {
for (asset_name, _) in assets.0.iter() {
self.cip2_random_improve_by(
available_inputs,
&mut available_indices,
&mut input_total,
&mut output_total,
|value| value.multiasset.as_ref()?.get(policy_id)?.get(asset_name),
&mut rng,
false,
)?;
}
}
}
// add in remaining ADA
self.cip2_random_improve_by(
available_inputs,
&mut available_indices,
&mut input_total,
&mut output_total,
|value| Some(value.coin),
&mut rng,
false,
)?;
// Phase 3: add extra inputs needed for fees (not covered by CIP-2)
// We do this at the end because this new inputs won't be associated with
// a specific output, so the improvement algorithm we do above does not apply here.
while input_total.coin < output_total.coin {
if available_indices.is_empty() {
return Err(JsError::from_str("UTxO Balance Insufficient[x]"));
}
let i = *available_indices
.iter()
.nth(rng.gen_range(0..available_indices.len()))
.unwrap();
available_indices.remove(&i);
let input = &available_inputs[i];
let input_fee = self.fee_for_input(
&input.output.address,
&input.input,
&input.output.amount,
)?;
self.add_input(&input.output.address, &input.input, &input.output.amount);
input_total = input_total.checked_add(&input.output.amount)?;
output_total = output_total.checked_add(&Value::new(&input_fee))?;
}
}
}
Ok(())
}
sourcepub fn set_asset(
&mut self,
policy_id: &PolicyID,
asset_name: &AssetName,
value: BigNum
) -> Option<BigNum>
pub fn set_asset(
&mut self,
policy_id: &PolicyID,
asset_name: &AssetName,
value: BigNum
) -> Option<BigNum>
sets the asset {asset_name} to {value} under policy {policy_id} returns the previous amount if it was set, or else None (undefined in JS)
Examples found in repository?
src/tx_builder/batch_tools/asset_categorizer.rs (line 209)
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
pub(crate) fn build_value(&self, used_utxos: &HashSet<UtxoIndex>, tx_output_proposal: &TxOutputProposal)
-> Result<Value, JsError> {
let mut value = Value::new(&tx_output_proposal.total_ada);
if tx_output_proposal.used_assets.is_empty() {
return Ok(value);
}
let mut multiasset = MultiAsset::new();
for (policy_index, assets) in &tx_output_proposal.grouped_assets {
for asset_index in assets {
let mut asset_coins = Coin::zero();
for utxo in used_utxos {
if let Some(coins) = self.assets_amounts[asset_index.0].get(utxo) {
asset_coins = asset_coins.checked_add(coins)?;
}
}
multiasset.set_asset(&self.policies[policy_index.0], &self.assets[asset_index.0].1, asset_coins);
}
}
value.set_multiasset(&multiasset);
Ok(value)
}
sourcepub fn get_asset(&self, policy_id: &PolicyID, asset_name: &AssetName) -> BigNum
pub fn get_asset(&self, policy_id: &PolicyID, asset_name: &AssetName) -> BigNum
returns the amount of asset {asset_name} under policy {policy_id} If such an asset does not exist, 0 is returned.
Examples found in repository?
src/utils.rs (line 1684)
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
pub(crate) fn get_input_shortage(all_inputs_value: &Value, all_outputs_value: &Value, fee: &Coin)
-> Result<Option<ValueShortage>, JsError> {
let mut shortage = ValueShortage{
ada_shortage: None,
asset_shortage: Vec::new()};
if all_inputs_value.coin < all_outputs_value.coin.checked_add(fee)? {
shortage.ada_shortage = Some((
all_inputs_value.coin.clone(),
all_outputs_value.coin.clone(),
fee.clone()));
}
if let Some(policies) = &all_outputs_value.multiasset {
for (policy_id, assets) in &policies.0 {
for (asset_name, coins) in &assets.0 {
let inputs_coins = match &all_inputs_value.multiasset {
Some(multiasset) => multiasset.get_asset(policy_id, asset_name),
None => Coin::zero()
};
if inputs_coins < *coins {
shortage.asset_shortage.push((policy_id.clone(), asset_name.clone(), inputs_coins, coins.clone()));
}
}
}
}
if shortage.ada_shortage.is_some() || shortage.asset_shortage.len() > 0 {
Ok(Some(shortage))
} else {
Ok(None)
}
}
sourcepub fn sub(&self, rhs_ma: &MultiAsset) -> MultiAsset
pub fn sub(&self, rhs_ma: &MultiAsset) -> MultiAsset
removes an asset from the list if the result is 0 or less does not modify this object, instead the result is returned
Examples found in repository?
src/utils.rs (line 477)
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
pub fn checked_sub(&self, rhs_value: &Value) -> Result<Value, JsError> {
let coin = self.coin.checked_sub(&rhs_value.coin)?;
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Ok(Value { coin, multiasset })
}
pub fn clamped_sub(&self, rhs_value: &Value) -> Value {
let coin = self.coin.clamped_sub(&rhs_value.coin);
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Value { coin, multiasset }
}
Trait Implementations§
source§impl Clone for MultiAsset
impl Clone for MultiAsset
source§fn clone(&self) -> MultiAsset
fn clone(&self) -> MultiAsset
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for MultiAsset
impl Debug for MultiAsset
source§impl<'de> Deserialize<'de> for MultiAsset
impl<'de> Deserialize<'de> for MultiAsset
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Deserialize for MultiAsset
impl Deserialize for MultiAsset
fn deserialize<R: BufRead + Seek>(
raw: &mut Deserializer<R>
) -> Result<Self, DeserializeError>
source§impl JsonSchema for MultiAsset
impl JsonSchema for MultiAsset
source§fn schema_name() -> String
fn schema_name() -> String
The name of the generated JSON Schema. Read more
source§fn json_schema(gen: &mut SchemaGenerator) -> Schema
fn json_schema(gen: &mut SchemaGenerator) -> Schema
Generates a JSON Schema for this type. Read more
source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
Whether JSON Schemas generated for this type should be re-used where possible using the
$ref
keyword. Read moresource§impl Ord for MultiAsset
impl Ord for MultiAsset
source§fn cmp(&self, other: &MultiAsset) -> Ordering
fn cmp(&self, other: &MultiAsset) -> Ordering
1.21.0 · source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read more
source§impl PartialEq<MultiAsset> for MultiAsset
impl PartialEq<MultiAsset> for MultiAsset
source§fn eq(&self, other: &MultiAsset) -> bool
fn eq(&self, other: &MultiAsset) -> bool
This method tests for
self
and other
values to be equal, and is used
by ==
.source§impl PartialOrd<MultiAsset> for MultiAsset
impl PartialOrd<MultiAsset> for MultiAsset
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read more