|
| 1 | +/* eslint-disable sonarjs/no-duplicate-string */ |
| 2 | +import * as Crypto from '@cardano-sdk/crypto'; |
| 3 | +import { AddressType, Bip32Account, GroupedAddress, InMemoryKeyAgent, util } from '@cardano-sdk/key-management'; |
| 4 | +import { Cardano } from '@cardano-sdk/core'; |
| 5 | +import { GenericTxBuilder, OutputValidation, RewardAccountWithPoolId, TxBuilderProviders } from '../../src'; |
| 6 | +import { |
| 7 | + GreedyInputSelector, |
| 8 | + InputSelectionError, |
| 9 | + InputSelectionFailure, |
| 10 | + LargeFirstSelector, |
| 11 | + roundRobinRandomImprove |
| 12 | +} from '@cardano-sdk/input-selection'; |
| 13 | +import { dummyLogger } from 'ts-log'; |
| 14 | +import { mockTxEvaluator } from './mocks'; |
| 15 | +import { mockProviders as mocks } from '@cardano-sdk/util-dev'; |
| 16 | +import uniqBy from 'lodash/uniqBy.js'; |
| 17 | + |
| 18 | +const largeFirstSelectSpy = jest.spyOn(LargeFirstSelector.prototype, 'select'); |
| 19 | + |
| 20 | +jest.mock('@cardano-sdk/input-selection', () => { |
| 21 | + const actual = jest.requireActual('@cardano-sdk/input-selection'); |
| 22 | + return { |
| 23 | + ...actual, |
| 24 | + roundRobinRandomImprove: jest.fn((args) => actual.roundRobinRandomImprove(args)) |
| 25 | + }; |
| 26 | +}); |
| 27 | + |
| 28 | +const inputResolver: Cardano.InputResolver = { |
| 29 | + resolveInput: async (txIn) => |
| 30 | + mocks.utxo.find(([hydratedTxIn]) => txIn.txId === hydratedTxIn.txId && txIn.index === hydratedTxIn.index)?.[1] || |
| 31 | + null |
| 32 | +}; |
| 33 | + |
| 34 | +/** Utility factory for tests to create a GenericTxBuilder with mocked dependencies */ |
| 35 | +const createTxBuilder = async ({ |
| 36 | + adjustRewardAccount = (r) => r, |
| 37 | + stakeDelegations, |
| 38 | + numAddresses = stakeDelegations.length, |
| 39 | + useMultiplePaymentKeys = false, |
| 40 | + rewardAccounts, |
| 41 | + keyAgent |
| 42 | +}: { |
| 43 | + adjustRewardAccount?: (rewardAccountWithPoolId: RewardAccountWithPoolId, index: number) => RewardAccountWithPoolId; |
| 44 | + stakeDelegations: { |
| 45 | + credentialStatus: Cardano.StakeCredentialStatus; |
| 46 | + poolId?: Cardano.PoolId; |
| 47 | + deposit?: Cardano.Lovelace; |
| 48 | + }[]; |
| 49 | + numAddresses?: number; |
| 50 | + useMultiplePaymentKeys?: boolean; |
| 51 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 52 | + rewardAccounts?: any; |
| 53 | + keyAgent: InMemoryKeyAgent; |
| 54 | +}) => { |
| 55 | + let groupedAddresses = await Promise.all( |
| 56 | + Array.from({ length: numAddresses }).map(async (_, idx) => |
| 57 | + keyAgent.deriveAddress({ index: 0, type: AddressType.External }, idx) |
| 58 | + ) |
| 59 | + ); |
| 60 | + |
| 61 | + // Simulate an HD wallet where a each stake key partitions 2 payment keys (2 addresses per stake key) |
| 62 | + if (useMultiplePaymentKeys) { |
| 63 | + const groupedAddresses2 = await Promise.all( |
| 64 | + stakeDelegations.map(async (_, idx) => keyAgent.deriveAddress({ index: 1, type: AddressType.External }, idx)) |
| 65 | + ); |
| 66 | + groupedAddresses = [...groupedAddresses, ...groupedAddresses2]; |
| 67 | + } |
| 68 | + |
| 69 | + const txBuilderProviders: jest.Mocked<TxBuilderProviders> = { |
| 70 | + addresses: { |
| 71 | + add: jest.fn().mockImplementation((...addreses) => groupedAddresses.push(...addreses)), |
| 72 | + get: jest.fn().mockResolvedValue(groupedAddresses) |
| 73 | + }, |
| 74 | + genesisParameters: jest.fn().mockResolvedValue(mocks.genesisParameters), |
| 75 | + protocolParameters: jest.fn().mockResolvedValue(mocks.protocolParameters), |
| 76 | + rewardAccounts: |
| 77 | + rewardAccounts || |
| 78 | + jest.fn().mockImplementation(() => |
| 79 | + Promise.resolve( |
| 80 | + // There can be multiple addresses with the same reward account. Extract the uniq reward accounts |
| 81 | + uniqBy(groupedAddresses, ({ rewardAccount }) => rewardAccount) |
| 82 | + // Create mock stakeKey/delegation status for each reward account according to the requested stakeDelegations. |
| 83 | + // This would normally be done by the wallet.delegation.rewardAccounts |
| 84 | + .map<RewardAccountWithPoolId>(({ rewardAccount: address }, index) => { |
| 85 | + const { credentialStatus, poolId, deposit } = stakeDelegations[index] ?? {}; |
| 86 | + return adjustRewardAccount( |
| 87 | + { |
| 88 | + address, |
| 89 | + credentialStatus: credentialStatus ?? Cardano.StakeCredentialStatus.Unregistered, |
| 90 | + dRepDelegatee: { |
| 91 | + delegateRepresentative: { |
| 92 | + __typename: 'AlwaysAbstain' |
| 93 | + } |
| 94 | + }, |
| 95 | + rewardBalance: mocks.rewardAccountBalance, |
| 96 | + ...(poolId ? { delegatee: { nextNextEpoch: { id: poolId } } } : undefined), |
| 97 | + ...(deposit && { deposit }) |
| 98 | + }, |
| 99 | + index |
| 100 | + ); |
| 101 | + }) |
| 102 | + ) |
| 103 | + ), |
| 104 | + tip: jest.fn().mockResolvedValue(mocks.ledgerTip), |
| 105 | + utxoAvailable: jest.fn().mockResolvedValue(mocks.utxo) |
| 106 | + }; |
| 107 | + const outputValidator = { |
| 108 | + validateOutput: jest.fn().mockResolvedValue({ coinMissing: 0n } as OutputValidation) |
| 109 | + }; |
| 110 | + const asyncKeyAgent = util.createAsyncKeyAgent(keyAgent); |
| 111 | + return { |
| 112 | + groupedAddresses, |
| 113 | + txBuilder: new GenericTxBuilder({ |
| 114 | + bip32Account: await Bip32Account.fromAsyncKeyAgent(asyncKeyAgent), |
| 115 | + inputResolver, |
| 116 | + logger: dummyLogger, |
| 117 | + outputValidator, |
| 118 | + txBuilderProviders, |
| 119 | + txEvaluator: mockTxEvaluator, |
| 120 | + witnesser: util.createBip32Ed25519Witnesser(asyncKeyAgent) |
| 121 | + }), |
| 122 | + txBuilderProviders, |
| 123 | + txBuilderWithoutBip32Account: new GenericTxBuilder({ |
| 124 | + inputResolver, |
| 125 | + logger: dummyLogger, |
| 126 | + outputValidator, |
| 127 | + txBuilderProviders, |
| 128 | + txEvaluator: mockTxEvaluator, |
| 129 | + witnesser: util.createBip32Ed25519Witnesser(asyncKeyAgent) |
| 130 | + }) |
| 131 | + }; |
| 132 | +}; |
| 133 | + |
| 134 | +describe('TxBuilder/inputSelectorFallback', () => { |
| 135 | + let txBuilder: GenericTxBuilder; |
| 136 | + let keyAgent: InMemoryKeyAgent; |
| 137 | + let groupedAddresses: GroupedAddress[]; |
| 138 | + |
| 139 | + beforeEach(async () => { |
| 140 | + keyAgent = await InMemoryKeyAgent.fromBip39MnemonicWords( |
| 141 | + { |
| 142 | + chainId: Cardano.ChainIds.Preprod, |
| 143 | + getPassphrase: async () => Buffer.from('passphrase'), |
| 144 | + mnemonicWords: util.generateMnemonicWords() |
| 145 | + }, |
| 146 | + { bip32Ed25519: await Crypto.SodiumBip32Ed25519.create(), logger: dummyLogger } |
| 147 | + ); |
| 148 | + |
| 149 | + const txBuilderFactory = await createTxBuilder({ |
| 150 | + keyAgent, |
| 151 | + stakeDelegations: [{ credentialStatus: Cardano.StakeCredentialStatus.Unregistered }] |
| 152 | + }); |
| 153 | + txBuilder = txBuilderFactory.txBuilder; |
| 154 | + groupedAddresses = txBuilderFactory.groupedAddresses; |
| 155 | + }); |
| 156 | + |
| 157 | + afterEach(() => jest.clearAllMocks()); |
| 158 | + |
| 159 | + it('uses random improve by default', async () => { |
| 160 | + const tx = await txBuilder.addOutput(mocks.utxo[0][1]).build().inspect(); |
| 161 | + |
| 162 | + expect(tx.inputSelection.inputs.size).toBeGreaterThan(0); |
| 163 | + expect(tx.inputSelection.outputs.size).toBe(1); |
| 164 | + expect(tx.inputSelection.change.length).toBeGreaterThan(0); |
| 165 | + expect(roundRobinRandomImprove).toHaveBeenCalled(); |
| 166 | + expect(largeFirstSelectSpy).not.toHaveBeenCalled(); |
| 167 | + }); |
| 168 | + |
| 169 | + const fallbackFailures = [ |
| 170 | + InputSelectionFailure.MaximumInputCountExceeded, |
| 171 | + InputSelectionFailure.UtxoFullyDepleted, |
| 172 | + InputSelectionFailure.UtxoNotFragmentedEnough |
| 173 | + ] as const; |
| 174 | + |
| 175 | + it.each(fallbackFailures)('falls back to large first when random improve throws', async (failure) => { |
| 176 | + (roundRobinRandomImprove as jest.Mock).mockImplementationOnce(() => { |
| 177 | + throw new InputSelectionError(failure); |
| 178 | + }); |
| 179 | + |
| 180 | + const tx = await txBuilder.addOutput(mocks.utxo[0][1]).build().inspect(); |
| 181 | + |
| 182 | + expect(tx.inputSelection.inputs.size).toBeGreaterThan(0); |
| 183 | + expect(tx.inputSelection.outputs.size).toBe(1); |
| 184 | + expect(tx.inputSelection.change.length).toBeGreaterThan(0); |
| 185 | + |
| 186 | + expect(roundRobinRandomImprove).toHaveBeenCalled(); |
| 187 | + expect(largeFirstSelectSpy).toHaveBeenCalled(); |
| 188 | + }); |
| 189 | + |
| 190 | + it.each(fallbackFailures)('only retries once with large first when random improve throws %s', async (failure) => { |
| 191 | + (roundRobinRandomImprove as jest.Mock).mockImplementationOnce(() => { |
| 192 | + throw new InputSelectionError(failure); |
| 193 | + }); |
| 194 | + |
| 195 | + largeFirstSelectSpy.mockImplementationOnce(async () => { |
| 196 | + throw new InputSelectionError(failure); |
| 197 | + }); |
| 198 | + |
| 199 | + await expect(txBuilder.addOutput(mocks.utxo[0][1]).build().inspect()).rejects.toThrow(failure); |
| 200 | + expect(roundRobinRandomImprove).toHaveBeenCalledTimes(1); |
| 201 | + expect(largeFirstSelectSpy).toHaveBeenCalledTimes(1); |
| 202 | + }); |
| 203 | + |
| 204 | + it('does not fallback to large first when random improve throws UtxoBalanceInsufficient input selection error', async () => { |
| 205 | + (roundRobinRandomImprove as jest.Mock).mockImplementationOnce(() => { |
| 206 | + throw new InputSelectionError(InputSelectionFailure.UtxoBalanceInsufficient); |
| 207 | + }); |
| 208 | + |
| 209 | + await expect(txBuilder.addOutput(mocks.utxo[0][1]).build().inspect()).rejects.toThrow('UTxO Balance Insufficient'); |
| 210 | + expect(roundRobinRandomImprove).toHaveBeenCalled(); |
| 211 | + expect(largeFirstSelectSpy).not.toHaveBeenCalled(); |
| 212 | + }); |
| 213 | + |
| 214 | + it('does not fallback to large first when using greedy input selector', async () => { |
| 215 | + const poolIds: Cardano.PoolId[] = [ |
| 216 | + Cardano.PoolId('pool1zuevzm3xlrhmwjw87ec38mzs02tlkwec9wxpgafcaykmwg7efhh'), |
| 217 | + Cardano.PoolId('pool1t9xlrjyk76c96jltaspgwcnulq6pdkmhnge8xgza8ku7qvpsy9r') |
| 218 | + ]; |
| 219 | + |
| 220 | + jest.spyOn(GreedyInputSelector.prototype, 'select').mockImplementationOnce(async () => { |
| 221 | + throw new InputSelectionError(InputSelectionFailure.MaximumInputCountExceeded); |
| 222 | + }); |
| 223 | + |
| 224 | + const output = { address: groupedAddresses[0].address, value: { coins: 10n } }; |
| 225 | + await expect( |
| 226 | + txBuilder |
| 227 | + .delegatePortfolio({ |
| 228 | + name: 'Tests Portfolio', |
| 229 | + pools: [ |
| 230 | + { |
| 231 | + id: Cardano.PoolIdHex(Cardano.PoolId.toKeyHash(poolIds[0])), |
| 232 | + weight: 1 |
| 233 | + }, |
| 234 | + { |
| 235 | + id: Cardano.PoolIdHex(Cardano.PoolId.toKeyHash(poolIds[1])), |
| 236 | + weight: 2 |
| 237 | + } |
| 238 | + ] |
| 239 | + }) |
| 240 | + .addOutput(txBuilder.buildOutput(output).toTxOut()) |
| 241 | + .build() |
| 242 | + .inspect() |
| 243 | + ).rejects.toThrow('Maximum Input Count Exceeded'); |
| 244 | + expect(roundRobinRandomImprove).not.toHaveBeenCalled(); |
| 245 | + expect(largeFirstSelectSpy).not.toHaveBeenCalled(); |
| 246 | + }); |
| 247 | +}); |
0 commit comments