@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,69 @@
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.signTransaction = void 0;
27
+ const CardanoWasm = __importStar(require("@emurgo/cardano-serialization-lib-asmjs"));
28
+ const trezor_1 = require("../../types/trezor");
29
+ const common_1 = require("../common");
30
+ const signTransaction = (txBodyHex,
31
+ // txMetadata: CardanoWasm.AuxiliaryData,
32
+ signedWitnesses, options) => {
33
+ const txBody = CardanoWasm.TransactionBody.from_bytes(Uint8Array.from(Buffer.from(txBodyHex, 'hex')));
34
+ const witnesses = CardanoWasm.TransactionWitnessSet.new();
35
+ const vkeyWitnesses = CardanoWasm.Vkeywitnesses.new();
36
+ const bootstrapWitnesses = CardanoWasm.BootstrapWitnesses.new();
37
+ signedWitnesses.forEach(w => {
38
+ const vKey = CardanoWasm.Vkey.new(CardanoWasm.PublicKey.from_bytes(Buffer.from(w.pubKey, 'hex')));
39
+ const signature = CardanoWasm.Ed25519Signature.from_bytes(Buffer.from(w.signature, 'hex'));
40
+ if (w.type === trezor_1.CardanoTxWitnessType.SHELLEY_WITNESS) {
41
+ // Shelley witness
42
+ const vKeyWitness = CardanoWasm.Vkeywitness.new(vKey, signature);
43
+ vkeyWitnesses.add(vKeyWitness);
44
+ }
45
+ else if (w.type === trezor_1.CardanoTxWitnessType.BYRON_WITNESS) {
46
+ // Byron witness (TODO: not used, needs testing)
47
+ if (w.chainCode) {
48
+ const xpubHex = `${w.pubKey}${w.chainCode}`;
49
+ const bip32Key = CardanoWasm.Bip32PublicKey.from_bytes(Buffer.from(xpubHex, 'hex'));
50
+ const byronAddress = CardanoWasm.ByronAddress.icarus_from_key(bip32Key, (0, common_1.getProtocolMagic)(!!(options === null || options === void 0 ? void 0 : options.testnet)));
51
+ const bootstrapWitness = CardanoWasm.BootstrapWitness.new(vKey, signature, Buffer.from(w.chainCode, 'hex'), byronAddress.attributes());
52
+ bootstrapWitnesses.add(bootstrapWitness);
53
+ }
54
+ }
55
+ });
56
+ if (bootstrapWitnesses.len() > 0) {
57
+ witnesses.set_bootstraps(bootstrapWitnesses);
58
+ }
59
+ if (vkeyWitnesses.len() > 0) {
60
+ witnesses.set_vkeys(vkeyWitnesses);
61
+ }
62
+ if (options === null || options === void 0 ? void 0 : options.signOnly) {
63
+ return Promise.resolve(Buffer.from(witnesses.to_bytes(), 'utf8').toString('hex'));
64
+ }
65
+ const transaction = CardanoWasm.Transaction.new(txBody, witnesses);
66
+ const serializedTx = Buffer.from(transaction.to_bytes()).toString('hex');
67
+ return Promise.resolve(serializedTx);
68
+ };
69
+ exports.signTransaction = signTransaction;
@@ -0,0 +1,17 @@
1
+ import { CardanoAddressParameters, CardanoInput, CardanoOutput } from '../../types/trezor';
2
+ import { Asset, FinalOutput, Utxo } from '../../types/types';
3
+ interface AssetInPolicy {
4
+ assetNameBytes: string;
5
+ amount: string;
6
+ }
7
+ export declare const transformToTokenBundle: (assets: Asset[]) => {
8
+ policyId: string;
9
+ tokenAmounts: AssetInPolicy[];
10
+ }[] | undefined;
11
+ export declare const transformToTrezorInputs: (utxos: Utxo[], trezorUtxos: {
12
+ txid: string;
13
+ vout: number;
14
+ path: string;
15
+ }[]) => CardanoInput[];
16
+ export declare const transformToTrezorOutputs: (outputs: FinalOutput[], changeAddressParameters: CardanoAddressParameters) => CardanoOutput[];
17
+ export {};
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transformToTrezorOutputs = exports.transformToTrezorInputs = exports.transformToTokenBundle = void 0;
4
+ const common_1 = require("../common");
5
+ const transformToTokenBundle = (assets) => {
6
+ // prepare token bundle used in trezor output
7
+ if (assets.length === 0)
8
+ return undefined;
9
+ const uniquePolicies = [];
10
+ assets.forEach(asset => {
11
+ const { policyId } = (0, common_1.parseAsset)(asset.unit);
12
+ if (!uniquePolicies.includes(policyId)) {
13
+ uniquePolicies.push(policyId);
14
+ }
15
+ });
16
+ const assetsByPolicy = [];
17
+ uniquePolicies.forEach(policyId => {
18
+ const assetsInPolicy = [];
19
+ assets.forEach(asset => {
20
+ const assetInfo = (0, common_1.parseAsset)(asset.unit);
21
+ if (assetInfo.policyId !== policyId)
22
+ return;
23
+ assetsInPolicy.push({
24
+ assetNameBytes: assetInfo.assetNameInHex,
25
+ amount: asset.quantity,
26
+ });
27
+ }),
28
+ assetsByPolicy.push({
29
+ policyId,
30
+ tokenAmounts: assetsInPolicy,
31
+ });
32
+ });
33
+ return assetsByPolicy;
34
+ };
35
+ exports.transformToTokenBundle = transformToTokenBundle;
36
+ const transformToTrezorInputs = (utxos, trezorUtxos) => {
37
+ return utxos.map(utxo => {
38
+ const utxoWithPath = trezorUtxos.find(u => u.txid === utxo.txHash && u.vout === utxo.outputIndex);
39
+ // shouldn't happen since utxos should be subset of trezorUtxos (with different shape/fields)
40
+ if (!utxoWithPath)
41
+ throw Error(`Cannot transform utxo ${utxo.txHash}:${utxo.outputIndex}`);
42
+ return {
43
+ path: utxoWithPath.path,
44
+ prev_hash: utxo.txHash,
45
+ prev_index: utxo.outputIndex,
46
+ };
47
+ });
48
+ };
49
+ exports.transformToTrezorInputs = transformToTrezorInputs;
50
+ const transformToTrezorOutputs = (outputs, changeAddressParameters) => {
51
+ return outputs.map(output => {
52
+ let params;
53
+ if (output.isChange) {
54
+ params = {
55
+ addressParameters: changeAddressParameters,
56
+ };
57
+ }
58
+ else {
59
+ params = {
60
+ address: output.address,
61
+ };
62
+ }
63
+ return Object.assign(Object.assign({}, params), { amount: output.amount, tokenBundle: (0, exports.transformToTokenBundle)(output.assets) });
64
+ });
65
+ };
66
+ exports.transformToTrezorOutputs = transformToTrezorOutputs;
@@ -0,0 +1,40 @@
1
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
+ export declare const CertificateType: {
3
+ readonly STAKE_REGISTRATION: 0;
4
+ readonly STAKE_DEREGISTRATION: 1;
5
+ readonly STAKE_DELEGATION: 2;
6
+ readonly STAKE_POOL_REGISTRATION: 3;
7
+ };
8
+ export declare const ERROR: {
9
+ readonly UTXO_BALANCE_INSUFFICIENT: {
10
+ readonly code: "UTXO_BALANCE_INSUFFICIENT";
11
+ readonly message: "UTxO balance insufficient";
12
+ };
13
+ readonly UTXO_VALUE_TOO_SMALL: {
14
+ readonly code: "UTXO_VALUE_TOO_SMALL";
15
+ readonly message: "UTxO value too small";
16
+ };
17
+ readonly UNSUPPORTED_CERTIFICATE_TYPE: {
18
+ readonly code: "UNSUPPORTED_CERTIFICATE_TYPE";
19
+ readonly message: "Unsupported certificate type";
20
+ };
21
+ readonly UTXO_NOT_FRAGMENTED_ENOUGH: {
22
+ readonly code: "UTXO_NOT_FRAGMENTED_ENOUGH";
23
+ readonly message: "UTxO Not fragmented enough.";
24
+ };
25
+ };
26
+ export declare const CARDANO_PARAMS: {
27
+ readonly PROTOCOL_MAGICS: {
28
+ readonly mainnet: number;
29
+ readonly testnet: number;
30
+ };
31
+ readonly NETWORK_IDS: {
32
+ readonly mainnet: number;
33
+ readonly testnet: number;
34
+ };
35
+ readonly COINS_PER_UTXO_BYTE: "4310";
36
+ readonly MAX_TX_SIZE: 16384;
37
+ readonly MAX_VALUE_SIZE: 5000;
38
+ };
39
+ export declare const MAX_TOKENS_PER_OUTPUT = 50;
40
+ export declare const DATA_COST_PER_UTXO_BYTE: CardanoWasm.DataCost;
@@ -0,0 +1,43 @@
1
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
2
+ export const CertificateType = {
3
+ STAKE_REGISTRATION: 0,
4
+ STAKE_DEREGISTRATION: 1,
5
+ STAKE_DELEGATION: 2,
6
+ STAKE_POOL_REGISTRATION: 3,
7
+ };
8
+ export const ERROR = {
9
+ UTXO_BALANCE_INSUFFICIENT: {
10
+ code: 'UTXO_BALANCE_INSUFFICIENT',
11
+ message: 'UTxO balance insufficient',
12
+ },
13
+ UTXO_VALUE_TOO_SMALL: {
14
+ code: 'UTXO_VALUE_TOO_SMALL',
15
+ message: 'UTxO value too small',
16
+ },
17
+ UNSUPPORTED_CERTIFICATE_TYPE: {
18
+ code: 'UNSUPPORTED_CERTIFICATE_TYPE',
19
+ message: 'Unsupported certificate type',
20
+ },
21
+ UTXO_NOT_FRAGMENTED_ENOUGH: {
22
+ code: 'UTXO_NOT_FRAGMENTED_ENOUGH',
23
+ message: 'UTxO Not fragmented enough.',
24
+ },
25
+ };
26
+ export const CARDANO_PARAMS = {
27
+ PROTOCOL_MAGICS: {
28
+ mainnet: CardanoWasm.NetworkInfo.mainnet().protocol_magic(),
29
+ testnet: CardanoWasm.NetworkInfo.testnet().protocol_magic(),
30
+ },
31
+ NETWORK_IDS: {
32
+ mainnet: CardanoWasm.NetworkInfo.mainnet().network_id(),
33
+ testnet: CardanoWasm.NetworkInfo.testnet().network_id(),
34
+ },
35
+ COINS_PER_UTXO_BYTE: '4310',
36
+ MAX_TX_SIZE: 16384,
37
+ MAX_VALUE_SIZE: 5000,
38
+ };
39
+ // https://github.com/vacuumlabs/adalite/blob/d8ba3bb1ff439ae8e02abd99163435a989d97961/app/frontend/wallet/shelley/transaction/constants.ts
40
+ // policyId is 28 bytes, assetName max 32 bytes, together with quantity makes
41
+ // max token size about 70 bytes, max output size is 4000 => 4000 / 70 ~ 50
42
+ export const MAX_TOKENS_PER_OUTPUT = 50;
43
+ export const DATA_COST_PER_UTXO_BYTE = CardanoWasm.DataCost.new_coins_per_byte(CardanoWasm.BigNum.from_str(CARDANO_PARAMS.COINS_PER_UTXO_BYTE));
@@ -0,0 +1,6 @@
1
+ import { CoinSelectionParams, Options, PrecomposedTransaction } from './types/types';
2
+ export declare const coinSelection: (params: CoinSelectionParams, options?: Options) => PrecomposedTransaction;
3
+ export * as types from './types/types';
4
+ export * as trezorUtils from './utils/trezor';
5
+ export { onekeyUtils, dAppUtils } from './utils/onekey';
6
+ export { CoinSelectionError } from './utils/errors';
@@ -0,0 +1,73 @@
1
+ import { ERROR } from './constants';
2
+ import { largestFirst } from './methods/largestFirst';
3
+ import { randomImprove } from './methods/randomImprove';
4
+ import { CoinSelectionError } from './utils/errors';
5
+ import { getLogger } from './utils/logger';
6
+ import { bigNumFromStr } from './utils/common';
7
+ export const coinSelection = (params, options) => {
8
+ const logger = getLogger(!!(options === null || options === void 0 ? void 0 : options.debug));
9
+ logger.debug('Args:', {
10
+ params,
11
+ options,
12
+ });
13
+ if (params.utxos.length === 0) {
14
+ logger.debug('Empty Utxo set');
15
+ throw new CoinSelectionError(ERROR.UTXO_BALANCE_INSUFFICIENT);
16
+ }
17
+ const t1 = new Date().getTime();
18
+ let res;
19
+ if (params.outputs.find(o => o.setMax) ||
20
+ params.certificates.length > 0 ||
21
+ params.withdrawals.length > 0 ||
22
+ (options === null || options === void 0 ? void 0 : options.forceLargestFirstSelection)) {
23
+ logger.debug('Running largest-first alg');
24
+ res = largestFirst(params, options);
25
+ }
26
+ else {
27
+ logger.debug('Running random-improve alg');
28
+ try {
29
+ res = randomImprove(params, options);
30
+ }
31
+ catch (error) {
32
+ if (error instanceof CoinSelectionError &&
33
+ error.code === 'UTXO_NOT_FRAGMENTED_ENOUGH') {
34
+ logger.debug(`random-improve failed with ${error.code}. Retrying with largest-first alg.`);
35
+ res = largestFirst(params, options);
36
+ }
37
+ else {
38
+ throw error;
39
+ }
40
+ }
41
+ }
42
+ const t2 = new Date().getTime();
43
+ logger.debug(`Duration: ${(t2 - t1) / 1000} seconds`);
44
+ const incompleteOutputs = res.outputs.find(o => !o.address ||
45
+ !o.amount ||
46
+ // assets set with quantity = 0
47
+ (o.assets.length > 0 &&
48
+ o.assets.find(a => !a.quantity ||
49
+ bigNumFromStr(a.quantity).compare(bigNumFromStr('0')) === 0)));
50
+ if (incompleteOutputs) {
51
+ const selection = {
52
+ type: 'nonfinal',
53
+ fee: res.fee,
54
+ totalSpent: res.totalSpent,
55
+ deposit: res.deposit,
56
+ withdrawal: res.withdrawal,
57
+ max: res.max,
58
+ };
59
+ logger.debug('Coin selection for a draft transaction:', selection);
60
+ return selection;
61
+ }
62
+ else {
63
+ const selection = Object.assign(Object.assign({ type: 'final' }, res), { outputs: res.outputs });
64
+ logger.debug('Coin selection for a final transaction:', selection);
65
+ return selection;
66
+ }
67
+ };
68
+ import * as types_1 from './types/types';
69
+ export { types_1 as types };
70
+ import * as trezorUtils_1 from './utils/trezor';
71
+ export { trezorUtils_1 as trezorUtils };
72
+ export { onekeyUtils, dAppUtils } from './utils/onekey';
73
+ export { CoinSelectionError } from './utils/errors';
@@ -0,0 +1,2 @@
1
+ import { CoinSelectionParams, CoinSelectionResult, Options } from '../types/types';
2
+ export declare const largestFirst: (params: CoinSelectionParams, options?: Options) => CoinSelectionResult;
@@ -0,0 +1,174 @@
1
+ import { ERROR } from '../constants';
2
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
3
+ import { bigNumFromStr, calculateRequiredDeposit, getAssetAmount, prepareCertificates, prepareChangeOutput, prepareWithdrawals, setMinUtxoValueForOutputs, sortUtxos, getTxBuilder, getInitialUtxoSet, setMaxOutput, getUserOutputQuantityWithDeposit, multiAssetToArray, buildTxInput, buildTxOutput, getUnsatisfiedAssets, splitChangeOutput, calculateUserOutputsFee, orderInputs, } from '../utils/common';
4
+ import { CoinSelectionError } from '../utils/errors';
5
+ export const largestFirst = (params, options) => {
6
+ var _a;
7
+ const { utxos, outputs, changeAddress, certificates, withdrawals, accountPubKey, ttl, } = params;
8
+ const txBuilder = getTxBuilder((_a = options === null || options === void 0 ? void 0 : options.feeParams) === null || _a === void 0 ? void 0 : _a.a);
9
+ if (ttl) {
10
+ txBuilder.set_ttl(ttl);
11
+ }
12
+ const usedUtxos = [];
13
+ let sortedUtxos = sortUtxos(utxos);
14
+ const accountKey = CardanoWasm.Bip32PublicKey.from_bytes(Buffer.from(accountPubKey, 'hex'));
15
+ // add withdrawals and certs to correctly set a fee
16
+ const preparedCertificates = prepareCertificates(certificates, accountKey);
17
+ const preparedWithdrawals = prepareWithdrawals(withdrawals);
18
+ if (preparedCertificates.len() > 0) {
19
+ txBuilder.set_certs(preparedCertificates);
20
+ }
21
+ if (preparedWithdrawals.len() > 0) {
22
+ txBuilder.set_withdrawals(preparedWithdrawals);
23
+ }
24
+ // TODO: negative value in case of deregistration (-2000000), but we still need enough utxos to cover fee which can't be (is that right?) paid from returned deposit
25
+ const deposit = calculateRequiredDeposit(certificates);
26
+ const totalWithdrawal = withdrawals.reduce((acc, withdrawal) => acc.checked_add(bigNumFromStr(withdrawal.amount)), bigNumFromStr('0'));
27
+ // calc initial fee
28
+ let totalFeesAmount = txBuilder.min_fee();
29
+ let utxosTotalAmount = totalWithdrawal;
30
+ if (deposit < 0) {
31
+ // stake deregistration, 2 ADA returned
32
+ utxosTotalAmount = utxosTotalAmount.checked_add(bigNumFromStr(Math.abs(deposit).toString()));
33
+ }
34
+ const preparedOutputs = setMinUtxoValueForOutputs(txBuilder, outputs, changeAddress);
35
+ const addUtxoToSelection = (utxo) => {
36
+ const { input, address, amount } = buildTxInput(utxo);
37
+ const fee = txBuilder.fee_for_input(address, input, amount);
38
+ txBuilder.add_input(address, input, amount);
39
+ usedUtxos.push(utxo);
40
+ totalFeesAmount = totalFeesAmount.checked_add(fee);
41
+ utxosTotalAmount = utxosTotalAmount.checked_add(bigNumFromStr(getAssetAmount(utxo)));
42
+ };
43
+ // set initial utxos set for setMax functionality
44
+ const maxOutputIndex = outputs.findIndex(o => !!o.setMax);
45
+ const maxOutput = preparedOutputs[maxOutputIndex];
46
+ const { used, remaining } = getInitialUtxoSet(sortedUtxos, maxOutput);
47
+ sortedUtxos = remaining;
48
+ used.forEach(utxo => addUtxoToSelection(utxo));
49
+ // add cost of external outputs to total fee amount
50
+ totalFeesAmount = totalFeesAmount.checked_add(calculateUserOutputsFee(txBuilder, preparedOutputs, changeAddress));
51
+ let totalUserOutputsAmount = getUserOutputQuantityWithDeposit(preparedOutputs, deposit);
52
+ let changeOutput = null;
53
+ let sufficientUtxos = false;
54
+ let forceAnotherRound = false;
55
+ while (!sufficientUtxos) {
56
+ if (maxOutput) {
57
+ // reset previously computed maxOutput in order to correctly calculate a potential change output
58
+ preparedOutputs[maxOutputIndex] = setMinUtxoValueForOutputs(txBuilder, [maxOutput], changeAddress)[0];
59
+ }
60
+ // Calculate change output
61
+ let singleChangeOutput = prepareChangeOutput(txBuilder, usedUtxos, preparedOutputs, changeAddress, utxosTotalAmount, getUserOutputQuantityWithDeposit(preparedOutputs, deposit), totalFeesAmount);
62
+ if (maxOutput) {
63
+ // set amount for a max output from a changeOutput calculated above
64
+ const { maxOutput: newMaxOutput } = setMaxOutput(maxOutput, singleChangeOutput);
65
+ // change output may be completely removed if all ADA are consumed by max output
66
+ preparedOutputs[maxOutputIndex] = newMaxOutput;
67
+ // recalculate total user outputs amount
68
+ totalUserOutputsAmount = getUserOutputQuantityWithDeposit(preparedOutputs, deposit);
69
+ // recalculate fees for outputs as cost for max output may be larger than before
70
+ totalFeesAmount = txBuilder
71
+ .min_fee()
72
+ .checked_add(calculateUserOutputsFee(txBuilder, preparedOutputs, changeAddress));
73
+ // recalculate change after setting amount to max output
74
+ singleChangeOutput = prepareChangeOutput(txBuilder, usedUtxos, preparedOutputs, changeAddress, utxosTotalAmount, getUserOutputQuantityWithDeposit(preparedOutputs, deposit), totalFeesAmount);
75
+ }
76
+ const changeOutputs = singleChangeOutput
77
+ ? splitChangeOutput(txBuilder, singleChangeOutput, changeAddress, options === null || options === void 0 ? void 0 : options._maxTokensPerOutput)
78
+ : [];
79
+ let requiredAmount = totalFeesAmount.checked_add(totalUserOutputsAmount);
80
+ changeOutputs.forEach(changeOutput => {
81
+ // we need to cover amounts and fees for change outputs
82
+ requiredAmount = requiredAmount
83
+ .checked_add(changeOutput.output.amount().coin())
84
+ .checked_add(changeOutput.outputFee);
85
+ });
86
+ // List of tokens for which we don't have enough utxos
87
+ const unsatisfiedAssets = getUnsatisfiedAssets(usedUtxos, preparedOutputs);
88
+ if (utxosTotalAmount.compare(requiredAmount) >= 0 &&
89
+ unsatisfiedAssets.length === 0 &&
90
+ usedUtxos.length > 0 && // TODO: force at least 1 utxo, otherwise withdrawal tx is composed without utxo if rewards > tx cost
91
+ !forceAnotherRound) {
92
+ // we are done. we have enough utxos to cover fees + minUtxoValue for each output. now we can add the cost of the change output to total fees
93
+ if (changeOutputs.length > 0) {
94
+ changeOutputs.forEach(changeOutput => {
95
+ totalFeesAmount = totalFeesAmount.checked_add(changeOutput.outputFee);
96
+ });
97
+ // set change output
98
+ changeOutput = changeOutputs.map(change => ({
99
+ isChange: true,
100
+ amount: change.output.amount().coin().to_str(),
101
+ address: changeAddress,
102
+ assets: multiAssetToArray(change.output.amount().multiasset()),
103
+ }));
104
+ }
105
+ else {
106
+ if (sortedUtxos.length > 0) {
107
+ // In current iteration we don't have enough utxo to meet min utxo value for an output,
108
+ // but some utxos are still available, force adding another one in order to create a change output
109
+ forceAnotherRound = true;
110
+ continue;
111
+ }
112
+ // Change output would be inefficient., we can burn its value + fee we would pay for it
113
+ const unspendableChangeAmount = utxosTotalAmount.clamped_sub(totalFeesAmount.checked_add(totalUserOutputsAmount));
114
+ totalFeesAmount = totalFeesAmount.checked_add(unspendableChangeAmount);
115
+ }
116
+ sufficientUtxos = true;
117
+ }
118
+ else {
119
+ if (unsatisfiedAssets.length > 0) {
120
+ // TODO: https://github.com/Emurgo/cardano-serialization-lib/pull/264
121
+ sortedUtxos = sortUtxos(sortedUtxos, unsatisfiedAssets[0]);
122
+ }
123
+ else {
124
+ sortedUtxos = sortUtxos(sortedUtxos);
125
+ }
126
+ const utxo = sortedUtxos.shift();
127
+ if (!utxo)
128
+ break;
129
+ addUtxoToSelection(utxo);
130
+ forceAnotherRound = false;
131
+ }
132
+ // END LOOP
133
+ }
134
+ if (!sufficientUtxos) {
135
+ throw new CoinSelectionError(ERROR.UTXO_BALANCE_INSUFFICIENT);
136
+ }
137
+ preparedOutputs.forEach(output => {
138
+ const txOutput = buildTxOutput(output, changeAddress);
139
+ txBuilder.add_output(txOutput);
140
+ });
141
+ const finalOutputs = JSON.parse(JSON.stringify(preparedOutputs));
142
+ if (changeOutput) {
143
+ changeOutput.forEach(change => {
144
+ finalOutputs.push(change);
145
+ txBuilder.add_output(buildTxOutput(change, changeAddress));
146
+ });
147
+ }
148
+ txBuilder.set_fee(totalFeesAmount);
149
+ const txBody = txBuilder.build();
150
+ const txHash = Buffer.from(CardanoWasm.hash_transaction(txBody).to_bytes()).toString('hex');
151
+ const txBodyHex = Buffer.from(txBody.to_bytes()).toString('hex');
152
+ const totalSpent = totalUserOutputsAmount.checked_add(totalFeesAmount);
153
+ // Set max property with the value of an output which has setMax=true
154
+ let max;
155
+ if (maxOutput) {
156
+ max =
157
+ maxOutput.assets.length > 0
158
+ ? maxOutput.assets[0].quantity
159
+ : maxOutput.amount;
160
+ }
161
+ // reorder inputs to match order within tx
162
+ const orderedInputs = orderInputs(usedUtxos, txBody);
163
+ return {
164
+ tx: { body: txBodyHex, hash: txHash, size: txBuilder.full_size() },
165
+ inputs: orderedInputs,
166
+ outputs: finalOutputs,
167
+ fee: totalFeesAmount.to_str(),
168
+ totalSpent: totalSpent.to_str(),
169
+ deposit: deposit.toString(),
170
+ withdrawal: totalWithdrawal.to_str(),
171
+ ttl,
172
+ max,
173
+ };
174
+ };
@@ -0,0 +1,2 @@
1
+ import { CoinSelectionParams, CoinSelectionResult, Options } from '../types/types';
2
+ export declare const randomImprove: (params: Pick<CoinSelectionParams, 'utxos' | 'outputs' | 'changeAddress' | 'ttl'>, options?: Options) => CoinSelectionResult;
@@ -0,0 +1,160 @@
1
+ import { ERROR } from '../constants';
2
+ import * as CardanoWasm from '@emurgo/cardano-serialization-lib-asmjs';
3
+ import { bigNumFromStr, prepareChangeOutput, setMinUtxoValueForOutputs, getTxBuilder, getUserOutputQuantityWithDeposit, multiAssetToArray, buildTxInput, buildTxOutput, getUnsatisfiedAssets, splitChangeOutput, filterUtxos, getUtxoQuantity, getOutputQuantity, getRandomUtxo, orderInputs, } from '../utils/common';
4
+ import { CoinSelectionError } from '../utils/errors';
5
+ import { getLogger } from '../utils/logger';
6
+ // Heavily inspired by https://github.com/input-output-hk/cardano-js-sdk
7
+ const improvesSelection = (utxoAlreadySelected, input, minimumTarget, asset) => {
8
+ const oldQuantity = getUtxoQuantity(utxoAlreadySelected, asset);
9
+ // We still haven't reached the minimum target of
10
+ // 100%. Therefore, we consider any potential input
11
+ // to be an improvement:
12
+ if (oldQuantity.compare(minimumTarget) < 0)
13
+ return true;
14
+ const newQuantity = oldQuantity.checked_add(getUtxoQuantity([input], asset));
15
+ const idealTarget = minimumTarget.checked_mul(bigNumFromStr('2'));
16
+ const newDistance = idealTarget.compare(newQuantity) > 0
17
+ ? idealTarget.clamped_sub(newQuantity)
18
+ : newQuantity.clamped_sub(idealTarget);
19
+ const oldDistance = idealTarget.compare(oldQuantity) > 0
20
+ ? idealTarget.clamped_sub(oldQuantity)
21
+ : oldQuantity.clamped_sub(idealTarget);
22
+ // Using this input will move us closer to the
23
+ // ideal target of 200%, so we treat this as an improvement:
24
+ if (newDistance.compare(oldDistance) < 0)
25
+ return true;
26
+ // Adding the selected input would move us further
27
+ // away from the target of 200%. Reaching this case
28
+ // means we have already covered the minimum target
29
+ // of 100%, and therefore it is safe to not consider
30
+ // this token any further:
31
+ return false;
32
+ };
33
+ const selection = (utxos, outputs, txBuilder, dummyAddress) => {
34
+ const utxoSelected = [];
35
+ const utxoRemaining = JSON.parse(JSON.stringify(utxos));
36
+ const preparedOutputs = setMinUtxoValueForOutputs(txBuilder, outputs, dummyAddress);
37
+ preparedOutputs.forEach(output => {
38
+ const txOutput = buildTxOutput(output, dummyAddress);
39
+ txBuilder.add_output(txOutput);
40
+ });
41
+ // Check for UTXO_BALANCE_INSUFFICIENT comparing provided inputs with requested outputs
42
+ const assetsRemaining = getUnsatisfiedAssets(utxoSelected, preparedOutputs);
43
+ assetsRemaining.forEach(asset => {
44
+ const outputQuantity = getOutputQuantity(preparedOutputs, asset);
45
+ const utxosQuantity = getUtxoQuantity(utxos, asset);
46
+ if (outputQuantity.compare(utxosQuantity) > 0) {
47
+ throw new CoinSelectionError(ERROR.UTXO_BALANCE_INSUFFICIENT);
48
+ }
49
+ });
50
+ while (assetsRemaining.length > 0) {
51
+ assetsRemaining.forEach((asset, assetIndex) => {
52
+ const assetUtxos = filterUtxos(utxoRemaining, asset);
53
+ if (assetUtxos.length > 0) {
54
+ const inputIdx = Math.floor(Math.random() * assetUtxos.length);
55
+ const utxo = assetUtxos[inputIdx];
56
+ if (improvesSelection(utxoSelected, utxo, getOutputQuantity(preparedOutputs, asset), asset)) {
57
+ utxoSelected.push(utxo);
58
+ const { input, address, amount } = buildTxInput(utxo);
59
+ txBuilder.add_input(address, input, amount);
60
+ utxoRemaining.splice(utxoRemaining.indexOf(utxo), 1);
61
+ }
62
+ else {
63
+ // The selection was not improved by including
64
+ // this input. If we've reached this point, it
65
+ // means that we've already covered the minimum
66
+ // target of 100%, and therefore it is safe to
67
+ // not consider this token any further.
68
+ assetsRemaining.splice(assetIndex, 1);
69
+ }
70
+ }
71
+ else {
72
+ // The attempt to select an input failed (there were
73
+ // no inputs remaining that contained the token).
74
+ // This means that we've already covered the minimum
75
+ // quantity required (due to the pre-condition), and
76
+ // therefore it is safe to not consider this token
77
+ // any further:
78
+ assetsRemaining.splice(assetIndex, 1);
79
+ }
80
+ });
81
+ }
82
+ return { utxoSelected, utxoRemaining, preparedOutputs };
83
+ };
84
+ const calculateChange = (utxoSelected, utxoRemaining, preparedOutputs, changeAddress, maxTokensPerOutput, txBuilder) => {
85
+ const totalFeesAmount = txBuilder.min_fee();
86
+ const totalUserOutputsAmount = getUserOutputQuantityWithDeposit(preparedOutputs, 0);
87
+ const singleChangeOutput = prepareChangeOutput(txBuilder, utxoSelected, preparedOutputs, changeAddress, getUtxoQuantity(utxoSelected, 'lovelace'), getUserOutputQuantityWithDeposit(preparedOutputs, 0), totalFeesAmount, () => getRandomUtxo(txBuilder, utxoRemaining, utxoSelected));
88
+ const changeOutputs = singleChangeOutput
89
+ ? splitChangeOutput(txBuilder, singleChangeOutput, changeAddress, maxTokensPerOutput)
90
+ : [];
91
+ let requiredAmount = totalFeesAmount.checked_add(totalUserOutputsAmount);
92
+ changeOutputs.forEach(changeOutput => {
93
+ // we need to cover amounts and fees for change outputs
94
+ requiredAmount = requiredAmount
95
+ .checked_add(changeOutput.output.amount().coin())
96
+ .checked_add(changeOutput.outputFee);
97
+ });
98
+ if (requiredAmount.compare(getUtxoQuantity(utxoSelected, 'lovelace')) > 0) {
99
+ const randomUtxo = getRandomUtxo(txBuilder, utxoRemaining, utxoSelected);
100
+ if (randomUtxo === null || randomUtxo === void 0 ? void 0 : randomUtxo.utxo) {
101
+ randomUtxo.addUtxo();
102
+ const { changeOutputs } = calculateChange(utxoSelected, utxoRemaining, preparedOutputs, changeAddress, maxTokensPerOutput, txBuilder);
103
+ return { changeOutputs };
104
+ }
105
+ else {
106
+ throw new CoinSelectionError(ERROR.UTXO_BALANCE_INSUFFICIENT);
107
+ }
108
+ }
109
+ else {
110
+ return { changeOutputs };
111
+ }
112
+ };
113
+ export const randomImprove = (params, options) => {
114
+ var _a;
115
+ const { utxos, outputs, changeAddress, ttl } = params;
116
+ const logger = getLogger(!!(options === null || options === void 0 ? void 0 : options.debug));
117
+ if (outputs.length > utxos.length) {
118
+ logger.debug('There are more outputs than utxos. Random-improve alg needs to have number of utxos same or larger than number of outputs');
119
+ throw new CoinSelectionError(ERROR.UTXO_NOT_FRAGMENTED_ENOUGH);
120
+ }
121
+ const txBuilder = getTxBuilder((_a = options === null || options === void 0 ? void 0 : options.feeParams) === null || _a === void 0 ? void 0 : _a.a);
122
+ if (ttl) {
123
+ txBuilder.set_ttl(ttl);
124
+ }
125
+ const { utxoSelected, utxoRemaining, preparedOutputs } = selection(utxos, outputs, txBuilder, changeAddress);
126
+ // compute change and adjust for fee
127
+ const { changeOutputs } = calculateChange(utxoSelected, utxoRemaining, preparedOutputs, changeAddress, options === null || options === void 0 ? void 0 : options._maxTokensPerOutput, txBuilder);
128
+ const finalOutputs = JSON.parse(JSON.stringify(preparedOutputs));
129
+ changeOutputs.forEach(change => {
130
+ const ch = {
131
+ isChange: true,
132
+ amount: change.output.amount().coin().to_str(),
133
+ address: changeAddress,
134
+ assets: multiAssetToArray(change.output.amount().multiasset()),
135
+ };
136
+ finalOutputs.push(ch);
137
+ txBuilder.add_output(buildTxOutput(ch, changeAddress));
138
+ });
139
+ const totalUserOutputsAmount = getUserOutputQuantityWithDeposit(preparedOutputs, 0);
140
+ const totalInput = getUtxoQuantity(utxoSelected, 'lovelace');
141
+ const totalOutput = getOutputQuantity(finalOutputs, 'lovelace');
142
+ const fee = totalInput.checked_sub(totalOutput);
143
+ const totalSpent = totalUserOutputsAmount.checked_add(fee);
144
+ txBuilder.set_fee(fee);
145
+ const txBody = txBuilder.build();
146
+ const txHash = Buffer.from(CardanoWasm.hash_transaction(txBody).to_bytes()).toString('hex');
147
+ const txBodyHex = Buffer.from(txBody.to_bytes()).toString('hex');
148
+ // reorder inputs to match order within tx
149
+ const orderedInputs = orderInputs(utxoSelected, txBody);
150
+ return {
151
+ tx: { body: txBodyHex, hash: txHash, size: txBuilder.full_size() },
152
+ inputs: orderedInputs,
153
+ outputs: finalOutputs,
154
+ fee: fee.to_str(),
155
+ totalSpent: totalSpent.to_str(),
156
+ deposit: '0',
157
+ withdrawal: '0',
158
+ ttl,
159
+ };
160
+ };