-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtransaction.ts
More file actions
333 lines (291 loc) · 9.81 KB
/
transaction.ts
File metadata and controls
333 lines (291 loc) · 9.81 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import {
BaseKey,
BaseTransaction,
InvalidTransactionError,
PublicKey,
Signature,
TransactionRecipient,
TransactionType,
} from '@bitgo/sdk-core';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import {
TransactionData as IotaTransactionData,
Transaction as IotaTransaction,
TransactionDataBuilder as IotaTransactionDataBuilder,
} from '@iota/iota-sdk/transactions';
import { TxData, TransactionObjectInput, TransactionExplanation } from './iface';
import { toBase64 } from '@iota/iota-sdk/utils';
import blake2b from '@bitgo/blake2b';
import {
MAX_GAS_BUDGET,
MAX_GAS_PAYMENT_OBJECTS,
MAX_GAS_PRICE,
IOTA_KEY_BYTES_LENGTH,
IOTA_SIGNATURE_LENGTH,
} from './constants';
export abstract class Transaction extends BaseTransaction {
static EMPTY_PUBLIC_KEY = Buffer.alloc(IOTA_KEY_BYTES_LENGTH);
static EMPTY_SIGNATURE = Buffer.alloc(IOTA_SIGNATURE_LENGTH);
protected _rebuildRequired: boolean;
protected _type: TransactionType;
protected _iotaTransaction: IotaTransaction;
private _gasBudget?: number;
private _gasPaymentObjects?: TransactionObjectInput[];
private _gasPrice?: number;
private _gasSponsor?: string;
private _sender: string;
private _signature?: Signature;
private _gasSponsorSignature?: Signature;
private _txDataBytes?: Uint8Array<ArrayBufferLike>;
private _isSimulateTx: boolean;
protected constructor(coinConfig: Readonly<CoinConfig>) {
super(coinConfig);
this._sender = '';
this._rebuildRequired = false;
this._isSimulateTx = true;
this._signature = {
publicKey: {
pub: Transaction.EMPTY_PUBLIC_KEY.toString('hex'),
},
signature: Transaction.EMPTY_SIGNATURE,
};
}
get gasBudget(): number | undefined {
return this._gasBudget;
}
set gasBudget(value: number | undefined) {
this._gasBudget = value;
this._rebuildRequired = true;
}
get gasPaymentObjects(): TransactionObjectInput[] | undefined {
return this._gasPaymentObjects;
}
set gasPaymentObjects(value: TransactionObjectInput[] | undefined) {
this._gasPaymentObjects = value;
this._rebuildRequired = true;
}
get gasPrice(): number | undefined {
return this._gasPrice;
}
set gasPrice(value: number | undefined) {
this._gasPrice = value;
this._rebuildRequired = true;
}
get gasSponsor(): string | undefined {
return this._gasSponsor;
}
set gasSponsor(value: string | undefined) {
this._gasSponsor = value;
this._rebuildRequired = true;
}
get sender(): string {
return this._sender;
}
set sender(value: string) {
this._sender = value;
this._rebuildRequired = true;
}
get isSimulateTx(): boolean {
return this._isSimulateTx;
}
set isSimulateTx(value: boolean) {
if (!value) {
try {
this.validateTxData();
this._rebuildRequired = true;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
throw new Error(`Tx data validation failed: ${errorMessage}. {Cause: ${error}}`);
}
}
this._isSimulateTx = value;
}
get signablePayload(): Buffer {
if (this.isSimulateTx) {
throw new Error('Cannot sign a simulate tx');
}
if (this._txDataBytes === undefined || this._rebuildRequired) {
throw new Error('Tx not built or a rebuild is required');
}
const intentMessage = this.messageWithIntent(this._txDataBytes);
return Buffer.from(blake2b(32).update(intentMessage).digest('binary'));
}
/** @inheritDoc **/
get id(): string {
if (this._txDataBytes === undefined || this._rebuildRequired) {
throw new Error('Tx not built or a rebuild is required');
}
return IotaTransactionDataBuilder.getDigestFromBytes(this._txDataBytes);
}
addSignature(publicKey: PublicKey, signature: Buffer): void {
this._signatures = [...this._signatures, signature.toString('hex')];
this._signature = { publicKey, signature };
}
addGasSponsorSignature(publicKey: PublicKey, signature: Buffer): void {
this._signatures = [...this._signatures, signature.toString('hex')];
this._gasSponsorSignature = { publicKey, signature };
}
canSign(_key: BaseKey): boolean {
return !this.isSimulateTx;
}
getFee(): string | undefined {
return this.gasBudget?.toString();
}
async toBroadcastFormat(): Promise<string> {
const txDataBytes: Uint8Array<ArrayBufferLike> = await this.build();
return toBase64(txDataBytes);
}
async build(): Promise<Uint8Array<ArrayBufferLike>> {
if (this.isSimulateTx) {
return this.buildDryRunTransaction();
}
return this.buildTransaction();
}
toJson(): TxData {
return {
sender: this.sender,
gasBudget: this.gasBudget,
gasPrice: this.gasPrice,
gasPaymentObjects: this.gasPaymentObjects,
gasSponsor: this.gasSponsor,
type: this.type,
};
}
parseFromJSON(txData: TxData): void {
this.sender = txData.sender;
this.gasBudget = txData.gasBudget;
this.gasPrice = txData.gasPrice;
this.gasPaymentObjects = txData.gasPaymentObjects;
if (txData.gasSponsor !== undefined) {
this.gasSponsor = txData.gasSponsor;
}
}
parseFromBroadcastTx(tx: string | Uint8Array): void {
const txData = IotaTransaction.from(tx).getData();
if (txData.sender) {
this.sender = txData.sender;
}
if (txData.gasData?.budget) {
this.gasBudget = Number(txData.gasData.budget);
} else {
this.gasBudget = undefined;
}
if (txData.gasData?.price) {
this.gasPrice = Number(txData.gasData.price);
} else {
this.gasPrice = undefined;
}
if (txData.gasData?.payment && txData.gasData.payment.length > 0) {
this.gasPaymentObjects = txData.gasData.payment.map((payment) => payment as TransactionObjectInput);
} else {
this.gasPaymentObjects = undefined;
}
if (txData.gasData?.owner) {
this.gasSponsor = txData.gasData.owner;
} else {
this.gasSponsor = undefined;
}
}
/**
* @inheritDoc
*/
explainTransaction(): any {
const result = this.toJson();
const displayOrder = ['id', 'outputs', 'outputAmount', 'changeOutputs', 'changeAmount', 'fee', 'type'];
const outputs: TransactionRecipient[] = [];
const explanationResult: TransactionExplanation = {
displayOrder,
id: this.id,
outputs,
outputAmount: '0',
changeOutputs: [],
changeAmount: '0',
fee: { fee: this.gasBudget ? this.gasBudget.toString() : '' },
sender: this.sender,
sponsor: this.gasSponsor,
type: this.type,
};
return this.explainTransactionImplementation(result, explanationResult);
}
protected updateIsSimulateTx(): void {
if (this.gasBudget && this.gasPrice && this.gasPaymentObjects && this.gasPaymentObjects?.length > 0) {
this.isSimulateTx = false;
} else {
this.isSimulateTx = true;
}
}
protected abstract messageWithIntent(message: Uint8Array): Uint8Array;
protected abstract populateTxInputsAndCommands(): void;
protected abstract validateTxDataImplementation(): void;
/**
* Add the input and output entries for this transaction.
*/
abstract addInputsAndOutputs(): void;
/**
* Returns a complete explanation for a transfer transaction
* @param {TxData} json The transaction data in json format
* @param {TransactionExplanation} explanationResult The transaction explanation to be completed
* @returns {TransactionExplanation}
*/
protected abstract explainTransactionImplementation(
json: TxData,
explanationResult: TransactionExplanation
): TransactionExplanation;
private async buildDryRunTransaction(): Promise<Uint8Array<ArrayBufferLike>> {
this.validateTxDataImplementation();
await this.populateTxData();
const txDataBuilder = new IotaTransactionDataBuilder(this._iotaTransaction.getData() as IotaTransactionData);
return txDataBuilder.build({
overrides: {
gasData: {
budget: MAX_GAS_BUDGET.toString(),
price: MAX_GAS_PRICE.toString(),
payment: [],
},
},
});
}
private async buildTransaction(): Promise<Uint8Array<ArrayBufferLike>> {
if (this._txDataBytes === undefined || this._rebuildRequired) {
this.validateTxData();
await this.populateTxData();
this._iotaTransaction.setGasPrice(this.gasPrice as number);
this._iotaTransaction.setGasBudget(this.gasBudget as number);
this._iotaTransaction.setGasPayment(this.gasPaymentObjects as TransactionObjectInput[]);
this._txDataBytes = await this._iotaTransaction.build();
this._rebuildRequired = false;
}
return this._txDataBytes;
}
private async populateTxData(): Promise<void> {
this._iotaTransaction = new IotaTransaction();
this.populateTxInputsAndCommands();
if (this.gasSponsor && this._sender !== this.gasSponsor) {
this._iotaTransaction = IotaTransaction.fromKind(
await this._iotaTransaction.build({ onlyTransactionKind: true })
);
this._iotaTransaction.setGasOwner(this._gasSponsor as string);
}
this._iotaTransaction.setSender(this.sender);
}
private validateTxData(): void {
this.validateTxDataImplementation();
if (!this.sender || this.sender === '') {
throw new InvalidTransactionError('Transaction sender is required');
}
if (!this.gasPrice) {
throw new InvalidTransactionError('Gas price is required');
}
if (!this.gasBudget) {
throw new InvalidTransactionError('Gas budget is required');
}
if (!this.gasPaymentObjects || this.gasPaymentObjects?.length === 0) {
throw new InvalidTransactionError('Gas payment objects are required');
}
if (this.gasPaymentObjects.length > MAX_GAS_PAYMENT_OBJECTS) {
throw new InvalidTransactionError(
`Gas payment objects count (${this.gasPaymentObjects.length}) exceeds maximum allowed (${MAX_GAS_PAYMENT_OBJECTS})`
);
}
}
}