Merge pull request #582 from input-output-hk/feat/ADP-2534-replace-current-fee-calculation
Feat/adp 2534 replace current fee calculation
Feat/adp 2534 replace current fee calculation
export * from './RoundRobinRandomImprove';
export * from './selectionConstraints';
export * from './types';
export * from './InputSelectionError';
export type ProtocolParametersForInputSelection = Pick<
Cardano.ProtocolParameters,
'coinsPerUtxoByte' | 'maxTxSize' | 'maxValueSize' | 'minFeeCoefficient' | 'minFeeConstant'
'coinsPerUtxoByte' | 'maxTxSize' | 'maxValueSize' | 'minFeeCoefficient' | 'minFeeConstant' | 'prices'
>;
export type ProtocolParametersRequiredByInputSelection = Required<{
node_modules
dist
secrets
coverage
\ No newline at end of file
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright © 2023 IOHK
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Copyright 2023 IOHK
Licensed under the Apache License, Version 2.0 (the "License”). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
\ No newline at end of file
# Cardano JS SDK | Tx Construction
This package provides a set of high level primitives or constructing transactions on the Cardano blockchain.
module.exports = require('../../test/jest.config');
\ No newline at end of file
{
"name": "@cardano-sdk/tx-construction",
"version": "0.1.0",
"description": "Types and functions for constructing transactions on Cardano",
"engines": {
"node": ">=14.20.1"
},
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js"
}
},
"repository": "https://github.com/input-output-hk/cardano-js-sdk",
"publishConfig": {
"access": "public"
},
"sideEffects": false,
"contributors": [
"Rhys Bartels-Waller <[email protected]> (https://iohk.io)",
"Martynas Kazlauskas <[email protected]> (https://iohk.io)",
"Daniele Ricci <[email protected]> (https://iohk.io)",
"Ivaylo Andonov <[email protected]> (https://iohk.io)",
"Mircea Hasegan <[email protected]> (https://iohk.io)",
"Angel Castillo Bacigalupi <[email protected]> (https://iohk.io)",
"Dmytro Iakymenko <[email protected]> (https://iohk.io)"
],
"license": "Apache-2.0",
"scripts": {
"build:esm": "tsc -p src/tsconfig.json --outDir ./dist/esm --module es2020",
"build:cjs": "tsc --build src",
"build": "run-s build:cjs build:esm module-fixup",
"circular-deps:check": "madge --circular dist",
"module-fixup": "shx cp ../../build/cjs-package.json ./dist/cjs/package.json && cp ../../build/esm-package.json ./dist/esm/package.json",
"tscNoEmit": "shx echo typescript --noEmit command not implemented yet",
"cleanup:dist": "shx rm -rf dist",
"cleanup:nm": "shx rm -rf node_modules",
"cleanup": "run-s cleanup:dist cleanup:nm",
"lint": "eslint -c ../../complete.eslintrc.js \"src/**/*.ts\" \"test/**/*.ts\"",
"lint:fix": "yarn lint --fix",
"test": "jest -c ./jest.config.js",
"test:build:verify": "tsc --build ./test",
"test:e2e": "shx echo 'test:e2e' command not implemented yet",
"coverage": "shx echo No coverage report for this package",
"prepack": "yarn build"
},
"devDependencies": {
"@cardano-sdk/crypto": "^0.1.0",
"@cardano-sdk/util-dev": "^0.6.0",
"@types/lodash": "^4.14.182",
"eslint": "^7.32.0",
"jest": "^28.1.3",
"madge": "^5.0.1",
"npm-run-all": "^4.1.5",
"shx": "^0.3.3",
"ts-jest": "^28.0.7",
"typescript": "^4.7.4"
},
"dependencies": {
"@cardano-sdk/core": "^0.7.0",
"@cardano-sdk/input-selection": "^0.7.0",
"@cardano-sdk/util": "^0.7.0",
"lodash": "^4.17.21",
"npm": "^9.3.0",
"ts-custom-error": "^3.2.0",
"ts-log": "^2.2.4"
},
"files": [
"dist/*",
"!dist/tsconfig.tsbuildinfo",
"LICENSE",
"NOTICE"
]
}
import { CML, Cardano, coreToCml } from '@cardano-sdk/core';
import { OpaqueNumber, usingAutoFree } from '@cardano-sdk/util';
/**
* The constant overhead of 160 bytes accounts for the transaction input and the entry in the UTxO map data
* structure (20 words * 8 bytes).
*/
const MIN_ADA_CONSTANT_OVERHEAD = 160;
// TODO: Remove this serialization function once CBOR serialization has been added to the SDK.
/**
* Serializes the given BigInt to CBOR format.
*
* @param bigInt The BigInt to be serialized.
*/
const serializeBigInt = (bigInt: string) =>
usingAutoFree((scope) => scope.manage(CML.BigNum.from_str(bigInt)).to_bytes());
// TODO: Remove this serialization function once CBOR serialization has been added to the SDK.
/**
* Serializes the given Tx Output to CBOR format.
*
* @param output The Tx Output to be serialized.
*/
const serializeTxOutput = (output: Cardano.TxOut) =>
usingAutoFree((scope) => coreToCml.txOut(scope, output).to_bytes());
// TODO: Remove this serialization function once CBOR serialization has been added to the SDK.
/**
* Serializes the given Tx to CBOR format.
*
* @param tx The Tx to be serialized.
*/
const serializeTx = (tx: Cardano.Tx) => usingAutoFree((scope) => coreToCml.tx(scope, tx).to_bytes());
/**
* Gets the total transaction execution units budget from the redeemers.
*
* @param redeemers The transaction redeemer.
*/
const getTotalExUnits = (redeemers: Cardano.Redeemer[]): Cardano.ExUnits => {
const totalExUnits: Cardano.ExUnits = { memory: 0, steps: 0 };
for (const redeemer of redeemers) {
totalExUnits.memory += redeemer.executionUnits.memory;
totalExUnits.steps += redeemer.executionUnits.steps;
}
return totalExUnits;
};
/**
* Gets the minimum fee incurred by the scripts on the transaction.
*
* @param tx The transaction to compute the min script fee from.
* @param exUnitsPrice The prices of the execution units.
*/
const minScriptFee = (tx: Cardano.Tx, exUnitsPrice: Cardano.Prices): bigint => {
if (!tx.witness.redeemers) return BigInt(0);
const totalExUnits = getTotalExUnits(tx.witness.redeemers);
return BigInt(Math.ceil(totalExUnits.steps * exUnitsPrice.steps + totalExUnits.memory * exUnitsPrice.memory));
};
/**
* The value of the min fee constant is a payable fee, regardless of the size of the transaction. This parameter was
* primarily introduced to prevent Distributed-Denial-of-Service (DDoS) attacks. This constant makes such attacks
* prohibitively expensive, and eliminates the possibility of an attacker generating millions of small transactions
* to flood and crash the system.
*/
export type MinFeeConstant = OpaqueNumber<'MinFeeConstant'>;
export const MinFeeConstant = (value: number): MinFeeConstant => value as unknown as MinFeeConstant;
/**
* Min fee coefficient reflects the dependence of the transaction cost on the size of the transaction. The larger
* the transaction, the more resources are needed to store and process it.
*/
export type MinFeeCoefficient = OpaqueNumber<'MinFeeCoefficient'>;
export const MinFeeCoefficient = (value: number): MinFeeCoefficient => value as unknown as MinFeeCoefficient;
/**
* Gets the minimum fee incurred by the transaction size.
*
* @param tx The transaction to compute the min fee from.
* @param minFeeConstant The prices of the execution units.
* @param minFeeCoefficient The prices of the execution units.
*/
const minNoScriptFee = (tx: Cardano.Tx, minFeeConstant: MinFeeConstant, minFeeCoefficient: MinFeeCoefficient) => {
const txSize = serializeTx(tx).length;
return BigInt(Math.ceil(txSize * minFeeCoefficient.valueOf() + minFeeConstant.valueOf()));
};
/**
* Gets the minimum ADA amount required to be contained in the given UTXO.
*
* Requiring some amount of ADA to be included in every UTXO (where that amount is based on the size of the UTXO,
* in bytes) limits the maximum total size taken up by UTXO entries on the ledger at any given time.
*
* @param output The UTXO to get the minimum ADA amount.
* @param coinsPerUtxoByte parameter used to adjust the maximum possible UTXO size by raising and lowering the min ada
* required per UTXO.
*/
export const minAdaRequired = (output: Cardano.TxOut, coinsPerUtxoByte: bigint): bigint => {
const oldCoinSize = serializeBigInt(output.value.coins.toString()).length;
let latestSize = oldCoinSize;
let isDone = false;
while (!isDone) {
const sizeDiff = latestSize - oldCoinSize;
const tentativeMinAda =
BigInt(serializeTxOutput(output).length + MIN_ADA_CONSTANT_OVERHEAD + sizeDiff) * coinsPerUtxoByte;
const newCoinSize = serializeBigInt(tentativeMinAda.toString()).length;
isDone = latestSize === newCoinSize;
latestSize = newCoinSize;
}
const sizeChange = latestSize - oldCoinSize;
return BigInt(serializeTxOutput(output).length + MIN_ADA_CONSTANT_OVERHEAD + sizeChange) * coinsPerUtxoByte;
};
/**
* Gets the minimum transaction fee for the given transaction given its size and its execution units budget.
*
* @param tx The transaction to compute the min fee from.
* @param exUnitsPrice The current (given by protocol parameters) execution unit prices.
* @param minFeeConstant The current (given by protocol parameters) constant fee that all transaction must pay.
* @param minFeeCoefficient The current (given by protocol parameters) transaction size fee coefficient.
*/
export const minFee = (
tx: Cardano.Tx,
exUnitsPrice: Cardano.Prices,
minFeeConstant: MinFeeConstant,
minFeeCoefficient: MinFeeCoefficient
) => minNoScriptFee(tx, minFeeConstant, minFeeCoefficient) + minScriptFee(tx, exUnitsPrice);
export * from './fees';
export * from './fees';
export * from './input-selection';
export * from './selectionConstraints';
import { CML, InvalidProtocolParametersError, cmlUtil, coreToCml } from '@cardano-sdk/core';
import { CML, Cardano, InvalidProtocolParametersError, cmlUtil, coreToCml } from '@cardano-sdk/core';
import {
ComputeMinimumCoinQuantity,
ComputeSelectionLimit,
SelectionConstraints,
SelectionSkeleton,
TokenBundleSizeExceedsLimit
} from './types';
import { ManagedFreeableScope, usingAutoFree } from '@cardano-sdk/util';
} from '@cardano-sdk/input-selection';
import { MinFeeCoefficient, MinFeeConstant, minAdaRequired, minFee } from '../fees';
import { usingAutoFree } from '@cardano-sdk/util';
export type BuildTx = (selection: SelectionSkeleton, scope: ManagedFreeableScope) => Promise<CML.Transaction>;
export type BuildTx = (selection: SelectionSkeleton) => Promise<Cardano.Tx>;
export interface DefaultSelectionConstraintsProps {
protocolParameters: ProtocolParametersForInputSelection;
(
{
minFeeCoefficient,
minFeeConstant
}: Pick<ProtocolParametersRequiredByInputSelection, 'minFeeCoefficient' | 'minFeeConstant'>,
minFeeConstant,
prices
}: Pick<ProtocolParametersRequiredByInputSelection, 'minFeeCoefficient' | 'minFeeConstant' | 'prices'>,
buildTx: BuildTx
): EstimateTxFee =>
(selection) =>
usingAutoFree(async (scope) => {
const tx = await buildTx(selection, scope);
// TODO: Get this from cardano-services
const priceMem = scope.manage(
CML.UnitInterval.new(scope.manage(CML.BigNum.from_str('577')), scope.manage(CML.BigNum.from_str('10000')))
);
const priceStep = scope.manage(
CML.UnitInterval.new(scope.manage(CML.BigNum.from_str('721')), scope.manage(CML.BigNum.from_str('100000000')))
);
const exInitPrices = scope.manage(CML.ExUnitPrices.new(priceMem, priceStep));
async (selection) => {
const tx = await buildTx(selection);
const linearFee = scope.manage(
CML.LinearFee.new(
scope.manage(CML.BigNum.from_str(minFeeCoefficient.toString())),
scope.manage(CML.BigNum.from_str(minFeeConstant.toString()))
)
);
const minFee = scope.manage(CML.min_fee(tx, linearFee, exInitPrices));
return BigInt(minFee.to_str());
});
return minFee(tx, prices, MinFeeConstant(minFeeConstant), MinFeeCoefficient(minFeeCoefficient));
};
export const computeMinimumCoinQuantity =
(coinsPerUtxoByte: ProtocolParametersRequiredByInputSelection['coinsPerUtxoByte']): ComputeMinimumCoinQuantity =>
(output) =>
usingAutoFree((scope) =>
BigInt(
scope
.manage(
CML.min_ada_required(
coreToCml.txOut(scope, output),
scope.manage(CML.BigNum.from_str(coinsPerUtxoByte.toString()))
)
)
.to_str()
)
);
minAdaRequired(output, BigInt(coinsPerUtxoByte));
export const tokenBundleSizeExceedsLimit =
(maxValueSize: ProtocolParametersRequiredByInputSelection['maxValueSize']): TokenBundleSizeExceedsLimit =>
(maxTxSize: ProtocolParametersRequiredByInputSelection['maxTxSize'], buildTx: BuildTx): ComputeSelectionLimit =>
(selectionSkeleton) =>
usingAutoFree(async (scope) => {
const tx = await buildTx(selectionSkeleton, scope);
const txSize = getTxSize(tx);
const tx = await buildTx(selectionSkeleton);
const txSize = getTxSize(coreToCml.tx(scope, tx));
if (txSize <= maxTxSize) {
return selectionSkeleton.inputs.size;
}
return selectionSkeleton.inputs.size - 1;
});
export const defaultSelectionConstraints = ({
protocolParameters: { coinsPerUtxoByte, maxTxSize, maxValueSize, minFeeCoefficient, minFeeConstant },
protocolParameters: { coinsPerUtxoByte, maxTxSize, maxValueSize, minFeeCoefficient, minFeeConstant, prices },
buildTx
}: DefaultSelectionConstraintsProps): SelectionConstraints => {
if (!coinsPerUtxoByte || !maxTxSize || !maxValueSize || !minFeeCoefficient || !minFeeConstant) {
if (!coinsPerUtxoByte || !maxTxSize || !maxValueSize || !minFeeCoefficient || !minFeeConstant || !prices) {
throw new InvalidProtocolParametersError(
'Missing one of: coinsPerUtxoByte, maxTxSize, maxValueSize, minFeeCoefficient, minFeeConstant'
'Missing one of: coinsPerUtxoByte, maxTxSize, maxValueSize, minFeeCoefficient, minFeeConstant, prices'
);
}
return {
computeMinimumCoinQuantity: computeMinimumCoinQuantity(coinsPerUtxoByte),
computeMinimumCost: computeMinimumCost({ minFeeCoefficient, minFeeConstant }, buildTx),
computeMinimumCost: computeMinimumCost({ minFeeCoefficient, minFeeConstant, prices }, buildTx),
computeSelectionLimit: computeSelectionLimit(maxTxSize, buildTx),
tokenBundleSizeExceedsLimit: tokenBundleSizeExceedsLimit(maxValueSize)
};
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "../dist/cjs"
},
"references": [
{
"path": "../../util/src"
},
{
"path": "../../core/src"
},
{
"path": "../../input-selection/src"
}
]
}
import { Cardano } from '@cardano-sdk/core';
import { MinFeeCoefficient, MinFeeConstant, minAdaRequired, minFee } from '../../src';
import {
babbageTx,
babbageTxWithoutScript,
noMultiasset,
noMultiassetMinAda,
onePolicyOne0CharAsset,
onePolicyOne0CharAssetDatumHash,
onePolicyOne0CharAssetDatumHashMinAda,
onePolicyOne0CharAssetMinAda,
onePolicyOne1CharAsset,
onePolicyOne1CharAssetMinAda,
onePolicyThree1CharAsset,
onePolicyThree1CharAssetMinAda,
threePolicyThree32CharAssetDatumHash,
threePolicyThree32CharAssetDatumHashMinAda,
twoPoliciesOne0CharAsset,
twoPoliciesOne0CharAssetMinAda,
twoPoliciesOne1CharAsset,
twoPoliciesOne1CharAssetMinAda,
twoPolicyOne0CharAssetDatum,
twoPolicyOne0CharAssetDatumAndScriptReference,
twoPolicyOne0CharAssetDatumAndScriptReferenceMinAda,
twoPolicyOne0CharAssetDatumHash,
twoPolicyOne0CharAssetDatumHashMinAda,
twoPolicyOne0CharAssetDatumMinAda
} from '../testData';
import { generateRandomHexString } from '@cardano-sdk/util-dev';
const COST_PER_UTXO_BYTE = BigInt(4310);
describe('fees', () => {
describe('minAdaRequired', () => {
it('calculate the correct min ada for an utxo with no multiasset', () => {
const minAda = minAdaRequired(noMultiasset, COST_PER_UTXO_BYTE);
expect(minAda).toBe(noMultiassetMinAda);
});
it('calculate the correct min ada for an utxo with one policy with one 0 char name asset', () => {
const minAda = minAdaRequired(onePolicyOne0CharAsset, COST_PER_UTXO_BYTE);
expect(minAda).toBe(onePolicyOne0CharAssetMinAda);
});
it('calculate the correct min ada for an utxo with one policy with one 1 char name asset', () => {
const minAda = minAdaRequired(onePolicyOne1CharAsset, COST_PER_UTXO_BYTE);
expect(minAda).toBe(onePolicyOne1CharAssetMinAda);
});
it('calculate the correct min ada for an utxo with one policy with three 1 char name assets', () => {
const minAda = minAdaRequired(onePolicyThree1CharAsset, COST_PER_UTXO_BYTE);
expect(minAda).toBe(onePolicyThree1CharAssetMinAda);
});
it('calculate the correct min ada for an utxo with two policies with one 0 char name assets', () => {
const minAda = minAdaRequired(twoPoliciesOne0CharAsset, COST_PER_UTXO_BYTE);
expect(minAda).toBe(twoPoliciesOne0CharAssetMinAda);
});
it('calculate the correct min ada for an utxo with two policies with one 1 char name assets', () => {
const minAda = minAdaRequired(twoPoliciesOne1CharAsset, COST_PER_UTXO_BYTE);
expect(minAda).toBe(twoPoliciesOne1CharAssetMinAda);
});
it('calculate the correct min ada for an utxo with one policy with one 0 char name assets and datum hash', () => {
const minAda = minAdaRequired(onePolicyOne0CharAssetDatumHash, COST_PER_UTXO_BYTE);
expect(minAda).toBe(onePolicyOne0CharAssetDatumHashMinAda);
});
it(
'calculate the correct min ada for an utxo with three policies with three' +
' 32 char name assets and datum hash',
() => {
const minAda = minAdaRequired(threePolicyThree32CharAssetDatumHash, COST_PER_UTXO_BYTE);
expect(minAda).toBe(threePolicyThree32CharAssetDatumHashMinAda);
}
);
it('calculate the correct min ada for an utxo with two policies with one 0 char name assets and datum hash', () => {
const minAda = minAdaRequired(twoPolicyOne0CharAssetDatumHash, COST_PER_UTXO_BYTE);
expect(minAda).toBe(twoPolicyOne0CharAssetDatumHashMinAda);
});
it('calculate the correct min ada for an utxo with two policies with one 0 char name assets and datum', () => {
const minAda = minAdaRequired(twoPolicyOne0CharAssetDatum, COST_PER_UTXO_BYTE);
expect(minAda).toBe(twoPolicyOne0CharAssetDatumMinAda);
});
it(
'calculate the correct min ada for an utxo with two policies with one 0 char name assets,' +
'datum and script reference',
() => {
const minAda = minAdaRequired(twoPolicyOne0CharAssetDatumAndScriptReference, COST_PER_UTXO_BYTE);
expect(minAda).toBe(twoPolicyOne0CharAssetDatumAndScriptReferenceMinAda);
}
);
it('calculate the correct min ada for an utxo with 1000 policies with one billion 0 char name asset', () => {
const output = onePolicyOne0CharAsset;
const assets = new Map([[Cardano.AssetId('ab8370c97ae17eb69a8c97f733888f7485b60fd820c69211c8bbeb56'), 1n]]);
for (let i = 0; i < 1000; ++i) {
const policy = generateRandomHexString(56);
assets.set(Cardano.AssetId(policy), 1_000_000_000n);
}
output.value.assets = assets;
const minAda = minAdaRequired(output, COST_PER_UTXO_BYTE);
expect(minAda).toBe(160_599_220n);
});
});
describe('minFee', () => {
it('calculate the correct min fee for transaction without scripts', () => {
const prices = { memory: 0.0577, steps: 0.000_007_21 };
const fee = minFee(babbageTxWithoutScript, prices, MinFeeConstant(155_381), MinFeeCoefficient(44));
expect(fee).toBe(176_193n);
});
it('calculate the correct min fee for transaction with scripts', () => {
const prices = { memory: 0.0577, steps: 0.000_007_21 };
const fee = minFee(babbageTx, prices, MinFeeConstant(155_381), MinFeeCoefficient(44));
expect(fee).toBe(218_807n);
});
});
});
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable unicorn/consistent-function-scoping */
import { AssetId } from '@cardano-sdk/util-dev';
import { CML, Cardano, InvalidProtocolParametersError } from '@cardano-sdk/core';
import { DefaultSelectionConstraintsProps, defaultSelectionConstraints } from '../src/selectionConstraints';
import { ProtocolParametersForInputSelection, SelectionSkeleton } from '../src/types';
import { Cardano, InvalidProtocolParametersError } from '@cardano-sdk/core';
import { DefaultSelectionConstraintsProps, defaultSelectionConstraints } from '../../src';
import { ProtocolParametersForInputSelection, SelectionSkeleton } from '@cardano-sdk/input-selection';
import { babbageTx, getBigBabbageTx } from '../testData';
jest.mock('@dcspark/cardano-multiplatform-lib-nodejs', () => {
const actualCml = jest.requireActual('@dcspark/cardano-multiplatform-lib-nodejs');
maxTxSize: 16_384,
maxValueSize: 5000,
minFeeCoefficient: 44,
minFeeConstant: 155_381
minFeeConstant: 155_381,
prices: { memory: 0.0577, steps: 0.000_007_21 }
} as ProtocolParametersForInputSelection;
it('Invalid parameters', () => {
});
it('computeMinimumCost', async () => {
const fee = 200_000n;
// Need this to not have to build Tx
cmlMock.min_fee.mockReturnValueOnce(cmlMock.BigNum.from_str(fee.toString()));
const buildTx = jest.fn();
cmlMock.Value.new.mockImplementation(cmlActual.Value.new);
const fee = 218_807n;
const buildTx = jest.fn(async () => babbageTx);
const selectionSkeleton = {} as SelectionSkeleton;
const constraints = defaultSelectionConstraints({
buildTx,
const result = await constraints.computeMinimumCost(selectionSkeleton);
expect(result).toEqual(fee);
expect(buildTx).toBeCalledTimes(1);
expect(buildTx).toBeCalledWith(selectionSkeleton, expect.anything());
expect(buildTx).toBeCalledWith(selectionSkeleton);
});
it('computeMinimumCoinQuantity', () => {
});
describe('computeSelectionLimit', () => {
const buildTxOfLength = (length: number) => async () => ({ to_bytes: () => ({ length }) } as CML.Transaction);
it("doesn't exceed max tx size", async () => {
const constraints = defaultSelectionConstraints({
buildTx: buildTxOfLength(protocolParameters.maxTxSize!),
buildTx: async () => babbageTx,
protocolParameters
});
expect(await constraints.computeSelectionLimit({ inputs: new Set([1, 2]) as any } as SelectionSkeleton)).toEqual(
it('exceeds max tx size', async () => {
const constraints = defaultSelectionConstraints({
buildTx: buildTxOfLength(protocolParameters.maxTxSize! + 1),
buildTx: getBigBabbageTx,
protocolParameters
});
expect(await constraints.computeSelectionLimit({ inputs: new Set([1, 2]) as any } as SelectionSkeleton)).toEqual(
import * as Crypto from '@cardano-sdk/crypto';
import { Base64Blob, HexBlob } from '@cardano-sdk/util';
import { Cardano } from '@cardano-sdk/core';
import { generateRandomHexString } from '@cardano-sdk/util-dev';
export const rewardAccount = Cardano.RewardAccount('stake1u89sasnfyjtmgk8ydqfv3fdl52f36x3djedfnzfc9rkgzrcss5vgr');
export const stakeKeyHash = Cardano.RewardAccount.toHash(rewardAccount);
export const poolId = Cardano.PoolId('pool1mpgg03jxj52qwxvvy7cmj58a96vl9pvxcqqvuw0kumheygxmn34');
export const vrf = Cardano.VrfVkHex('8dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0');
export const metadataJson = {
hash: Crypto.Hash32ByteBase16('0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5'),
url: 'https://example.com'
};
export const script: Cardano.NativeScript = {
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireAnyOf,
scripts: [
{
__type: Cardano.ScriptType.Native,
keyHash: Crypto.Ed25519KeyHashHex('b275b08c999097247f7c17e77007c7010cd19f20cc086ad99d398538'),
kind: Cardano.NativeScriptKind.RequireSignature
},
{
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireAllOf,
scripts: [
{
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireTimeBefore,
slot: Cardano.Slot(3000)
},
{
__type: Cardano.ScriptType.Native,
keyHash: Crypto.Ed25519KeyHashHex('966e394a544f242081e41d1965137b1bb412ac230d40ed5407821c37'),
kind: Cardano.NativeScriptKind.RequireSignature
},
{
__type: Cardano.ScriptType.Native,
kind: Cardano.NativeScriptKind.RequireTimeAfter,
slot: Cardano.Slot(4000)
}
]
}
]
};
export const mintTokenMap = new Map([
[Cardano.AssetId('2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740'), 20n],
[Cardano.AssetId('659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba8254534c41'), -50n],
[Cardano.AssetId('7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373'), 40n],
[Cardano.AssetId('7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373504154415445'), 30n]
]);
export const valueWithAssets = {
assets: new Map([
[Cardano.AssetId('2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740'), 20n],
[Cardano.AssetId('659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba8254534c41'), 50n],
[Cardano.AssetId('7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373'), 40n],
[Cardano.AssetId('7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373504154415445'), 30n]
]),
coins: 10n
};
export const txIn = {
index: 0,
txId: Cardano.TransactionId('0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5')
};
export const txOut: Cardano.TxOut = {
address: Cardano.Address(
'addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp'
),
value: valueWithAssets
};
export const txBody: Cardano.TxBody = {
certificates: [
{
__typename: Cardano.CertificateType.PoolRetirement,
epoch: Cardano.EpochNo(500),
poolId: Cardano.PoolId('pool1y6chk7x7fup4ms9leesdr57r4qy9cwxuee0msan72x976a6u0nc')
},
{
__typename: Cardano.CertificateType.GenesisKeyDelegation,
genesisDelegateHash: Crypto.Hash28ByteBase16('a646474b8f5431261506b6c273d307c7569a4eb6c96b42dd4a29520a'),
genesisHash: Crypto.Hash28ByteBase16('0d94e174732ef9aae73f395ab44507bfa983d65023c11a951f0c32e4'),
vrfKeyHash: Crypto.Hash32ByteBase16('03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314')
}
],
collaterals: [{ ...txIn, index: txIn.index + 1 }],
fee: 10n,
inputs: [txIn],
mint: mintTokenMap,
outputs: [txOut],
requiredExtraSignatures: [Crypto.Ed25519KeyHashHex('6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d39')],
scriptIntegrityHash: Crypto.Hash32ByteBase16('6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d38abc123de'),
validityInterval: {
invalidBefore: Cardano.Slot(100),
invalidHereafter: Cardano.Slot(1000)
},
withdrawals: [
{
quantity: 5n,
stakeAddress: Cardano.RewardAccount('stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27')
}
]
};
export const simpleTxBody: Cardano.TxBody = {
fee: 10n,
inputs: [txIn],
outputs: [txOut],
validityInterval: {
invalidBefore: Cardano.Slot(100),
invalidHereafter: Cardano.Slot(1000)
}
};
export const babbageTxBody: Cardano.TxBody = {
...txBody,
collateralReturn: txOut,
referenceInputs: [txIn],
totalCollateral: 100n
};
export const vkey = '6199186adb51974690d7247d2646097d2c62763b767b528816fb7ed3f9f55d39';
export const signature =
// eslint-disable-next-line max-len
'bdea87fca1b4b4df8a9b8fb4183c0fab2f8261eb6c5e4bc42c800bb9c8918755bdea87fca1b4b4df8a9b8fb4183c0fab2f8261eb6c5e4bc42c800bb9c8918755';
export const tx: Cardano.Tx = {
auxiliaryData: {
body: {
blob: new Map<bigint, Cardano.Metadatum>([
[1n, 1234n],
[2n, 'str'],
[3n, [1234n, 'str']],
[4n, new Uint8Array(Buffer.from('bytes'))],
[
5n,
new Map<Cardano.Metadatum, Cardano.Metadatum>([
['strkey', 123n],
[['listkey'], 'strvalue']
])
],
[6n, -7n]
])
}
},
body: txBody,
id: Cardano.TransactionId('8d2feeab1087e0aa4ad06e878c5269eaa2edcef5264bcc97542a28c189b2cbc5'),
witness: {
// bootstrap values from ogmios.wsp.json
bootstrap: [
{
addressAttributes: Base64Blob('oA=='),
chainCode: HexBlob('b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450'),
key: Crypto.Ed25519PublicKeyHex('deeb8f82f2af5836ebbc1b450b6dbf0b03c93afe5696f10d49e8a8304ebfac01'),
signature: Crypto.Ed25519SignatureHex(
Buffer.from(
'ZGdic3hnZ3RvZ2hkanB0ZXR2dGtjb2N2eWZpZHFxZ2d1cmpocmhxYWlpc3BxcnVlbGh2eXBxeGVld3ByeWZ2dw==',
'base64'
).toString('hex')
)
}
],
datums: [HexBlob('187b')],
redeemers: [
{
data: HexBlob('d86682008101'),
executionUnits: {
memory: 3000,
steps: 7000
},
index: 0,
purpose: Cardano.RedeemerPurpose.mint
},
{
data: HexBlob('d86682008102'),
executionUnits: {
memory: 5000,
steps: 2000
},
index: 1,
purpose: Cardano.RedeemerPurpose.certificate
}
],
scripts: [
{
__type: Cardano.ScriptType.Plutus,
bytes: HexBlob('b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450'),
version: Cardano.PlutusLanguageVersion.V1
},
{
__type: Cardano.ScriptType.Plutus,
bytes: HexBlob('b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450'),
version: Cardano.PlutusLanguageVersion.V2
},
{
__type: Cardano.ScriptType.Native,
{
"extends": "../../../test/tsconfig.json",
"compilerOptions": {
"baseUrl": "."
},
"references": [
{
"path": "../src"
}
]
}
"@cardano-sdk/dapp-connector": "^0.6.1",
"@cardano-sdk/input-selection": "^0.7.0",
"@cardano-sdk/key-management": "^0.3.0",
"@cardano-sdk/tx-construction": "^0.1.0",
"@cardano-sdk/util": "^0.7.0",
"@cardano-sdk/util-rxjs": "^0.4.3",
"backoff-rxjs": "^7.0.0",