@onekeyfe/cardano-coin-selection-asmjs 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.MD +25 -0
  2. package/README.md +183 -0
  3. package/lib/cjs/constants/index.d.ts +40 -0
  4. package/lib/cjs/constants/index.js +69 -0
  5. package/lib/cjs/index.d.ts +6 -0
  6. package/lib/cjs/index.js +101 -0
  7. package/lib/cjs/methods/largestFirst.d.ts +2 -0
  8. package/lib/cjs/methods/largestFirst.js +201 -0
  9. package/lib/cjs/methods/randomImprove.d.ts +2 -0
  10. package/lib/cjs/methods/randomImprove.js +187 -0
  11. package/lib/cjs/types/trezor.d.ts +45 -0
  12. package/lib/cjs/types/trezor.js +8 -0
  13. package/lib/cjs/types/types.d.ts +116 -0
  14. package/lib/cjs/types/types.js +17 -0
  15. package/lib/cjs/utils/common.d.ts +46 -0
  16. package/lib/cjs/utils/common.js +514 -0
  17. package/lib/cjs/utils/errors.d.ts +8 -0
  18. package/lib/cjs/utils/errors.js +13 -0
  19. package/lib/cjs/utils/logger.d.ts +5 -0
  20. package/lib/cjs/utils/logger.js +27 -0
  21. package/lib/cjs/utils/onekey/dapp.d.ts +14 -0
  22. package/lib/cjs/utils/onekey/dapp.js +247 -0
  23. package/lib/cjs/utils/onekey/error.d.ts +28 -0
  24. package/lib/cjs/utils/onekey/error.js +25 -0
  25. package/lib/cjs/utils/onekey/index.d.ts +48 -0
  26. package/lib/cjs/utils/onekey/index.js +15 -0
  27. package/lib/cjs/utils/onekey/signTx.d.ts +26 -0
  28. package/lib/cjs/utils/onekey/signTx.js +296 -0
  29. package/lib/cjs/utils/onekey/transaction.d.ts +5 -0
  30. package/lib/cjs/utils/onekey/transaction.js +49 -0
  31. package/lib/cjs/utils/onekey/txToOneKey.d.ts +67 -0
  32. package/lib/cjs/utils/onekey/txToOneKey.js +504 -0
  33. package/lib/cjs/utils/onekey/types.d.ts +79 -0
  34. package/lib/cjs/utils/onekey/types.js +16 -0
  35. package/lib/cjs/utils/trezor/index.d.ts +3 -0
  36. package/lib/cjs/utils/trezor/index.js +9 -0
  37. package/lib/cjs/utils/trezor/sign.d.ts +5 -0
  38. package/lib/cjs/utils/trezor/sign.js +69 -0
  39. package/lib/cjs/utils/trezor/transformations.d.ts +17 -0
  40. package/lib/cjs/utils/trezor/transformations.js +66 -0
  41. package/lib/esm/constants/index.d.ts +40 -0
  42. package/lib/esm/constants/index.js +43 -0
  43. package/lib/esm/index.d.ts +6 -0
  44. package/lib/esm/index.js +73 -0
  45. package/lib/esm/methods/largestFirst.d.ts +2 -0
  46. package/lib/esm/methods/largestFirst.js +174 -0
  47. package/lib/esm/methods/randomImprove.d.ts +2 -0
  48. package/lib/esm/methods/randomImprove.js +160 -0
  49. package/lib/esm/types/trezor.d.ts +45 -0
  50. package/lib/esm/types/trezor.js +5 -0
  51. package/lib/esm/types/types.d.ts +116 -0
  52. package/lib/esm/types/types.js +14 -0
  53. package/lib/esm/utils/common.d.ts +46 -0
  54. package/lib/esm/utils/common.js +460 -0
  55. package/lib/esm/utils/errors.d.ts +8 -0
  56. package/lib/esm/utils/errors.js +9 -0
  57. package/lib/esm/utils/logger.d.ts +5 -0
  58. package/lib/esm/utils/logger.js +23 -0
  59. package/lib/esm/utils/onekey/dapp.d.ts +14 -0
  60. package/lib/esm/utils/onekey/dapp.js +216 -0
  61. package/lib/esm/utils/onekey/error.d.ts +28 -0
  62. package/lib/esm/utils/onekey/error.js +22 -0
  63. package/lib/esm/utils/onekey/index.d.ts +48 -0
  64. package/lib/esm/utils/onekey/index.js +11 -0
  65. package/lib/esm/utils/onekey/signTx.d.ts +26 -0
  66. package/lib/esm/utils/onekey/signTx.js +266 -0
  67. package/lib/esm/utils/onekey/transaction.d.ts +5 -0
  68. package/lib/esm/utils/onekey/transaction.js +42 -0
  69. package/lib/esm/utils/onekey/txToOneKey.d.ts +67 -0
  70. package/lib/esm/utils/onekey/txToOneKey.js +477 -0
  71. package/lib/esm/utils/onekey/types.d.ts +79 -0
  72. package/lib/esm/utils/onekey/types.js +15 -0
  73. package/lib/esm/utils/trezor/index.d.ts +3 -0
  74. package/lib/esm/utils/trezor/index.js +3 -0
  75. package/lib/esm/utils/trezor/sign.d.ts +5 -0
  76. package/lib/esm/utils/trezor/sign.js +42 -0
  77. package/lib/esm/utils/trezor/transformations.d.ts +17 -0
  78. package/lib/esm/utils/trezor/transformations.js +60 -0
  79. package/package.json +61 -0
