|
| 1 | +/* eslint-disable max-params */ |
| 2 | +import { Cardano, coalesceValueQuantities } from '@cardano-sdk/core'; |
| 3 | +import { InputSelectionError, InputSelectionFailure } from '../InputSelectionError'; |
| 4 | +import { InputSelectionParameters, InputSelector, SelectionConstraints, SelectionResult } from '../types'; |
| 5 | +import { |
| 6 | + addTokenMaps, |
| 7 | + getCoinQuantity, |
| 8 | + hasNegativeAssetValue, |
| 9 | + sortByCoins, |
| 10 | + stubMaxSizeAddress, |
| 11 | + subtractTokenMaps, |
| 12 | + toValues |
| 13 | +} from '../util'; |
| 14 | +import { splitChange } from './util'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Greedy selection initialization properties. |
| 18 | + */ |
| 19 | +export interface GreedySelectorProps { |
| 20 | + /** |
| 21 | + * Callback that returns a map of addresses with their intended proportions expressed as weights. |
| 22 | + * |
| 23 | + * The weight is an integer, and relative to other weights in the map. For example, a map with two addresses and |
| 24 | + * respective weights of 1 and 2 means that we expect the selector to assign twice more change to the second address |
| 25 | + * than the first. This means that for every 3 Ada, 1 Ada should go to the first address, and 2 Ada should go to |
| 26 | + * the second. |
| 27 | + * |
| 28 | + * If the same distribution is needed for each address use the same weight (e.g. 1). |
| 29 | + * |
| 30 | + * This selector will create N change outputs at this change addresses with the given proportions. |
| 31 | + */ |
| 32 | + getChangeAddresses: () => Promise<Map<Cardano.PaymentAddress, number>>; |
| 33 | +} |
| 34 | + |
| 35 | +/** |
| 36 | + * Given a set of input and outputs, compute the fee. Then extract the fee from the change output |
| 37 | + * with the highest value. |
| 38 | + * |
| 39 | + * @param changeLovelace The available amount of lovelace to be used as change. |
| 40 | + * @param constraints The selection constraints. |
| 41 | + * @param inputs The inputs of the transaction. |
| 42 | + * @param outputs The outputs of the transaction. |
| 43 | + * @param changeOutputs The list of change outputs. |
| 44 | + * @param currentFee The current computed fee for this selection. |
| 45 | + */ |
| 46 | +const adjustOutputsForFee = async ( |
| 47 | + changeLovelace: bigint, |
| 48 | + constraints: SelectionConstraints, |
| 49 | + inputs: Set<Cardano.Utxo>, |
| 50 | + outputs: Set<Cardano.TxOut>, |
| 51 | + changeOutputs: Array<Cardano.TxOut>, |
| 52 | + currentFee: bigint |
| 53 | +): Promise<{ fee: bigint; change: Array<Cardano.TxOut> }> => { |
| 54 | + const totalOutputs = new Set([...outputs, ...changeOutputs]); |
| 55 | + const fee = await constraints.computeMinimumCost({ |
| 56 | + change: [], |
| 57 | + fee: currentFee, |
| 58 | + inputs, |
| 59 | + outputs: totalOutputs |
| 60 | + }); |
| 61 | + |
| 62 | + if (fee === changeLovelace) return { change: [], fee }; |
| 63 | + |
| 64 | + if (changeLovelace < fee) throw new InputSelectionError(InputSelectionFailure.UtxoBalanceInsufficient); |
| 65 | + |
| 66 | + const updatedOutputs = [...changeOutputs]; |
| 67 | + |
| 68 | + updatedOutputs.sort(sortByCoins); |
| 69 | + |
| 70 | + let feeAccountedFor = false; |
| 71 | + for (const output of updatedOutputs) { |
| 72 | + const adjustedCoins = output.value.coins - fee; |
| 73 | + |
| 74 | + if (adjustedCoins >= constraints.computeMinimumCoinQuantity(output)) { |
| 75 | + output.value.coins = adjustedCoins; |
| 76 | + feeAccountedFor = true; |
| 77 | + break; |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + if (!feeAccountedFor) { |
| 82 | + throw new InputSelectionError(InputSelectionFailure.UtxoFullyDepleted); |
| 83 | + } |
| 84 | + |
| 85 | + return { change: [...updatedOutputs], fee }; |
| 86 | +}; |
| 87 | + |
| 88 | +/** |
| 89 | + * Recursively compute the fee and compute change outputs until it finds a set of change outputs that satisfies the fee. |
| 90 | + * |
| 91 | + * @param inputs The inputs of the transaction. |
| 92 | + * @param outputs The outputs of the transaction. |
| 93 | + * @param changeLovelace The total amount of lovelace in the change. |
| 94 | + * @param changeAssets The total assets to be distributed as change. |
| 95 | + * @param constraints The selection constraints. |
| 96 | + * @param getChangeAddresses A callback that returns a list of addresses and their proportions. |
| 97 | + * @param fee The current computed fee for this selection. |
| 98 | + */ |
| 99 | +const splitChangeAndComputeFee = async ( |
| 100 | + inputs: Set<Cardano.Utxo>, |
| 101 | + outputs: Set<Cardano.TxOut>, |
| 102 | + changeLovelace: bigint, |
| 103 | + changeAssets: Cardano.TokenMap | undefined, |
| 104 | + constraints: SelectionConstraints, |
| 105 | + getChangeAddresses: () => Promise<Map<Cardano.PaymentAddress, number>>, |
| 106 | + fee: bigint |
| 107 | +): Promise<{ fee: bigint; change: Array<Cardano.TxOut> }> => { |
| 108 | + const changeOutputs = await splitChange( |
| 109 | + getChangeAddresses, |
| 110 | + changeLovelace, |
| 111 | + changeAssets, |
| 112 | + constraints.computeMinimumCoinQuantity, |
| 113 | + constraints.tokenBundleSizeExceedsLimit, |
| 114 | + fee |
| 115 | + ); |
| 116 | + |
| 117 | + const adjustedChangeOutputs = await adjustOutputsForFee( |
| 118 | + changeLovelace, |
| 119 | + constraints, |
| 120 | + inputs, |
| 121 | + outputs, |
| 122 | + changeOutputs, |
| 123 | + fee |
| 124 | + ); |
| 125 | + |
| 126 | + // If the newly computed fee is higher than tha available balance for change, |
| 127 | + // but there are unallocated native assets, return the assets as change with 0n coins. |
| 128 | + if (adjustedChangeOutputs.fee >= changeLovelace) { |
| 129 | + return { |
| 130 | + change: [ |
| 131 | + { |
| 132 | + address: stubMaxSizeAddress, |
| 133 | + value: { |
| 134 | + assets: changeAssets, |
| 135 | + coins: 0n |
| 136 | + } |
| 137 | + } |
| 138 | + ], |
| 139 | + fee: adjustedChangeOutputs.fee |
| 140 | + }; |
| 141 | + } |
| 142 | + |
| 143 | + if (fee < adjustedChangeOutputs.fee) { |
| 144 | + return splitChangeAndComputeFee( |
| 145 | + inputs, |
| 146 | + outputs, |
| 147 | + changeLovelace, |
| 148 | + changeAssets, |
| 149 | + constraints, |
| 150 | + getChangeAddresses, |
| 151 | + adjustedChangeOutputs.fee |
| 152 | + ); |
| 153 | + } |
| 154 | + |
| 155 | + return adjustedChangeOutputs; |
| 156 | +}; |
| 157 | + |
| 158 | +/** |
| 159 | + * Selects all UTXOs to fulfill the amount required for the given outputs and return the remaining balance |
| 160 | + * as change. |
| 161 | + */ |
| 162 | +export class GreedyInputSelector implements InputSelector { |
| 163 | + #props: GreedySelectorProps; |
| 164 | + |
| 165 | + constructor(props: GreedySelectorProps) { |
| 166 | + this.#props = props; |
| 167 | + } |
| 168 | + |
| 169 | + async select(params: InputSelectionParameters): Promise<SelectionResult> { |
| 170 | + const { utxo: inputs, outputs, constraints, implicitValue } = params; |
| 171 | + const utxoValues = toValues([...inputs]); |
| 172 | + const outputsValues = toValues([...outputs]); |
| 173 | + const totalLovelaceInUtxoSet = getCoinQuantity(utxoValues); |
| 174 | + const totalLovelaceInOutputSet = getCoinQuantity(outputsValues); |
| 175 | + const totalAssetsInUtxoSet = coalesceValueQuantities(utxoValues).assets; |
| 176 | + const totalAssetsInOutputSet = coalesceValueQuantities(outputsValues).assets; |
| 177 | + const implicitCoinInput = implicitValue?.coin?.input || 0n; |
| 178 | + const implicitCoinOutput = implicitValue?.coin?.deposit || 0n; |
| 179 | + const implicitAssetInput = implicitValue?.mint || new Map<Cardano.AssetId, bigint>(); |
| 180 | + const totalLovelaceInput = totalLovelaceInUtxoSet + implicitCoinInput; |
| 181 | + const totalLovelaceOutput = totalLovelaceInOutputSet + implicitCoinOutput; |
| 182 | + const totalAssetsInput = addTokenMaps(totalAssetsInUtxoSet, implicitAssetInput); |
| 183 | + |
| 184 | + const changeLovelace = totalLovelaceInput - totalLovelaceOutput; |
| 185 | + const changeAssets = subtractTokenMaps(totalAssetsInput, totalAssetsInOutputSet); |
| 186 | + |
| 187 | + if (inputs.size === 0 || totalLovelaceOutput > totalLovelaceInput || hasNegativeAssetValue(changeAssets)) |
| 188 | + throw new InputSelectionError(InputSelectionFailure.UtxoBalanceInsufficient); |
| 189 | + |
| 190 | + const adjustedChangeOutputs = await splitChangeAndComputeFee( |
| 191 | + inputs, |
| 192 | + outputs, |
| 193 | + changeLovelace, |
| 194 | + changeAssets, |
| 195 | + constraints, |
| 196 | + this.#props.getChangeAddresses, |
| 197 | + 0n |
| 198 | + ); |
| 199 | + |
| 200 | + const change = adjustedChangeOutputs.change.filter( |
| 201 | + (out) => out.value.coins > 0n || (out.value.assets?.size || 0) > 0 |
| 202 | + ); |
| 203 | + |
| 204 | + if (changeLovelace - adjustedChangeOutputs.fee < 0n) |
| 205 | + throw new InputSelectionError(InputSelectionFailure.UtxoBalanceInsufficient); |
| 206 | + |
| 207 | + if ( |
| 208 | + inputs.size > |
| 209 | + (await constraints.computeSelectionLimit({ change, fee: adjustedChangeOutputs.fee, inputs, outputs })) |
| 210 | + ) { |
| 211 | + throw new InputSelectionError(InputSelectionFailure.MaximumInputCountExceeded); |
| 212 | + } |
| 213 | + |
| 214 | + return { |
| 215 | + remainingUTxO: new Set<Cardano.Utxo>(), // This input selection always consumes all inputs. |
| 216 | + selection: { |
| 217 | + change, |
| 218 | + fee: adjustedChangeOutputs.fee, |
| 219 | + inputs, |
| 220 | + outputs |
| 221 | + } |
| 222 | + }; |
| 223 | + } |
| 224 | +} |
0 commit comments