|
| 1 | +/** |
| 2 | + * Descriptor output types and utilities. |
| 3 | + * Moved from @bitgo/utxo-core. |
| 4 | + */ |
| 5 | +import { Descriptor } from "../index.js"; |
| 6 | + |
| 7 | +import { getFixedOutputSum, MaxOutput, Output, PrevOutput } from "./Output.js"; |
| 8 | +import { DescriptorMap } from "./DescriptorMap.js"; |
| 9 | +import { getDescriptorAtIndexCheckScript } from "./derive.js"; |
| 10 | + |
| 11 | +export type WithDescriptor<T> = T & { |
| 12 | + descriptor: Descriptor; |
| 13 | +}; |
| 14 | + |
| 15 | +export type WithOptDescriptor<T> = T & { |
| 16 | + descriptor?: Descriptor; |
| 17 | +}; |
| 18 | + |
| 19 | +export function isInternalOutput<T extends object>( |
| 20 | + output: T | WithDescriptor<T>, |
| 21 | +): output is WithDescriptor<T> { |
| 22 | + return "descriptor" in output && output.descriptor !== undefined; |
| 23 | +} |
| 24 | + |
| 25 | +export function isExternalOutput<T extends object>(output: T | WithDescriptor<T>): output is T { |
| 26 | + return !isInternalOutput(output); |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * @return the sum of the external outputs that are not 'max' |
| 31 | + * @param outputs |
| 32 | + */ |
| 33 | +export function getExternalFixedAmount(outputs: WithOptDescriptor<Output | MaxOutput>[]): bigint { |
| 34 | + return getFixedOutputSum(outputs.filter(isExternalOutput)); |
| 35 | +} |
| 36 | + |
| 37 | +export type DescriptorWalletOutput = PrevOutput & { |
| 38 | + descriptorName: string; |
| 39 | + descriptorIndex: number | undefined; |
| 40 | +}; |
| 41 | + |
| 42 | +export type DerivedDescriptorWalletOutput = WithDescriptor<PrevOutput>; |
| 43 | + |
| 44 | +export function toDerivedDescriptorWalletOutput( |
| 45 | + output: DescriptorWalletOutput, |
| 46 | + descriptorMap: DescriptorMap, |
| 47 | +): DerivedDescriptorWalletOutput { |
| 48 | + const descriptor = descriptorMap.get(output.descriptorName); |
| 49 | + if (!descriptor) { |
| 50 | + throw new Error(`Descriptor not found: ${output.descriptorName}`); |
| 51 | + } |
| 52 | + if (!(descriptor instanceof Descriptor)) { |
| 53 | + throw new Error(`Expected Descriptor instance for ${output.descriptorName}`); |
| 54 | + } |
| 55 | + const descriptorAtIndex = getDescriptorAtIndexCheckScript( |
| 56 | + descriptor, |
| 57 | + output.descriptorIndex, |
| 58 | + output.witnessUtxo.script, |
| 59 | + output.descriptorName, |
| 60 | + ); |
| 61 | + return { |
| 62 | + hash: output.hash, |
| 63 | + index: output.index, |
| 64 | + witnessUtxo: output.witnessUtxo, |
| 65 | + descriptor: descriptorAtIndex, |
| 66 | + }; |
| 67 | +} |
0 commit comments