-
Notifications
You must be signed in to change notification settings - Fork 54
/
OutputBuilder.ts
162 lines (138 loc) · 5.38 KB
/
OutputBuilder.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { Cardano, Handle, HandleProvider } from '@cardano-sdk/core';
import { Hash32ByteBase16 } from '@cardano-sdk/crypto';
import { Logger } from 'ts-log';
import {
InvalidConfigurationError,
OutputBuilder,
OutputBuilderTxOut,
OutputValidationMinimumCoinError,
OutputValidationMissingRequiredError,
OutputValidationTokenBundleSizeError,
TxOutputFailure,
PartialTxOut
} from './types';
import { OutputValidation, OutputValidator } from '../output-validation';
export type OutputBuilderValidator = Pick<OutputValidator, 'validateOutput'>;
/** Properties needed to construct a {@link TxOutputBuilder} */
export interface OutputBuilderProps {
/** This validator is normally created and passed as an arg here by the {@link TxBuilder.buildOutput} method */
outputValidator: OutputBuilderValidator;
/** Optional partial transaction output to use for initialization. */
txOut?: PartialTxOut;
/** Logger */
logger: Logger;
/** Handle Provider for resolving addresses */
handleProvider?: HandleProvider;
}
/** Determines if the `PartialTxOut` arg has at least an address and coins. */
const isViableTxOut = (txOut: PartialTxOut): txOut is Cardano.TxOut =>
!!((txOut?.address || txOut?.handle) && txOut?.value?.coins);
/**
* Transforms from `OutputValidation` type emitted by `OutputValidator`, to
* `OutputValidationMinimumCoinError` | `OutputValidationTokenBundleSizeError`
*/
const toOutputValidationError = (
txOut: Cardano.TxOut,
validation: OutputValidation
): OutputValidationMinimumCoinError | OutputValidationTokenBundleSizeError | undefined => {
if (validation.coinMissing) {
return new OutputValidationMinimumCoinError(txOut, validation);
}
if (validation.tokenBundleSizeExceedsLimit) {
return new OutputValidationTokenBundleSizeError(txOut, validation);
}
};
/**
* `OutputBuilder` implementation based on {@link OutputValidator}.
*/
export class TxOutputBuilder implements OutputBuilder {
/**
* Transaction output that is updated by `TxOutputBuilder` methods.
* Every method call recreates the `partialOutput`, thus updating it immutably.
*/
#partialOutput: PartialTxOut;
#outputValidator: OutputBuilderValidator;
#logger: Logger;
#handleProvider: HandleProvider | null = null;
constructor({ outputValidator, txOut, logger, handleProvider }: OutputBuilderProps) {
this.#partialOutput = { ...txOut };
this.#outputValidator = outputValidator;
this.#logger = logger;
if (handleProvider) {
this.#handleProvider = handleProvider;
}
}
/**
* Create transaction output snapshot, as it was configured until the point of calling this method.
*
* @returns {Cardano.TxOut} transaction output snapshot.
* - It can be used in {@link TxBuilder.addOutput}.
* - It will be validated once {@link TxBuilder.build} method is called.
* @throws OutputValidationMissingRequiredError {@link OutputValidationMissingRequiredError} if
* the mandatory fields 'address' or 'coins' are missing
*/
toTxOut(): OutputBuilderTxOut {
if (!isViableTxOut(this.#partialOutput)) {
throw new OutputValidationMissingRequiredError(this.#partialOutput);
}
this.#logger.debug('toTxOut result:', this.#partialOutput);
return { ...this.#partialOutput };
}
async inspect(): Promise<PartialTxOut> {
return this.#partialOutput;
}
value(value: Cardano.Value): OutputBuilder {
this.#partialOutput = { ...this.#partialOutput, value: { ...value } };
return this;
}
coin(coin: Cardano.Lovelace): OutputBuilder {
this.#partialOutput = { ...this.#partialOutput, value: { ...this.#partialOutput?.value, coins: coin } };
return this;
}
assets(assets: Cardano.TokenMap): OutputBuilder {
this.#partialOutput = {
...this.#partialOutput,
value: { ...this.#partialOutput?.value, assets }
};
return this;
}
asset(assetId: Cardano.AssetId, quantity: bigint): OutputBuilder {
const assets: Cardano.TokenMap = new Map(this.#partialOutput?.value?.assets);
quantity === 0n ? assets.delete(assetId) : assets.set(assetId, quantity);
return this.assets(assets);
}
address(address: Cardano.PaymentAddress): OutputBuilder {
this.#partialOutput = { ...this.#partialOutput, address };
return this;
}
datum(datumHash: Hash32ByteBase16): OutputBuilder {
this.#partialOutput = { ...this.#partialOutput, datumHash };
return this;
}
handle(handle: Handle): OutputBuilder {
if (!this.#handleProvider) {
throw new InvalidConfigurationError(TxOutputFailure.MissingHandleProviderError);
}
this.#partialOutput = { ...this.#partialOutput, handle };
return this;
}
async build(): Promise<OutputBuilderTxOut> {
const txOut = this.toTxOut();
const outputValidation = toOutputValidationError(txOut, await this.#outputValidator.validateOutput(txOut));
if (outputValidation) {
throw outputValidation;
}
if (this.#partialOutput.handle && this.#handleProvider) {
const resolution = await this.#handleProvider.resolveHandles({ handles: [this.#partialOutput.handle] });
if (resolution[0] !== null) {
txOut.handle = resolution[0];
txOut.address = resolution[0].resolvedAddresses.cardano;
} else {
// The an error because the handle resolved to null so we don't have
// an address for the transaction.
throw new OutputValidationMissingRequiredError(this.#partialOutput);
}
}
return txOut;
}
}