Skip to content

Commit

Permalink
chore: renamed plus and minus to add and subtract, added utility meth…
Browse files Browse the repository at this point in the history
…ods (#457)

* Add support for Optional types in blueprint processing (#451)

* Add support for Optional types in blueprint processing

Implemented changes to handle Optional types in blueprint definitions. Added tests for processing blueprints with basic option types and ensured proper compilation. Updated schema and processing utilities to accommodate new Optional type handling.

* Add Pair type support and serialization logic

Added the Pair type to Type and JavaType enums. Updated BlueprintSchema, ConverterCodeGenerator, and ClassDefinitionGenerator to handle Pair serialization and deserialization. Introduced unit tests to verify Pair functionality.

* Fix package issue due to aiken stdlib definitions

* To fix #452 Add tests for ScheduledTransactionRedeemer model and related tests

* feat: support hash param on CIP-30.

* Refactor COSESign builders for external payload and hashing

Refactor `COSESignBuilder` and `COSESign1Builder` to handle external payloads and add support for payload hashing. Update `CIP30DataSigner` logic to remove redundant hashed payload header. Adjust tests to align with these changes and add new test files for Rust code comparisons.

* chore: renamed plus and minus to add and subtract, added utility methods

* chore: added random . to cover for unit sanitization

* chore: removed check on asset name, re-used AssetUtil and moved up in dependency hierarchy

* chore: added tests

* chore: fixed assets and multi assets removal in case of a non modifiable list

* chore: one last fix

* refactor: Revert AssetUtil package move to avoid breaking change (#468)

* chore: Refactor asset name handling and update Value methods

* To fix SonarQube error. Deprecate old methods in `MultiAsset`, `Asset`, `Value`

Add deprecation annotations with versioning to methods in `MultiAsset`, `Asset`, and `Value` classes, pointing to their new equivalents. Also, convert JUnit 5 test methods to package-private scope.

---------

Co-authored-by: Satya <35016438+satran004@users.noreply.github.com>
Co-authored-by: Mateusz Czeladka <mateusz.szczap@gmail.com>
Co-authored-by: Satya <satran004@gmail.com>
  • Loading branch information
4 people authored Nov 25, 2024
1 parent 436b396 commit 6131dce
Show file tree
Hide file tree
Showing 18 changed files with 564 additions and 118 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ void testMintingTwoNFTs_withSamePolicy() throws Exception {
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down Expand Up @@ -337,7 +337,7 @@ void testMintingTwoNFTs_withSamePolicyAndAssetName_differentReceivers() throws E
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down Expand Up @@ -450,7 +450,7 @@ void testMintingTwoNFTs_withSamePolicyAndAssetName_differentReceivers_withOutput
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ private static OutputAmount applyUtxoToChangeAmount(OutputAmount outputAmount, S
if(matchingAsset.isPresent()){
// update matchingAsset
assetAmountsForPolicy.remove(matchingAsset.get());
assetAmountsForPolicy.add(matchingAsset.get().plus(toAsset(utxoAmt)));
assetAmountsForPolicy.add(matchingAsset.get().add(toAsset(utxoAmt)));
}else{
// add new asset to matchingMultiAsset
assetAmountsForPolicy.add(new Asset(policyIdAssetName._2, utxoQty));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ default TxBuilder buildInputs(TxInputBuilder after, boolean mergeChangeOutput) {
.filter(transactionOutput -> transactionOutput.getAddress().equals(txOutput.getAddress()))
.findFirst().orElse(null);
if (txOutputSameAddress != null) {
txOutputSameAddress.setValue(txOutputSameAddress.getValue().plus(txOutput.getValue()));
txOutputSameAddress.setValue(txOutputSameAddress.getValue().add(txOutput.getValue()));
} else {
transaction.getBody().getOutputs().add(txOutput);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ private static void adjust(TxBuilderContext context, Transaction transaction, Tr
//Let's make fee to a default one and add the existing fee to changeoutput
BigInteger existingFee = transaction.getBody().getFee();
Value changeOutputValue = outputToAdjust.getValue();
changeOutputValue = changeOutputValue.plus(Value.builder().coin(existingFee).build());
changeOutputValue = changeOutputValue.add(Value.builder().coin(existingFee).build());
outputToAdjust.setValue(changeOutputValue);
transaction.getBody().setFee(DEFAULT_FEE); //Just a dummy fee for now

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,19 @@ public static TxInputBuilder createFromSender(String sender, String changeAddres
Value value = Value.builder().coin(BigInteger.ZERO).multiAssets(new ArrayList<>()).build();
value = outputs.stream()
.map(output -> output.getValue())
.reduce(value, (value1, value2) -> value1.plus(value2));
.reduce(value, (value1, value2) -> value1.add(value2));

//Check if mint value is there in context. Then we need to ignore mint outputs from total value
List<MultiAsset> mintMultiAssets = context.getMintMultiAssets();
Optional<Value> mintValue = findMintValueFromMultiAssets(mintMultiAssets);
if (mintValue.isPresent()) {
value = value.minus(mintValue.get());
value = value.subtract(mintValue.get());
}

//check if there is any burn multiasset value
Optional<Value> burnValue = findBurnValueFromMultiAssets(mintMultiAssets);
if (burnValue.isPresent()) {
value = value.plus(burnValue.get());
value = value.add(burnValue.get());
}

Set<Utxo> utxoSet = getUtxosForValue(context, sender, value, Collections.EMPTY_SET);
Expand All @@ -84,7 +84,7 @@ public static TxInputBuilder createFromSender(String sender, String changeAddres
});

//Substract output values from change
Value changedValue = changeOutput.getValue().minus(value);
Value changedValue = changeOutput.getValue().subtract(value);
changeOutput.setValue(changedValue);
BigInteger additionalLovelace = MinAdaCheckers.minAdaChecker().apply(context, changeOutput);

Expand Down Expand Up @@ -260,19 +260,19 @@ public static TxInputBuilder createFromUtxos(Supplier<List<Utxo>> supplier, Stri
Value value = Value.builder().coin(BigInteger.ZERO).multiAssets(new ArrayList<>()).build();
value = outputs.stream()
.map(TransactionOutput::getValue)
.reduce(value, Value::plus);
.reduce(value, Value::add);

//Check if mint value is there in context. Then we need to ignore mint outputs from total value
List<MultiAsset> mintMultiAssets = context.getMintMultiAssets();
Optional<Value> mintValue = findMintValueFromMultiAssets(mintMultiAssets);
if (mintValue.isPresent()) {
value = value.minus(mintValue.get());
value = value.subtract(mintValue.get());
}

//check if there is any burn multiasset value
Optional<Value> burnValue = findBurnValueFromMultiAssets(mintMultiAssets);
if (burnValue.isPresent()) {
value = value.plus(burnValue.get());
value = value.add(burnValue.get());
}

List<Utxo> utxos = supplier.get();
Expand All @@ -293,7 +293,7 @@ public static TxInputBuilder createFromUtxos(Supplier<List<Utxo>> supplier, Stri
});

//Subtract output values from change
Value changedValue = changeOutput.getValue().minus(value);
Value changedValue = changeOutput.getValue().subtract(value);
changeOutput.setValue(changedValue);

if (datumHash != null && !datumHash.isEmpty())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public static TxOutputBuilder createFromOutput(TransactionOutput txnOutput, bool
outputs.stream().filter(to -> address.equals(to.getAddress()))
.findFirst()
.ifPresentOrElse(to -> {
Value newValue = to.getValue().plus(value);
Value newValue = to.getValue().add(value);
to.setValue(newValue);
copyDatumAndScriptRef(txnOutput, to);

Expand Down Expand Up @@ -153,7 +153,7 @@ private static void handleMultiAssetOutput(Output output, MinAdaChecker minAdaCh
outputs.stream().filter(to -> output.getAddress().equals(to.getAddress()))
.findFirst()
.ifPresentOrElse(to -> {
Value newValue = to.getValue().plus(new Value(BigInteger.ZERO, List.of(multiAsset)));
Value newValue = to.getValue().add(new Value(BigInteger.ZERO, List.of(multiAsset)));
to.setValue(newValue);
copyDatumAndScriptRef(output, to);

Expand Down Expand Up @@ -244,7 +244,7 @@ private static void checkIfMinAdaIsThere(TxBuilderContext tc, TransactionOutput

if (additionalLovelace != null && additionalLovelace.compareTo(BigInteger.ZERO) == 1) {
Value orginalValue = output.getValue();
Value newValue = orginalValue.plus(Value.builder().coin(additionalLovelace).build());
Value newValue = orginalValue.add(Value.builder().coin(additionalLovelace).build());

output.setValue(newValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static TxBuilder mergeOutputsForAddress(String address) {
return;

Optional<Value> totalValue = addressOutputs.stream().map(output -> output.getValue())
.reduce((value1, value2) -> value1.plus(value2));
.reduce((value1, value2) -> value1.add(value2));

TransactionOutput newOutput = new TransactionOutput(address, totalValue.get());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ public static TxBuilder balanceTx(String feePayer, int additionalSigners, boolea
transaction.getBody().getOutputs().stream()
.filter(output -> feePayer.equals(output.getAddress()))
.max((to1, to2) -> to1.getValue().getCoin().compareTo(to2.getValue().getCoin()))
.ifPresent(transactionOutput -> transactionOutput.setValue(transactionOutput.getValue().plus(Value.builder().coin(fee).build())));
.ifPresent(transactionOutput -> transactionOutput.setValue(transactionOutput.getValue().add(Value.builder().coin(fee).build())));

Value newCollateralReturnValue = transaction.getBody().getCollateralReturn()
.getValue().plus(Value.builder().coin(transaction.getBody().getTotalCollateral()).build());
.getValue().add(Value.builder().coin(transaction.getBody().getTotalCollateral()).build());
transaction.getBody().getCollateralReturn().setValue(newCollateralReturnValue);
transaction.getBody().setTotalCollateral(BigInteger.valueOf(1000000)); //reset total collateral. some dummy value

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ void createFromUtxos() throws Exception {

//These two have same policy id
AssetUtil.getMultiAssetFromUnitAndAmount("329728f73683fe04364631c27a7912538c116d802416ca1eaf2d7a96736174636f696e", BigInteger.valueOf(7500))
.plus(AssetUtil.getMultiAssetFromUnitAndAmount("329728f73683fe04364631c27a7912538c116d802416ca1eaf2d7a96926174636f766e", BigInteger.valueOf(8000)))
.add(AssetUtil.getMultiAssetFromUnitAndAmount("329728f73683fe04364631c27a7912538c116d802416ca1eaf2d7a96926174636f766e", BigInteger.valueOf(8000)))
)
)
.build())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@

import static com.bloxbean.cardano.client.common.ADAConversionUtil.adaToLovelace;
import static com.bloxbean.cardano.client.common.CardanoConstants.LOVELACE;
import static com.bloxbean.cardano.client.transaction.util.CostModelUtil.PlutusV1CostModel;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ContractTransactionIT extends BaseITTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ void testMintingTwoNFTs_withSamePolicy() throws Exception {
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down Expand Up @@ -364,7 +364,7 @@ void testMintingTwoNFTs_withSamePolicyAndAssetName_differentReceivers() throws E
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down Expand Up @@ -473,7 +473,7 @@ void testMintingTwoNFTs_withSamePolicyAndAssetName_differentReceivers_withOutput
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down Expand Up @@ -638,7 +638,7 @@ void testPayments_whenMergeOutputTrue() throws Exception {
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down Expand Up @@ -756,7 +756,7 @@ void testPayments_whenMergeOutputFalse() throws Exception {
.assetName(LOVELACE)
.qty(adaToLovelace(4)).build();

MultiAsset mergeMultiAsset = multiAsset1.plus(multiAsset2);
MultiAsset mergeMultiAsset = multiAsset1.add(multiAsset2);

//Create TxBuilder function
TxBuilder txBuilder =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ protected T payToAddress(String address, List<Amount> amounts, byte[] datumHash,
Tuple<String, String> policyAssetName = AssetUtil.getPolicyIdAndAssetName(unit);
Asset asset = new Asset(policyAssetName._2, amount.getQuantity());
MultiAsset multiAsset = new MultiAsset(policyAssetName._1, List.of(asset));
Value newValue = transactionOutput.getValue().plus(new Value(BigInteger.ZERO, List.of(multiAsset)));
Value newValue = transactionOutput.getValue().add(new Value(BigInteger.ZERO, List.of(multiAsset)));
transactionOutput.setValue(newValue);
}
}
Expand Down Expand Up @@ -453,7 +453,7 @@ protected void addToMultiAssetList(@NonNull Script script, List<Asset> assets) {
}
}).findFirst().ifPresentOrElse(ma -> {
multiAssets.remove(ma);
multiAssets.add(new Tuple<>(script, ma._2.plus(multiAsset)));
multiAssets.add(new Tuple<>(script, ma._2.add(multiAsset)));
}, () -> {
multiAssets.add(new Tuple<>(script, multiAsset));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,7 @@ public class Asset {

@JsonIgnore
public byte[] getNameAsBytes() {
byte[] assetNameBytes = null;
if (name != null && !name.isEmpty()) {
//Check if caller has provided a hex string as asset name
if (name.startsWith("0x")) {
try {
assetNameBytes = HexUtil.decodeHexString(name.substring(2));
} catch (IllegalArgumentException e) {
// name is not actually a hex string
assetNameBytes = name.getBytes(StandardCharsets.UTF_8);
}
} else {
assetNameBytes = name.getBytes(StandardCharsets.UTF_8);
}
} else {
assetNameBytes = new byte[0];
}
return assetNameBytes;
return nameToBytes(name);
}

/**
Expand Down Expand Up @@ -71,25 +55,60 @@ public String toString() {
* @param that
* @return a new Asset as sum of this value and the one passed as parameter
*/
public Asset plus(Asset that) {
public Asset add(Asset that) {
if (!Arrays.equals(getNameAsBytes(), that.getNameAsBytes())) {
throw new IllegalArgumentException("Trying to add Assets with different name");
}
return Asset.builder().name(getNameAsHex()).value(getValue().add(that.getValue())).build();
}

/**
* Returns a new asset that is the sum of this asset and the provided asset.
*
* @deprecated
* <p>Use {@link #add(Asset)} instead</p>
*
* @param that the asset to be added to this asset
* @return a new Asset representing the sum of this asset and the provided asset
*/
@Deprecated(since = "0.6.3")
public Asset plus(Asset that) {
return this.add(that);
}

/**
* returns a new asset that is a subtraction of this and that (asset passed as parameter)
* @param that
* @return a new Asset as subtract of this value and the one passed as parameter
*/
public Asset minus(Asset that) {
public Asset subtract(Asset that) {
if (!Arrays.equals(getNameAsBytes(), that.getNameAsBytes())) {
throw new IllegalArgumentException("Trying to add Assets with different name");
}
return Asset.builder().name(getName()).value(getValue().subtract(that.getValue())).build();
}

/**
* Returns a new asset that is a subtraction of this asset and the provided asset.
* @deprecated
* <p>Use {@link #subtract(Asset)} instead</p>
*
* @param that the asset to be subtracted from this asset
* @return a new Asset representing the difference between this asset and the provided asset
*/
@Deprecated(since = "0.6.3")
public Asset minus(Asset that) {
return this.subtract(that);
}

public boolean hasName(String assetName) {
byte[] assetNameBytes = nameToBytes(assetName);
byte[] existingAssetNameBytes = nameToBytes(name);

//check if both byte array are same
return Arrays.equals(assetNameBytes, existingAssetNameBytes);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
Expand All @@ -102,4 +121,24 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(Arrays.hashCode(getNameAsBytes()), value);
}

private static byte[] nameToBytes(String assetName) {
byte[] assetNameBytes = null;
if (assetName != null && !assetName.isEmpty()) {
//Check if caller has provided a hex string as asset name
if (assetName.startsWith("0x")) {
try {
assetNameBytes = HexUtil.decodeHexString(assetName.substring(2));
} catch (IllegalArgumentException e) {
// name is not actually a hex string
assetNameBytes = assetName.getBytes(StandardCharsets.UTF_8);
}
} else {
assetNameBytes = assetName.getBytes(StandardCharsets.UTF_8);
}
} else {
assetNameBytes = new byte[0];
}
return assetNameBytes;
}
}
Loading

0 comments on commit 6131dce

Please sign in to comment.