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