-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtransaction.ts
More file actions
428 lines (372 loc) · 13.1 KB
/
transaction.ts
File metadata and controls
428 lines (372 loc) · 13.1 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import {
BaseKey,
BaseTransaction,
Entry,
InvalidTransactionError,
PublicKey,
Signature,
TransactionRecipient,
TransactionType,
} from '@bitgo/sdk-core';
import { logger } from '@bitgo/logger';
import { BaseCoin as CoinConfig, NetworkType } from '@bitgo/statics';
import {
AccountAddress,
AccountAuthenticator,
AccountAuthenticatorEd25519,
AccountAuthenticatorNoAccountAuthenticator,
Aptos,
AptosConfig,
DEFAULT_MAX_GAS_AMOUNT,
Ed25519PublicKey,
Ed25519Signature,
FeePayerRawTransaction,
generateSigningMessage,
generateUserTransactionHash,
Hex,
InputGenerateTransactionPayloadData,
Network,
RAW_TRANSACTION_SALT,
RAW_TRANSACTION_WITH_DATA_SALT,
RawTransaction,
SignedTransaction,
SimpleTransaction,
TransactionAuthenticatorFeePayer,
TransactionPayload,
} from '@aptos-labs/ts-sdk';
import { DEFAULT_GAS_UNIT_PRICE, UNAVAILABLE_TEXT } from '../constants';
import utils from '../utils';
import BigNumber from 'bignumber.js';
import { AptTransactionExplanation, TxData } from '../iface';
import assert from 'assert';
export type InputsAndOutputs = {
/** Used for this.inputs */
inputs: Entry[];
/** Used for this.outputs */
outputs: Entry[];
/** Used for this.explainTransaction() */
externalOutputs: TransactionRecipient[];
};
export abstract class Transaction extends BaseTransaction {
protected _rawTransaction: RawTransaction;
protected _senderSignature: Signature;
protected _feePayerSignature: Signature;
protected _sender: string;
protected _recipients: TransactionRecipient[];
protected _sequenceNumber: number;
protected _maxGasAmount: number;
protected _gasUnitPrice: number;
protected _gasUsed: number;
protected _expirationTime: number;
protected _feePayerAddress: string;
protected _assetId: string;
protected _isSimulateTxn: boolean;
static EMPTY_PUBLIC_KEY = Buffer.alloc(32);
static EMPTY_SIGNATURE = Buffer.alloc(64);
constructor(coinConfig: Readonly<CoinConfig>) {
super(coinConfig);
this._maxGasAmount = DEFAULT_MAX_GAS_AMOUNT;
this._gasUnitPrice = DEFAULT_GAS_UNIT_PRICE;
this._gasUsed = 0;
this._expirationTime = utils.getTxnExpirationTimestamp();
this._sequenceNumber = 0;
this._sender = AccountAddress.ZERO.toString();
this._recipients = [];
this._assetId = AccountAddress.ZERO.toString();
this._isSimulateTxn = false;
this._senderSignature = {
publicKey: {
pub: Hex.fromHexInput(Transaction.EMPTY_PUBLIC_KEY).toString(),
},
signature: Transaction.EMPTY_SIGNATURE,
};
this._feePayerAddress = AccountAddress.ZERO.toString();
this._feePayerSignature = {
publicKey: {
pub: Hex.fromHexInput(Transaction.EMPTY_PUBLIC_KEY).toString(),
},
signature: Transaction.EMPTY_SIGNATURE,
};
}
/** @inheritDoc **/
public override get id(): string {
this.generateTxnId();
return this._id ?? UNAVAILABLE_TEXT;
}
get sender(): string {
return this._sender;
}
set sender(value: string) {
this._sender = value;
}
/**
* @deprecated - use `recipients()`.
*/
get recipient(): TransactionRecipient {
assert(this._recipients.length > 0, 'No recipients available');
return this._recipients[0];
}
/**
* @deprecated - use `recipients()`.
*/
set recipient(value: TransactionRecipient) {
this.recipients = [value];
}
get recipients(): TransactionRecipient[] {
return this._recipients;
}
set recipients(value: TransactionRecipient[]) {
this._recipients = value;
}
get sequenceNumber(): number {
return this._sequenceNumber;
}
set sequenceNumber(value: number) {
this._sequenceNumber = value;
}
get maxGasAmount(): number {
return this._maxGasAmount;
}
set maxGasAmount(value: number) {
this._maxGasAmount = value;
}
get gasUnitPrice(): number {
return this._gasUnitPrice;
}
set gasUnitPrice(value: number) {
this._gasUnitPrice = value;
}
get gasUsed(): number {
return this._gasUsed;
}
set gasUsed(value: number) {
this._gasUsed = value;
}
get expirationTime(): number {
return this._expirationTime;
}
set expirationTime(value: number) {
this._expirationTime = value;
}
get feePayerAddress(): string {
return this._feePayerAddress;
}
set transactionType(transactionType: TransactionType) {
this._type = transactionType;
}
get assetId(): string {
return this._assetId;
}
set assetId(value: string) {
this._assetId = value;
}
get isSimulateTxn(): boolean {
return this._isSimulateTxn;
}
set isSimulateTxn(value: boolean) {
this._isSimulateTxn = value;
}
protected abstract getTransactionPayloadData(): InputGenerateTransactionPayloadData;
protected abstract parseTransactionPayload(payload: TransactionPayload): void;
fromDeserializedSignedTransaction(signedTxn: SignedTransaction): void {
try {
const rawTxn = signedTxn.raw_txn;
this.parseTransactionPayload(rawTxn.payload);
this._sender = rawTxn.sender.toString();
this._sequenceNumber = utils.castToNumber(rawTxn.sequence_number);
this._maxGasAmount = utils.castToNumber(rawTxn.max_gas_amount);
this._gasUnitPrice = utils.castToNumber(rawTxn.gas_unit_price);
this._expirationTime = utils.castToNumber(rawTxn.expiration_timestamp_secs);
this._rawTransaction = rawTxn;
this.loadInputsAndOutputs();
const authenticator = signedTxn.authenticator as TransactionAuthenticatorFeePayer;
this._feePayerAddress = authenticator.fee_payer.address.toString();
const senderAuthenticator = authenticator.sender as AccountAuthenticatorEd25519;
const senderSignature = Buffer.from(senderAuthenticator.signature.toUint8Array());
this.addSenderSignature({ pub: senderAuthenticator.public_key.toString() }, senderSignature);
const feePayerAuthenticator = authenticator.fee_payer.authenticator as AccountAuthenticatorEd25519;
const feePayerSignature = Buffer.from(feePayerAuthenticator.signature.toUint8Array());
this.addFeePayerSignature(
{ pub: utils.stripHexPrefix(feePayerAuthenticator.public_key.toString()) },
feePayerSignature
);
} catch (e) {
logger.error('invalid signed transaction', e);
throw new Error('invalid signed transaction');
}
}
canSign(_key: BaseKey): boolean {
return false;
}
toBroadcastFormat(): string {
if (!this._rawTransaction) {
throw new InvalidTransactionError('Empty transaction');
}
return this.serialize();
}
serialize(): string {
let senderAuthenticator: AccountAuthenticator;
let feePayerAuthenticator: AccountAuthenticator;
if (this.isSimulateTxn) {
senderAuthenticator = new AccountAuthenticatorNoAccountAuthenticator();
feePayerAuthenticator = new AccountAuthenticatorNoAccountAuthenticator();
} else {
const senderPublicKeyBuffer = utils.getBufferFromHexString(this._senderSignature.publicKey.pub);
const senderPublicKey = new Ed25519PublicKey(senderPublicKeyBuffer);
const senderSignature = new Ed25519Signature(this._senderSignature.signature);
senderAuthenticator = new AccountAuthenticatorEd25519(senderPublicKey, senderSignature);
const feePayerPublicKeyBuffer = utils.getBufferFromHexString(this._feePayerSignature.publicKey.pub);
const feePayerPublicKey = new Ed25519PublicKey(feePayerPublicKeyBuffer);
const feePayerSignature = new Ed25519Signature(this._feePayerSignature.signature);
feePayerAuthenticator = new AccountAuthenticatorEd25519(feePayerPublicKey, feePayerSignature);
}
const txnAuthenticator = new TransactionAuthenticatorFeePayer(senderAuthenticator, [], [], {
address: AccountAddress.fromString(this._feePayerAddress),
authenticator: feePayerAuthenticator,
});
const signedTxn = new SignedTransaction(this._rawTransaction, txnAuthenticator);
return signedTxn.toString();
}
addSenderSignature(publicKey: PublicKey, signature: Buffer): void {
this._signatures = [signature.toString('hex')];
this._senderSignature = { publicKey, signature };
}
getFeePayerPubKey(): string {
return this._feePayerSignature.publicKey.pub;
}
addFeePayerSignature(publicKey: PublicKey, signature: Buffer): void {
this._feePayerSignature = { publicKey, signature };
}
addFeePayerAddress(address: string): void {
this._feePayerAddress = address;
}
async build(): Promise<void> {
await this.buildRawTransaction();
this.generateTxnId();
this.loadInputsAndOutputs();
}
abstract inputsAndOutputs(): InputsAndOutputs;
loadInputsAndOutputs(): void {
const { inputs, outputs } = this.inputsAndOutputs();
this._inputs = inputs;
this._outputs = outputs;
}
fromRawTransaction(rawTransaction: string): void {
let signedTxn: SignedTransaction;
try {
signedTxn = utils.deserializeSignedTransaction(rawTransaction);
} catch (e) {
throw new Error('invalid raw transaction');
}
this.fromDeserializedSignedTransaction(signedTxn);
}
/**
* Deserializes a signed transaction hex string
* @param {string} signedRawTransaction
* @returns {SignedTransaction} the aptos signed transaction
*/
static deserializeSignedTransaction(signedRawTransaction: string): SignedTransaction {
try {
return utils.deserializeSignedTransaction(signedRawTransaction);
} catch (e) {
throw new Error('invalid raw transaction');
}
}
toJson(): TxData {
return {
id: this.id,
sender: this.sender,
recipients: this.recipients,
sequenceNumber: this.sequenceNumber,
maxGasAmount: this.maxGasAmount,
gasUnitPrice: this.gasUnitPrice,
gasUsed: this.gasUsed,
expirationTime: this.expirationTime,
feePayer: this.feePayerAddress,
assetId: this.assetId,
};
}
public getFee(): string {
return new BigNumber(this.gasUsed).multipliedBy(this.gasUnitPrice).toString();
}
public override get signablePayload(): Buffer {
return this.feePayerAddress ? this.getSignablePayloadWithFeePayer() : this.getSignablePayloadWithoutFeePayer();
}
/** @inheritDoc */
override explainTransaction(): AptTransactionExplanation {
const displayOrder = [
'id',
'outputs',
'outputAmount',
'changeOutputs',
'changeAmount',
'fee',
'withdrawAmount',
'sender',
'type',
];
const outputs: TransactionRecipient[] = this.inputsAndOutputs().externalOutputs;
const outputAmount = outputs
.reduce((accumulator, current) => accumulator.plus(current.amount), new BigNumber('0'))
.toString();
return {
displayOrder,
id: this.id,
outputs,
outputAmount,
changeOutputs: [],
changeAmount: '0',
fee: { fee: this.getFee() },
sender: this.sender,
type: this.type,
};
}
protected async buildRawTransaction(): Promise<void> {
const network: Network = this._coinConfig.network.type === NetworkType.MAINNET ? Network.MAINNET : Network.TESTNET;
const aptos = new Aptos(new AptosConfig({ network }));
const senderAddress = AccountAddress.fromString(this._sender);
const simpleTxn = await aptos.transaction.build.simple({
sender: senderAddress,
data: this.getTransactionPayloadData() as InputGenerateTransactionPayloadData,
options: {
maxGasAmount: this.maxGasAmount,
gasUnitPrice: this.gasUnitPrice,
expireTimestamp: this.expirationTime,
accountSequenceNumber: this.sequenceNumber,
},
});
this._rawTransaction = simpleTxn.rawTransaction;
}
private getSignablePayloadWithFeePayer(): Buffer {
const feePayerRawTxn = new FeePayerRawTransaction(
this._rawTransaction,
[],
AccountAddress.fromString(this._feePayerAddress)
);
return Buffer.from(generateSigningMessage(feePayerRawTxn.bcsToBytes(), RAW_TRANSACTION_WITH_DATA_SALT));
}
private getSignablePayloadWithoutFeePayer(): Buffer {
return Buffer.from(generateSigningMessage(this._rawTransaction.bcsToBytes(), RAW_TRANSACTION_SALT));
}
private generateTxnId() {
if (
!this._senderSignature ||
!this._senderSignature.publicKey ||
!this._senderSignature.signature ||
!this._feePayerSignature ||
!this._feePayerSignature.publicKey ||
!this._feePayerSignature.signature ||
!this._feePayerAddress
) {
return;
}
const transaction = new SimpleTransaction(this._rawTransaction, AccountAddress.fromString(this._feePayerAddress));
const senderPublicKey = new Ed25519PublicKey(utils.getBufferFromHexString(this._senderSignature.publicKey.pub));
const senderSignature = new Ed25519Signature(this._senderSignature.signature);
const senderAuthenticator = new AccountAuthenticatorEd25519(senderPublicKey, senderSignature);
const feePayerPublicKey = new Ed25519PublicKey(utils.getBufferFromHexString(this._feePayerSignature.publicKey.pub));
const feePayerSignature = new Ed25519Signature(this._feePayerSignature.signature);
const feePayerAuthenticator = new AccountAuthenticatorEd25519(feePayerPublicKey, feePayerSignature);
this._id = generateUserTransactionHash({ transaction, senderAuthenticator, feePayerAuthenticator });
}
}