@@ -0,0 +1,514 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.orderInputs = exports.calculateUserOutputsFee = exports.getRandomUtxo = exports.filterUtxos = exports.getUserOutputQuantityWithDeposit = exports.setMaxOutput = exports.getInitialUtxoSet = exports.getUnsatisfiedAssets = exports.getTxBuilder = exports.prepareChangeOutput = exports.splitChangeOutput = exports.setMinUtxoValueForOutputs = exports.calculateRequiredDeposit = exports.prepareCertificates = exports.prepareWithdrawals = exports.getOutputCost = exports.buildTxOutput = exports.buildTxInput = exports.sortUtxos = exports.getOutputQuantity = exports.getUtxoQuantity = exports.getAssetAmount = exports.multiAssetToArray = exports.buildMultiAsset = exports.parseAsset = exports.getNetworkId = exports.getProtocolMagic = exports.bigNumFromStr = void 0;
27
+ const CardanoWasm = __importStar(require("@emurgo/cardano-serialization-lib-asmjs"));
28
+ const constants_1 = require("../constants");
29
+ const errors_1 = require("./errors");
30
+ const bigNumFromStr = (num) => CardanoWasm.BigNum.from_str(num);
31
+ exports.bigNumFromStr = bigNumFromStr;
32
+ const getProtocolMagic = (tesnet) => tesnet
33
+ ? constants_1.CARDANO_PARAMS.PROTOCOL_MAGICS.testnet
34
+ : constants_1.CARDANO_PARAMS.PROTOCOL_MAGICS.mainnet;
35
+ exports.getProtocolMagic = getProtocolMagic;
36
+ const getNetworkId = (testnet) => testnet
37
+ ? constants_1.CARDANO_PARAMS.NETWORK_IDS.testnet
38
+ : constants_1.CARDANO_PARAMS.NETWORK_IDS.mainnet;
39
+ exports.getNetworkId = getNetworkId;
40
+ const parseAsset = (hex) => {
41
+ const policyIdSize = 56;
42
+ const policyId = hex.slice(0, policyIdSize);
43
+ const assetNameInHex = hex.slice(policyIdSize);
44
+ return {
45
+ policyId,
46
+ assetNameInHex,
47
+ };
48
+ };
49
+ exports.parseAsset = parseAsset;
50
+ const buildMultiAsset = (assets) => {
51
+ const multiAsset = CardanoWasm.MultiAsset.new();
52
+ const assetsGroupedByPolicy = {};
53
+ assets.forEach(assetEntry => {
54
+ const { policyId, assetNameInHex } = (0, exports.parseAsset)(assetEntry.unit);
55
+ if (!assetsGroupedByPolicy[policyId]) {
56
+ assetsGroupedByPolicy[policyId] = CardanoWasm.Assets.new();
57
+ }
58
+ const assets = assetsGroupedByPolicy[policyId];
59
+ assets.insert(CardanoWasm.AssetName.new(Buffer.from(assetNameInHex, 'hex')), (0, exports.bigNumFromStr)(assetEntry.quantity || '0'));
60
+ });
61
+ Object.keys(assetsGroupedByPolicy).forEach(policyId => {
62
+ const scriptHash = CardanoWasm.ScriptHash.from_bytes(Buffer.from(policyId, 'hex'));
63
+ multiAsset.insert(scriptHash, assetsGroupedByPolicy[policyId]);
64
+ });
65
+ return multiAsset;
66
+ };
67
+ exports.buildMultiAsset = buildMultiAsset;
68
+ const multiAssetToArray = (multiAsset) => {
69
+ if (!multiAsset)
70
+ return [];
71
+ const assetsArray = [];
72
+ const policyHashes = multiAsset.keys();
73
+ for (let i = 0; i < policyHashes.len(); i++) {
74
+ const policyId = policyHashes.get(i);
75
+ const assetsInPolicy = multiAsset.get(policyId);
76
+ if (!assetsInPolicy)
77
+ continue;
78
+ const assetNames = assetsInPolicy.keys();
79
+ for (let j = 0; j < assetNames.len(); j++) {
80
+ const assetName = assetNames.get(j);
81
+ const amount = assetsInPolicy.get(assetName);
82
+ if (!amount)
83
+ continue;
84
+ const policyIdHex = Buffer.from(policyId.to_bytes()).toString('hex');
85
+ const assetNameHex = Buffer.from(assetName.name()).toString('hex');
86
+ assetsArray.push({
87
+ quantity: amount.to_str(),
88
+ unit: `${policyIdHex}${assetNameHex}`,
89
+ });
90
+ }
91
+ }
92
+ return assetsArray;
93
+ };
94
+ exports.multiAssetToArray = multiAssetToArray;
95
+ const getAssetAmount = (obj, asset = 'lovelace') => { var _a, _b; return (_b = (_a = obj.amount.find(a => a.unit === asset)) === null || _a === void 0 ? void 0 : _a.quantity) !== null && _b !== void 0 ? _b : '0'; };
96
+ exports.getAssetAmount = getAssetAmount;
97
+ const getUtxoQuantity = (utxos, asset = 'lovelace') => utxos.reduce((acc, utxo) => acc.checked_add((0, exports.bigNumFromStr)((0, exports.getAssetAmount)(utxo, asset))), (0, exports.bigNumFromStr)('0'));
98
+ exports.getUtxoQuantity = getUtxoQuantity;
99
+ const getOutputQuantity = (outputs, asset = 'lovelace') => {
100
+ if (asset === 'lovelace') {
101
+ return outputs.reduce((acc, output) => { var _a; return acc.checked_add((0, exports.bigNumFromStr)((_a = output.amount) !== null && _a !== void 0 ? _a : '0')); }, (0, exports.bigNumFromStr)('0'));
102
+ }
103
+ return outputs.reduce((acc, output) => {
104
+ var _a, _b, _c;
105
+ return acc.checked_add((0, exports.bigNumFromStr)((_c = (_b = (_a = output.assets) === null || _a === void 0 ? void 0 : _a.find(a => a.unit === asset)) === null || _b === void 0 ? void 0 : _b.quantity) !== null && _c !== void 0 ? _c : '0'));
106
+ }, (0, exports.bigNumFromStr)('0'));
107
+ };
108
+ exports.getOutputQuantity = getOutputQuantity;
109
+ const sortUtxos = (utxos, asset = 'lovelace') => {
110
+ const copy = JSON.parse(JSON.stringify(utxos));
111
+ return copy.sort((u1, u2) => (0, exports.bigNumFromStr)((0, exports.getAssetAmount)(u2, asset)).compare((0, exports.bigNumFromStr)((0, exports.getAssetAmount)(u1, asset))));
112
+ };
113
+ exports.sortUtxos = sortUtxos;
114
+ const buildTxInput = (utxo) => {
115
+ const input = CardanoWasm.TransactionInput.new(CardanoWasm.TransactionHash.from_bytes(Buffer.from(utxo.txHash, 'hex')), utxo.outputIndex);
116
+ const amount = CardanoWasm.Value.new((0, exports.bigNumFromStr)((0, exports.getAssetAmount)(utxo)));
117
+ const assets = utxo.amount.filter(a => a.unit !== 'lovelace');
118
+ if (assets.length > 0) {
119
+ const multiAsset = (0, exports.buildMultiAsset)(assets);
120
+ amount.set_multiasset(multiAsset);
121
+ }
122
+ const address = CardanoWasm.Address.from_bech32(utxo.address);
123
+ return { input, address, amount };
124
+ };
125
+ exports.buildTxInput = buildTxInput;
126
+ const buildTxOutput = (output, dummyAddress) => {
127
+ var _a;
128
+ // If output.address was not defined fallback to bech32 address (useful for "precompose" tx
129
+ // which doesn't have all necessary data, but we can fill in the blanks and return some info such as fee)
130
+ const outputAddr = output.address && CardanoWasm.ByronAddress.is_valid(output.address)
131
+ ? CardanoWasm.ByronAddress.from_base58(output.address).to_address()
132
+ : CardanoWasm.Address.from_bech32((_a = output.address) !== null && _a !== void 0 ? _a : dummyAddress);
133
+ // Set initial amount
134
+ const outputAmount = output.amount
135
+ ? (0, exports.bigNumFromStr)(output.amount)
136
+ : (0, exports.bigNumFromStr)('0');
137
+ // Create Value including assets
138
+ let outputValue = CardanoWasm.Value.new(outputAmount);
139
+ const multiAsset = output.assets.length > 0 ? (0, exports.buildMultiAsset)(output.assets) : null;
140
+ if (multiAsset) {
141
+ outputValue.set_multiasset(multiAsset);
142
+ }
143
+ // Calculate min required ADA for the output
144
+ let txOutput = CardanoWasm.TransactionOutput.new(outputAddr, outputValue);
145
+ const minAdaRequired = CardanoWasm.min_ada_for_output(txOutput, constants_1.DATA_COST_PER_UTXO_BYTE);
146
+ // If calculated min required ada is greater than current output value than adjust it
147
+ if (outputAmount.compare(minAdaRequired) < 0) {
148
+ outputValue = CardanoWasm.Value.new(minAdaRequired);
149
+ if (multiAsset) {
150
+ outputValue.set_multiasset(multiAsset);
151
+ }
152
+ txOutput = CardanoWasm.TransactionOutput.new(outputAddr, outputValue);
153
+ }
154
+ return txOutput;
155
+ };
156
+ exports.buildTxOutput = buildTxOutput;
157
+ const getOutputCost = (txBuilder, output, dummyAddress) => {
158
+ const txOutput = (0, exports.buildTxOutput)(output, dummyAddress);
159
+ const outputFee = txBuilder.fee_for_output(txOutput);
160
+ const minAda = CardanoWasm.min_ada_for_output(txOutput, constants_1.DATA_COST_PER_UTXO_BYTE);
161
+ return {
162
+ output: txOutput,
163
+ outputFee,
164
+ minOutputAmount: minAda, // should match https://cardano-ledger.readthedocs.io/en/latest/explanations/min-utxo.html
165
+ };
166
+ };
167
+ exports.getOutputCost = getOutputCost;
168
+ const prepareWithdrawals = (withdrawals) => {
169
+ const preparedWithdrawals = CardanoWasm.Withdrawals.new();
170
+ withdrawals.forEach(withdrawal => {
171
+ const rewardAddress = CardanoWasm.RewardAddress.from_address(CardanoWasm.Address.from_bech32(withdrawal.stakeAddress));
172
+ if (rewardAddress) {
173
+ preparedWithdrawals.insert(rewardAddress, (0, exports.bigNumFromStr)(withdrawal.amount));
174
+ }
175
+ });
176
+ return preparedWithdrawals;
177
+ };
178
+ exports.prepareWithdrawals = prepareWithdrawals;
179
+ const prepareCertificates = (certificates, accountKey) => {
180
+ const preparedCertificates = CardanoWasm.Certificates.new();
181
+ if (certificates.length === 0)
182
+ return preparedCertificates;
183
+ const stakeKey = accountKey.derive(2).derive(0);
184
+ const stakeCred = CardanoWasm.StakeCredential.from_keyhash(stakeKey.to_raw_key().hash());
185
+ certificates.forEach(cert => {
186
+ if (cert.type === constants_1.CertificateType.STAKE_REGISTRATION) {
187
+ preparedCertificates.add(CardanoWasm.Certificate.new_stake_registration(CardanoWasm.StakeRegistration.new(stakeCred)));
188
+ }
189
+ else if (cert.type === constants_1.CertificateType.STAKE_DELEGATION) {
190
+ preparedCertificates.add(CardanoWasm.Certificate.new_stake_delegation(CardanoWasm.StakeDelegation.new(stakeCred, CardanoWasm.Ed25519KeyHash.from_bytes(Buffer.from(cert.pool, 'hex')))));
191
+ }
192
+ else if (cert.type === constants_1.CertificateType.STAKE_DEREGISTRATION) {
193
+ preparedCertificates.add(CardanoWasm.Certificate.new_stake_deregistration(CardanoWasm.StakeDeregistration.new(stakeCred)));
194
+ }
195
+ else {
196
+ throw new errors_1.CoinSelectionError(constants_1.ERROR.UNSUPPORTED_CERTIFICATE_TYPE);
197
+ }
198
+ });
199
+ return preparedCertificates;
200
+ };
201
+ exports.prepareCertificates = prepareCertificates;
202
+ const calculateRequiredDeposit = (certificates) => {
203
+ const CertificateDeposit = {
204
+ [constants_1.CertificateType.STAKE_DELEGATION]: 0,
205
+ [constants_1.CertificateType.STAKE_POOL_REGISTRATION]: 500000000,
206
+ [constants_1.CertificateType.STAKE_REGISTRATION]: 2000000,
207
+ [constants_1.CertificateType.STAKE_DEREGISTRATION]: -2000000,
208
+ };
209
+ return certificates.reduce((acc, cert) => (acc += CertificateDeposit[cert.type]), 0);
210
+ };
211
+ exports.calculateRequiredDeposit = calculateRequiredDeposit;
212
+ const setMinUtxoValueForOutputs = (txBuilder, outputs, dummyAddress) => {
213
+ const preparedOutputs = outputs.map(output => {
214
+ // sets minimal output ADA amount in case of multi-asset output
215
+ const { minOutputAmount } = (0, exports.getOutputCost)(txBuilder, output, dummyAddress);
216
+ const outputAmount = (0, exports.bigNumFromStr)(output.amount || '0');
217
+ let amount;
218
+ if (output.assets.length > 0 && outputAmount.compare(minOutputAmount) < 0) {
219
+ // output with an asset(s) adjust minimum ADA to met network requirements
220
+ amount = minOutputAmount.to_str();
221
+ }
222
+ else {
223
+ amount = output.amount;
224
+ }
225
+ if (!output.setMax &&
226
+ output.assets.length === 0 &&
227
+ output.amount &&
228
+ outputAmount.compare(minOutputAmount) < 0) {
229
+ // Case of an output without any asset, and without setMax = true
230
+ // If the user entered less than min utxo val then throw an error (won't throw if there is no amount yet)
231
+ // (On outputs with setMax flag we set '0' on purpose)
232
+ // (On outputs with an asset we automatically adjust ADA amount if it is below required minimum)
233
+ throw new errors_1.CoinSelectionError(constants_1.ERROR.UTXO_VALUE_TOO_SMALL);
234
+ }
235
+ if (output.setMax) {
236
+ // if setMax is active set initial value to 0
237
+ if (output.assets.length > 0) {
238
+ output.assets[0].quantity = '0';
239
+ }
240
+ else {
241
+ amount = '0';
242
+ }
243
+ }
244
+ return Object.assign(Object.assign({}, output), {
245
+ // if output contains assets make sure that minUtxoValue is at least minOutputAmount (even for output where we want to setMax)
246
+ amount });
247
+ });
248
+ return preparedOutputs;
249
+ };
250
+ exports.setMinUtxoValueForOutputs = setMinUtxoValueForOutputs;
251
+ const splitChangeOutput = (txBuilder, singleChangeOutput, changeAddress, maxTokensPerOutput = constants_1.MAX_TOKENS_PER_OUTPUT) => {
252
+ // TODO: https://github.com/Emurgo/cardano-serialization-lib/pull/236
253
+ const multiAsset = singleChangeOutput.output.amount().multiasset();
254
+ if (!multiAsset || (multiAsset && multiAsset.len() < maxTokensPerOutput)) {
255
+ return [singleChangeOutput];
256
+ }
257
+ let lovelaceAvailable = singleChangeOutput.output
258
+ .amount()
259
+ .coin()
260
+ .checked_add(singleChangeOutput.outputFee);
261
+ const allAssets = (0, exports.multiAssetToArray)(singleChangeOutput.output.amount().multiasset());
262
+ const nAssetBundles = Math.ceil(allAssets.length / maxTokensPerOutput);
263
+ const changeOutputs = [];
264
+ // split change output to multiple outputs, where each bundle has maximum of maxTokensPerOutput assets
265
+ for (let i = 0; i < nAssetBundles; i++) {
266
+ const assetsBundle = allAssets.slice(i * maxTokensPerOutput, (i + 1) * maxTokensPerOutput);
267
+ const outputValue = CardanoWasm.Value.new_from_assets((0, exports.buildMultiAsset)(assetsBundle));
268
+ const txOutput = CardanoWasm.TransactionOutput.new(CardanoWasm.Address.from_bech32(changeAddress), outputValue);
269
+ const minAdaRequired = CardanoWasm.min_ada_for_output(txOutput, constants_1.DATA_COST_PER_UTXO_BYTE);
270
+ changeOutputs.push({
271
+ isChange: true,
272
+ address: changeAddress,
273
+ amount: minAdaRequired.to_str(),
274
+ assets: assetsBundle,
275
+ });
276
+ }
277
+ const changeOutputsCost = changeOutputs.map((partialChange, i) => {
278
+ let changeOutputCost = (0, exports.getOutputCost)(txBuilder, partialChange, changeAddress);
279
+ lovelaceAvailable = lovelaceAvailable.clamped_sub((0, exports.bigNumFromStr)(partialChange.amount).checked_add(changeOutputCost.outputFee));
280
+ if (i === changeOutputs.length - 1) {
281
+ // add all unused ADA to the last change output
282
+ let changeOutputAmount = lovelaceAvailable.checked_add((0, exports.bigNumFromStr)(partialChange.amount));
283
+ if (changeOutputAmount.compare(changeOutputCost.minOutputAmount) < 0) {
284
+ // computed change amount would be below minUtxoValue
285
+ // set change output amount to met minimum requirements for minUtxoValue
286
+ changeOutputAmount = changeOutputCost.minOutputAmount;
287
+ }
288
+ partialChange.amount = changeOutputAmount.to_str();
289
+ changeOutputCost = (0, exports.getOutputCost)(txBuilder, partialChange, changeAddress);
290
+ }
291
+ return changeOutputCost;
292
+ });
293
+ return changeOutputsCost;
294
+ };
295
+ exports.splitChangeOutput = splitChangeOutput;
296
+ const prepareChangeOutput = (txBuilder, usedUtxos, preparedOutputs, changeAddress, utxosTotalAmount, totalOutputAmount, totalFeesAmount, pickAdditionalUtxo) => {
297
+ // change output amount should be lowered by the cost of the change output (fee + minUtxoVal)
298
+ // The cost will be subtracted once we calculate it.
299
+ const placeholderChangeOutputAmount = utxosTotalAmount.clamped_sub(totalFeesAmount.checked_add(totalOutputAmount));
300
+ const uniqueAssets = [];
301
+ usedUtxos.forEach(utxo => {
302
+ const assets = utxo.amount.filter(a => a.unit !== 'lovelace');
303
+ assets.forEach(asset => {
304
+ if (!uniqueAssets.includes(asset.unit)) {
305
+ uniqueAssets.push(asset.unit);
306
+ }
307
+ });
308
+ });
309
+ const changeOutputAssets = uniqueAssets
310
+ .map(assetUnit => {
311
+ const assetInputAmount = (0, exports.getUtxoQuantity)(usedUtxos, assetUnit);
312
+ const assetSpentAmount = (0, exports.getOutputQuantity)(preparedOutputs, assetUnit);
313
+ return {
314
+ unit: assetUnit,
315
+ quantity: assetInputAmount.clamped_sub(assetSpentAmount).to_str(),
316
+ };
317
+ })
318
+ .filter(asset => asset.quantity !== '0');
319
+ const changeOutputCost = (0, exports.getOutputCost)(txBuilder, {
320
+ address: changeAddress,
321
+ amount: placeholderChangeOutputAmount.to_str(),
322
+ assets: changeOutputAssets,
323
+ }, changeAddress);
324
+ // calculate change output amount as utxosTotalAmount - totalOutputAmount - totalFeesAmount - change output fee
325
+ const totalSpent = totalOutputAmount
326
+ .checked_add(totalFeesAmount)
327
+ .checked_add(changeOutputCost.outputFee);
328
+ let changeOutputAmount = utxosTotalAmount.clamped_sub(totalSpent);
329
+ // Sum of all tokens in utxos must be same as sum of the tokens in external + change outputs
330
+ // If computed change output doesn't contain any tokens then it makes sense to add it only if the fee + minUtxoValue is less then the amount
331
+ let isChangeOutputNeeded = false;
332
+ if (changeOutputAssets.length > 0 ||
333
+ changeOutputAmount.compare(changeOutputCost.minOutputAmount) >= 0) {
334
+ isChangeOutputNeeded = true;
335
+ }
336
+ else if (pickAdditionalUtxo &&
337
+ changeOutputAmount.compare((0, exports.bigNumFromStr)('5000')) >= 0) {
338
+ // change amount is above our constant (0.005 ADA), but still less than required minUtxoValue
339
+ // try to add another utxo recalculate change again
340
+ const utxo = pickAdditionalUtxo();
341
+ if (utxo) {
342
+ utxo.addUtxo();
343
+ const newTotalFee = txBuilder.min_fee();
344
+ return (0, exports.prepareChangeOutput)(txBuilder, usedUtxos, preparedOutputs, changeAddress, (0, exports.getUtxoQuantity)(usedUtxos, 'lovelace'), totalOutputAmount, newTotalFee, pickAdditionalUtxo);
345
+ }
346
+ }
347
+ if (isChangeOutputNeeded) {
348
+ if (changeOutputAmount.compare(changeOutputCost.minOutputAmount) < 0) {
349
+ // computed change amount would be below minUtxoValue
350
+ // set change output amount to met minimum requirements for minUtxoValue
351
+ changeOutputAmount = changeOutputCost.minOutputAmount;
352
+ }
353
+ // TODO: changeOutputCost.output.amount().set_coin(changeOutputAmount)?
354
+ const txOutput = (0, exports.buildTxOutput)({
355
+ amount: changeOutputAmount.to_str(),
356
+ address: changeAddress,
357
+ assets: changeOutputAssets,
358
+ }, changeAddress);
359
+ // WARNING: It returns a change output also in a case where we don't have enough utxos to cover the output cost, but the change output is needed because it contains additional assets
360
+ return {
361
+ outputFee: changeOutputCost.outputFee,
362
+ minOutputAmount: changeOutputCost.minOutputAmount,
363
+ output: txOutput,
364
+ };
365
+ }
366
+ // Change output not needed
367
+ return null;
368
+ };
369
+ exports.prepareChangeOutput = prepareChangeOutput;
370
+ const getTxBuilder = (a = '44') => CardanoWasm.TransactionBuilder.new(CardanoWasm.TransactionBuilderConfigBuilder.new()
371
+ .fee_algo(CardanoWasm.LinearFee.new((0, exports.bigNumFromStr)(a), (0, exports.bigNumFromStr)('155381')))
372
+ .pool_deposit((0, exports.bigNumFromStr)('500000000'))
373
+ .key_deposit((0, exports.bigNumFromStr)('2000000'))
374
+ .coins_per_utxo_byte((0, exports.bigNumFromStr)(constants_1.CARDANO_PARAMS.COINS_PER_UTXO_BYTE))
375
+ .max_value_size(constants_1.CARDANO_PARAMS.MAX_VALUE_SIZE)
376
+ .max_tx_size(constants_1.CARDANO_PARAMS.MAX_TX_SIZE)
377
+ .build());
378
+ exports.getTxBuilder = getTxBuilder;
379
+ const getUnsatisfiedAssets = (selectedUtxos, outputs) => {
380
+ const assets = [];
381
+ outputs.forEach(output => {
382
+ if (output.assets.length > 0) {
383
+ const asset = output.assets[0];
384
+ const assetAmountInUtxos = (0, exports.getUtxoQuantity)(selectedUtxos, asset.unit);
385
+ if (assetAmountInUtxos.compare((0, exports.bigNumFromStr)(asset.quantity)) < 0) {
386
+ assets.push(asset.unit);
387
+ }
388
+ }
389
+ });
390
+ const lovelaceUtxo = (0, exports.getUtxoQuantity)(selectedUtxos, 'lovelace');
391
+ if (lovelaceUtxo.compare((0, exports.getOutputQuantity)(outputs, 'lovelace')) < 0) {
392
+ assets.push('lovelace');
393
+ }
394
+ return assets;
395
+ };
396
+ exports.getUnsatisfiedAssets = getUnsatisfiedAssets;
397
+ const getInitialUtxoSet = (utxos, maxOutput) => {
398
+ var _a, _b;
399
+ // Picks all utxos containing an asset on which the user requested to set maximum value
400
+ if (!maxOutput)
401
+ return {
402
+ used: [],
403
+ remaining: utxos,
404
+ };
405
+ const used = [];
406
+ const remaining = [];
407
+ const maxOutputAsset = (_b = (_a = maxOutput.assets[0]) === null || _a === void 0 ? void 0 : _a.unit) !== null && _b !== void 0 ? _b : 'lovelace';
408
+ // either all UTXOs will be used (send max for ADA output) or initial set of used utxos will contain all utxos containing given token
409
+ utxos.forEach(u => {
410
+ if (u.amount.find(a => a.unit === maxOutputAsset)) {
411
+ used.push(u);
412
+ }
413
+ else {
414
+ remaining.push(u);
415
+ }
416
+ });
417
+ return {
418
+ used,
419
+ remaining,
420
+ };
421
+ };
422
+ exports.getInitialUtxoSet = getInitialUtxoSet;
423
+ const setMaxOutput = (maxOutput, changeOutput) => {
424
+ var _a, _b, _c, _d;
425
+ const maxOutputAsset = (_b = (_a = maxOutput.assets[0]) === null || _a === void 0 ? void 0 : _a.unit) !== null && _b !== void 0 ? _b : 'lovelace';
426
+ let newMaxAmount = (0, exports.bigNumFromStr)('0');
427
+ const changeOutputAssets = (0, exports.multiAssetToArray)(changeOutput === null || changeOutput === void 0 ? void 0 : changeOutput.output.amount().multiasset());
428
+ if (maxOutputAsset === 'lovelace') {
429
+ // set maxOutput for ADA
430
+ if (changeOutput) {
431
+ newMaxAmount = changeOutput.output.amount().coin();
432
+ if (changeOutputAssets.length === 0) {
433
+ // we don't need the change output anymore
434
+ newMaxAmount = newMaxAmount.checked_add(changeOutput.outputFee);
435
+ changeOutput = null;
436
+ }
437
+ else {
438
+ newMaxAmount = newMaxAmount.clamped_sub(changeOutput.minOutputAmount);
439
+ const txOutput = CardanoWasm.TransactionOutput.new(changeOutput.output.address(), CardanoWasm.Value.new(newMaxAmount));
440
+ const minUtxoVal = CardanoWasm.min_ada_for_output(txOutput, constants_1.DATA_COST_PER_UTXO_BYTE);
441
+ if (newMaxAmount.compare(minUtxoVal) < 0) {
442
+ // the amount would be less than min required ADA
443
+ throw new errors_1.CoinSelectionError(constants_1.ERROR.UTXO_BALANCE_INSUFFICIENT);
444
+ }
445
+ }
446
+ }
447
+ maxOutput.amount = newMaxAmount.to_str();
448
+ }
449
+ else {
450
+ // set maxOutput for token
451
+ if (changeOutput) {
452
+ // max amount of the asset in output is equal to its quantity in change output
453
+ newMaxAmount = (0, exports.bigNumFromStr)((_d = (_c = changeOutputAssets.find(a => a.unit === maxOutputAsset)) === null || _c === void 0 ? void 0 : _c.quantity) !== null && _d !== void 0 ? _d : '0');
454
+ maxOutput.assets[0].quantity = newMaxAmount.to_str(); // TODO: set 0 if no change?
455
+ const txOutput = CardanoWasm.TransactionOutput.new(changeOutput.output.address(),
456
+ // new_from_assets does not automatically include required ADA
457
+ CardanoWasm.Value.new_from_assets((0, exports.buildMultiAsset)(maxOutput.assets)));
458
+ // adjust ADA amount to cover min ada for the asset
459
+ maxOutput.amount = CardanoWasm.min_ada_for_output(txOutput, constants_1.DATA_COST_PER_UTXO_BYTE).to_str();
460
+ }
461
+ }
462
+ return { maxOutput };
463
+ };
464
+ exports.setMaxOutput = setMaxOutput;
465
+ const getUserOutputQuantityWithDeposit = (outputs, deposit, asset = 'lovelace') => {
466
+ let amount = (0, exports.getOutputQuantity)(outputs, asset);
467
+ if (deposit > 0) {
468
+ amount = amount.checked_add((0, exports.bigNumFromStr)(deposit.toString()));
469
+ }
470
+ return amount;
471
+ };
472
+ exports.getUserOutputQuantityWithDeposit = getUserOutputQuantityWithDeposit;
473
+ const filterUtxos = (utxos, asset) => {
474
+ return utxos.filter(utxo => utxo.amount.find(a => a.unit === asset));
475
+ };
476
+ exports.filterUtxos = filterUtxos;
477
+ const getRandomUtxo = (txBuilder, utxoRemaining, utxoSelected) => {
478
+ const index = Math.floor(Math.random() * utxoRemaining.length);
479
+ const utxo = utxoRemaining[index];
480
+ if (!utxo)
481
+ return null;
482
+ return {
483
+ utxo,
484
+ addUtxo: () => {
485
+ utxoSelected.push(utxo);
486
+ const { input, address, amount } = (0, exports.buildTxInput)(utxo);
487
+ txBuilder.add_input(address, input, amount);
488
+ utxoRemaining.splice(utxoRemaining.indexOf(utxo), 1);
489
+ },
490
+ };
491
+ };
492
+ exports.getRandomUtxo = getRandomUtxo;
493
+ const calculateUserOutputsFee = (txBuilder, userOutputs, changeAddress) => {
494
+ // Calculate fee and minUtxoValue for all external outputs
495
+ const outputsCost = userOutputs.map(output => (0, exports.getOutputCost)(txBuilder, output, changeAddress));
496
+ const totalOutputsFee = outputsCost.reduce((acc, output) => (acc = acc.checked_add(output.outputFee)), (0, exports.bigNumFromStr)('0'));
497
+ return totalOutputsFee;
498
+ };
499
+ exports.calculateUserOutputsFee = calculateUserOutputsFee;
500
+ const orderInputs = (inputsToOrder, txBody) => {
501
+ // reorder inputs to match order within tx
502
+ const orderedInputs = [];
503
+ for (let i = 0; i < txBody.inputs().len(); i++) {
504
+ const txid = Buffer.from(txBody.inputs().get(i).transaction_id().to_bytes()).toString('hex');
505
+ const outputIndex = txBody.inputs().get(i).index();
506
+ const utxo = inputsToOrder.find(uu => uu.txHash === txid && uu.outputIndex === outputIndex);
507
+ if (!utxo) {
508
+ throw new Error('Failed to order the utxos to match the order of inputs in constructed tx. THIS SHOULD NOT HAPPEN');
509
+ }
510
+ orderedInputs.push(utxo);
511
+ }
512
+ return orderedInputs;
513
+ };
514
+ exports.orderInputs = orderInputs;
@@ -0,0 +1,8 @@
1
+ import { ERROR } from '../constants';
2
+ declare type ErrorTypeKeys = keyof typeof ERROR;
3
+ declare type ErrorObjectType = typeof ERROR[ErrorTypeKeys];
4
+ export declare class CoinSelectionError extends Error {
5
+ code: ErrorObjectType['code'];
6
+ constructor(errorObject: ErrorObjectType);
7
+ }
8
+ export {};
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CoinSelectionError = void 0;
4
+ class CoinSelectionError extends Error {
5
+ constructor(errorObject) {
6
+ super(errorObject.message);
7
+ this.name = 'CoinSelectionError';
8
+ this.code = errorObject.code;
9
+ this.message = errorObject.message;
10
+ Object.setPrototypeOf(this, CoinSelectionError.prototype);
11
+ }
12
+ }
13
+ exports.CoinSelectionError = CoinSelectionError;
@@ -0,0 +1,5 @@
1
+ interface Logger {
2
+ debug: (...args: unknown[]) => void;
3
+ }
4
+ export declare const getLogger: (debug: boolean) => Logger;
5
+ export {};
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getLogger = void 0;
4
+ const myFormat = ({ level, args, label, timestamp, }) => {
5
+ if (timestamp) {
6
+ return [`${timestamp} [${label}] ${level}:`, ...args];
7
+ }
8
+ return [`[${label}] ${level}:`, ...args];
9
+ };
10
+ const getLogger = (debug) => {
11
+ const label = '@fivebinaries/coin-selection';
12
+ return {
13
+ debug: (...args) => {
14
+ if (!debug)
15
+ return;
16
+ const formattedMessage = myFormat({
17
+ level: 'DEBUG',
18
+ args: args,
19
+ // timestamp: new Date().toISOString(),
20
+ timestamp: undefined,
21
+ label,
22
+ });
23
+ console.log(...formattedMessage);
24
+ },
25
+ };
26
+ };
27
+ exports.getLogger = getLogger;
@@ -0,0 +1,14 @@
1
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
+ import { IAdaAmount, IAdaUTXO, IChangeAddress, IEncodedTxADA } from './types';
3
+ export declare const assetsToValue: (assets: IAdaAmount[]) => Promise<CardanoWasm.Value>;
4
+ export declare const extractKeyHash: (address: string) => Promise<string>;
5
+ export declare const dAppUtils: {
6
+ getBalance: (balances: IAdaAmount[]) => Promise<string>;
7
+ getAddresses: (addresses: string[]) => Promise<string[]>;
8
+ getUtxos: (address: string, utxos: IAdaUTXO[], amount?: string) => Promise<string[] | null | undefined>;
9
+ convertCborTxToEncodeTx: (txHex: string, utxos: IAdaUTXO[], addresses: string[], changeAddress: IChangeAddress) => Promise<IEncodedTxADA>;
10
+ signData: (address: string, payload: string, xprv: string, accountIndex: number) => Promise<{
11
+ signature: string;
12
+ key: string;
13
+ }>;
14
+ };