-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtransaction.ts
More file actions
454 lines (411 loc) · 14.9 KB
/
transaction.ts
File metadata and controls
454 lines (411 loc) · 14.9 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import {
BaseKey,
BaseTransaction,
Entry,
InvalidTransactionError,
NodeEnvironmentError,
TransactionType,
} from '@bitgo/sdk-core';
import * as CardanoWasm from '@emurgo/cardano-serialization-lib-nodejs';
import { KeyPair } from './keyPair';
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import adaUtils from './utils';
export interface TransactionInput {
transaction_id: string;
transaction_index: number;
}
export interface Asset {
policy_id: string;
asset_name: string;
quantity: string;
fingerprint?: string;
}
export interface TransactionOutput {
address: string;
amount: string;
multiAssets?: CardanoWasm.MultiAsset | Asset;
}
export interface Witness {
publicKey: string;
signature: string;
}
export enum CertType {
StakeKeyRegistration,
StakeKeyDelegation,
StakeKeyDeregistration,
StakePoolRegistration,
VoteDelegation,
}
export interface Cert {
type: CertType;
stakeCredentialHash?: string;
poolKeyHash?: string;
dRepId?: string;
}
export interface Withdrawal {
stakeAddress: string;
value: string;
}
export type StakeKeyRegistrationCert = Cert;
export type StakeKeyDelegationCert = Cert;
export interface StakePoolRegistrationCert extends Cert {
vrfKeyHash: string;
pledge: string;
cost: string;
marginNumerator: string;
marginDenominator: string;
rewardAccount: string;
poolOwners: string[];
}
export interface PledgeDetails {
stakeKeyRegistration?: StakeKeyRegistrationCert;
stakeKeyDelegation?: StakeKeyDelegationCert;
stakePoolRegistration: StakePoolRegistrationCert;
}
/**
* The transaction data returned from the toJson() function of a transaction
*/
export interface TxData {
id: string | undefined;
type: TransactionType;
inputs: TransactionInput[];
outputs: TransactionOutput[];
witnesses: Witness[];
certs: Cert[];
withdrawals: Withdrawal[];
pledgeDetails?: PledgeDetails;
}
export class Transaction extends BaseTransaction {
private _transaction: CardanoWasm.Transaction;
private _fee: string;
private _pledgeDetails?: PledgeDetails;
constructor(coinConfig: Readonly<CoinConfig>) {
super(coinConfig);
}
get transaction(): CardanoWasm.Transaction {
return this._transaction;
}
set transaction(tx: CardanoWasm.Transaction) {
this._transaction = tx;
this._id = Buffer.from(CardanoWasm.hash_transaction(tx.body()).to_bytes()).toString('hex');
}
/** @inheritdoc */
canSign(key: BaseKey): boolean {
try {
new KeyPair({ prv: key.key });
return true;
} catch {
return false;
}
}
toBroadcastFormat(): string {
if (!this._transaction) {
throw new InvalidTransactionError('Empty transaction data');
}
return Buffer.from(this._transaction.to_bytes()).toString('hex');
}
/** @inheritdoc */
toJson(): TxData {
if (!this._transaction) {
throw new InvalidTransactionError('Empty transaction data');
}
const result: TxData = {
id: this.id,
type: this._type as TransactionType,
inputs: [],
outputs: [],
witnesses: [],
certs: [],
withdrawals: [],
};
for (let i = 0; i < this._transaction.body().inputs().len(); i++) {
const input = this._transaction.body().inputs().get(i);
result.inputs.push({
transaction_id: Buffer.from(input.transaction_id().to_bytes()).toString('hex'),
transaction_index: input.index(),
});
}
for (let i = 0; i < this._transaction.body().outputs().len(); i++) {
const output = this._transaction.body().outputs().get(i);
result.outputs.push({
address: adaUtils.getAddressString(output.address()),
amount: output.amount().coin().to_str(),
multiAssets: output.amount().multiasset() || undefined,
});
}
if (this._transaction.body().certs()) {
for (let i = 0; i < this._transaction.body().certs()!.len(); i++) {
const cert = this._transaction.body().certs()!.get(i);
if (cert.as_stake_registration() !== undefined) {
const stakeRegistration = cert.as_stake_registration() as CardanoWasm.StakeRegistration;
result.certs.push({
type: CertType.StakeKeyRegistration,
stakeCredentialHash: Buffer.from(stakeRegistration.stake_credential().to_bytes()).toString('hex'),
});
}
if (cert.as_stake_deregistration() !== undefined) {
const stakeDeregistration = cert.as_stake_deregistration() as CardanoWasm.StakeDeregistration;
result.certs.push({
type: CertType.StakeKeyDeregistration,
stakeCredentialHash: Buffer.from(stakeDeregistration.stake_credential().to_bytes()).toString('hex'),
});
}
if (cert.as_stake_delegation() !== undefined) {
const stakeDelegation = cert.as_stake_delegation() as CardanoWasm.StakeDelegation;
result.certs.push({
type: CertType.StakeKeyDelegation,
stakeCredentialHash: Buffer.from(stakeDelegation.stake_credential().to_bytes()).toString('hex'),
poolKeyHash: Buffer.from(stakeDelegation.pool_keyhash().to_bytes()).toString('hex'),
});
}
if (cert.as_pool_registration() !== undefined) {
const stakePoolRegistration = cert.as_pool_registration() as CardanoWasm.PoolRegistration;
result.certs.push({
type: CertType.StakePoolRegistration,
poolKeyHash: Buffer.from(stakePoolRegistration.pool_params().operator().to_bytes()).toString('hex'),
});
}
if (cert.as_vote_delegation() !== undefined) {
const voteDelegation = cert.as_vote_delegation() as CardanoWasm.VoteDelegation;
result.certs.push({
type: CertType.VoteDelegation,
stakeCredentialHash: Buffer.from(voteDelegation.stake_credential().to_bytes()).toString('hex'),
dRepId: adaUtils.getDRepIdFromDRep(voteDelegation.drep()),
});
}
}
}
result.pledgeDetails = this._pledgeDetails;
if (this._transaction.body().withdrawals()) {
const withdrawals = this._transaction.body().withdrawals() as CardanoWasm.Withdrawals;
const keys = withdrawals.keys();
for (let i = 0; i < keys.len(); i++) {
const rewardAddress = keys.get(i);
const reward = withdrawals.get(rewardAddress) as CardanoWasm.BigNum;
result.withdrawals.push({
stakeAddress: rewardAddress.to_address().to_bytes().toString(),
value: reward.to_str(),
});
}
}
if (this._transaction.witness_set().vkeys() !== undefined) {
const vkeys = this._transaction.witness_set().vkeys() as CardanoWasm.Vkeywitnesses;
for (let i = 0; i < vkeys.len(); i++) {
const vkey = (this._transaction.witness_set().vkeys() as CardanoWasm.Vkeywitnesses).get(i);
result.witnesses.push({
publicKey: vkey?.vkey().public_key().to_hex(),
signature: vkey?.signature().to_hex(),
});
}
}
return result;
}
/**
* Build input and output field for this transaction
*
*/
loadInputsAndOutputs(): void {
const outputs: Entry[] = [];
const inputs: Entry[] = [];
const tx_outputs = this._transaction.body().outputs();
for (let i = 0; i < tx_outputs.len(); i++) {
const output = tx_outputs.get(i);
outputs.push({
address: adaUtils.getAddressString(output.address()),
value: output.amount().coin().to_str(),
});
}
this._outputs = outputs;
this._inputs = inputs;
}
/** @inheritdoc */
get signablePayload(): Buffer {
return Buffer.from(CardanoWasm.hash_transaction(this._transaction.body()).to_bytes());
}
/**
* Sets this transaction payload
*
* @param rawTx
*/
fromRawTransaction(rawTx: string): void {
if (CardanoWasm.Transaction === undefined) {
// a temp fix until we solve import problem in webpack
throw new NodeEnvironmentError('unable to load cardano serialization library');
}
const HEX_REGEX = /^[0-9a-fA-F]+$/;
const bufferRawTransaction = HEX_REGEX.test(rawTx) ? Buffer.from(rawTx, 'hex') : Buffer.from(rawTx, 'base64');
try {
const txn = CardanoWasm.Transaction.from_bytes(bufferRawTransaction);
this._transaction = txn;
this._id = Buffer.from(CardanoWasm.hash_transaction(txn.body()).to_bytes()).toString('hex');
this._type = TransactionType.Send;
if (this._transaction.body().certs()) {
const certs: CardanoWasm.Certificate[] = [];
for (let i = 0; i < this._transaction.body().certs()!.len(); i++) {
const cert = this._transaction.body().certs()!.get(i);
certs.push(cert);
}
if (certs.some((c) => c.as_pool_registration() !== undefined)) {
this._type = TransactionType.StakingPledge;
const stakeKeyRegistration = certs.find((c) => c.as_stake_registration() !== undefined);
const stakeKeyDelegation = certs.find((c) => c.as_stake_delegation() !== undefined);
const stakePoolRegistration = certs.find((c) => c.as_pool_registration() !== undefined);
this._pledgeDetails = {
stakeKeyRegistration: this.loadStakeKeyRegistration(stakeKeyRegistration),
stakeKeyDelegation: this.loadStakeKeyDelegation(stakeKeyDelegation),
stakePoolRegistration: this.loadStakePoolRegistration(stakePoolRegistration!),
};
} else if (certs.some((c) => c.as_stake_registration() !== undefined)) {
this._type = TransactionType.StakingActivate;
} else if (certs.some((c) => c.as_stake_deregistration() !== undefined)) {
this._type = TransactionType.StakingDeactivate;
} else if (certs.some((c) => c.as_vote_delegation() !== undefined)) {
this._type = TransactionType.VoteDelegation;
}
}
if (this._transaction.body().withdrawals()) {
this._type = TransactionType.StakingWithdraw;
}
this._fee = txn.body().fee().to_str();
this.loadInputsAndOutputs();
if (this._transaction.witness_set().vkeys()) {
const vkeys = this._transaction.witness_set().vkeys()! as CardanoWasm.Vkeywitnesses;
for (let i = 0; i < vkeys.len(); i++) {
const vkey = vkeys.get(i);
this._signatures.push(vkey.signature().to_hex());
}
}
} catch (e) {
throw new InvalidTransactionError('unable to build transaction from raw');
}
}
private loadStakeKeyRegistration(
certificate: CardanoWasm.Certificate | undefined
): StakeKeyRegistrationCert | undefined {
if (certificate === undefined) {
return undefined;
}
const stakeRegistration = certificate.as_stake_registration();
if (stakeRegistration !== undefined && stakeRegistration!.stake_credential().to_keyhash() !== undefined) {
return {
type: CertType.StakeKeyRegistration,
stakeCredentialHash: stakeRegistration!.stake_credential().to_keyhash()!.to_hex(),
};
} else {
return undefined;
}
}
private loadStakeKeyDelegation(certificate: CardanoWasm.Certificate | undefined): StakeKeyDelegationCert | undefined {
if (certificate === undefined) {
return undefined;
}
const stakeDelegation = certificate.as_stake_delegation();
if (stakeDelegation !== undefined && stakeDelegation!.stake_credential().to_keyhash() !== undefined) {
return {
type: CertType.StakeKeyDelegation,
stakeCredentialHash: stakeDelegation!.stake_credential().to_keyhash()!.to_hex(),
poolKeyHash: stakeDelegation!.pool_keyhash().to_hex(),
};
} else {
return undefined;
}
}
private loadStakePoolRegistration(certificate: CardanoWasm.Certificate): StakePoolRegistrationCert {
const poolRegistration = certificate.as_pool_registration();
const rewardAccount = poolRegistration!.pool_params().reward_account();
const networkId = rewardAccount.to_address().network_id();
const owners: string[] = [];
for (let i = 0; i < poolRegistration!.pool_params().pool_owners().len(); i++) {
const poolOwner = poolRegistration!.pool_params().pool_owners().get(i);
const ownerStakeKey = CardanoWasm.Credential.from_keyhash(poolOwner);
owners.push(CardanoWasm.RewardAddress.new(networkId, ownerStakeKey).to_address().to_bech32());
}
return {
type: CertType.StakePoolRegistration,
poolKeyHash: poolRegistration!.pool_params().operator().to_hex(),
vrfKeyHash: poolRegistration!.pool_params().vrf_keyhash().to_hex(),
pledge: poolRegistration!.pool_params().pledge().to_str(),
cost: poolRegistration!.pool_params().cost().to_str(),
marginNumerator: poolRegistration!.pool_params().margin().numerator().to_str(),
marginDenominator: poolRegistration!.pool_params().margin().denominator().to_str(),
rewardAccount: rewardAccount.to_address().to_bech32(),
poolOwners: owners,
};
}
/**
* Set the transaction type.
*
* @param {TransactionType} transactionType The transaction type to be set.
*/
setTransactionType(transactionType: TransactionType): void {
this._type = transactionType;
}
/** @inheritdoc */
explainTransaction(): {
outputs: { amount: string; address: string }[];
certificates: Cert[];
changeOutputs: string[];
outputAmount: string;
fee: { fee: string };
displayOrder: string[];
id: string | undefined;
changeAmount: string;
type: string;
withdrawals: Withdrawal[];
pledgeDetails?: PledgeDetails;
} {
const txJson = this.toJson();
const displayOrder = ['id', 'outputAmount', 'changeAmount', 'outputs', 'changeOutputs', 'fee', 'type'];
const amount = txJson.outputs.map((o) => ({ amount: BigInt(o.amount) }));
const outputAmount = amount.reduce((p, n) => p + BigInt(n.amount), BigInt('0')).toString();
const type =
this._type === TransactionType.Send
? 'Transfer'
: this._type === TransactionType.StakingActivate
? 'StakingActivate'
: this._type === TransactionType.StakingWithdraw
? 'StakingWithdraw'
: this._type === TransactionType.StakingDeactivate
? 'StakingDeactivate'
: this._type === TransactionType.StakingPledge
? 'StakingPledge'
: this._type === TransactionType.VoteDelegation
? 'VoteDelegation'
: 'undefined';
return {
displayOrder,
id: txJson.id,
outputs: txJson.outputs.map((o) => ({ address: o.address, amount: o.amount })),
outputAmount: outputAmount,
changeOutputs: [],
changeAmount: '0',
fee: { fee: this._fee },
type,
certificates: txJson.certs,
withdrawals: txJson.withdrawals,
pledgeDetails: this._pledgeDetails,
};
}
getPledgeDetails(): PledgeDetails | undefined {
return this._pledgeDetails;
}
/**
* Get transaction fee
*/
get getFee(): string {
return this._fee;
}
/**
* Set transaction fee
*
* @param fee
*/
fee(fee: string) {
this._fee = fee;
}
}
export interface SponsorshipInfo {
feeAddress: string;
feeAddressInputBalance: string;
isRebuild?: boolean; // hack to redirect the flow to the legacy build
}