-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathton.ts
More file actions
611 lines (530 loc) · 20.4 KB
/
ton.ts
File metadata and controls
611 lines (530 loc) · 20.4 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import BigNumber from 'bignumber.js';
import * as _ from 'lodash';
import TonWeb from 'tonweb';
import {
BaseCoin,
BitGoBase,
EDDSAMethods,
InvalidAddressError,
KeyPair,
MPCAlgorithm,
MultisigType,
multisigTypes,
ParsedTransaction,
ParseTransactionOptions,
SignedTransaction,
SignTransactionOptions,
TransactionExplanation,
TssVerifyAddressOptions,
VerifyTransactionOptions,
EDDSAMethodTypes,
MPCRecoveryOptions,
MPCTx,
OvcInput,
OvcOutput,
Environments,
MPCSweepTxs,
PublicKey,
MPCTxs,
MPCSweepRecoveryOptions,
AuditDecryptedKeyParams,
extractCommonKeychain,
} from '@bitgo/sdk-core';
import { auditEddsaPrivateKey, getDerivationPath } from '@bitgo/sdk-lib-mpc';
import { BaseCoin as StaticsBaseCoin, coins } from '@bitgo/statics';
import { Transaction as WasmTonTransaction } from '@bitgo/wasm-ton';
import { KeyPair as TonKeyPair } from './lib/keyPair';
import { TransactionBuilderFactory, Utils, TransferBuilder, TokenTransferBuilder, TransactionBuilder } from './lib';
import { explainTonTransaction } from './lib/explainTransactionWasm';
import { getFeeEstimate } from './lib/utils';
export interface TonParseTransactionOptions extends ParseTransactionOptions {
txHex: string;
fromAddressBounceable?: boolean;
toAddressBounceable?: boolean;
}
export class Ton extends BaseCoin {
protected readonly _staticsCoin: Readonly<StaticsBaseCoin>;
protected constructor(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>) {
super(bitgo);
if (!staticsCoin) {
throw new Error('missing required constructor parameter staticsCoin');
}
this._staticsCoin = staticsCoin;
}
static createInstance(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>): BaseCoin {
return new Ton(bitgo, staticsCoin);
}
/**
* Factor between the coin's base unit and its smallest subdivison
*/
public getBaseFactor(): number {
return 1e9;
}
public getChain(): string {
return 'ton';
}
public getFamily(): string {
return 'ton';
}
public getFullName(): string {
return 'Ton';
}
/** @inheritDoc */
supportsTss(): boolean {
return true;
}
/** inherited doc */
getDefaultMultisigType(): MultisigType {
return multisigTypes.tss;
}
getMPCAlgorithm(): MPCAlgorithm {
return 'eddsa';
}
allowsAccountConsolidations(): boolean {
return true;
}
getAddressDetails(address: string): { address: string; memoId?: string } {
const addressComponents = address.split('?memoId=');
if (addressComponents.length > 1) {
return {
address: addressComponents[0],
memoId: addressComponents[1],
};
} else {
return {
address: addressComponents[0],
};
}
}
async verifyTransaction(params: VerifyTransactionOptions): Promise<boolean> {
const { txPrebuild: txPrebuild, txParams: txParams } = params;
const rawTx = txPrebuild.txHex;
if (!rawTx) {
throw new Error('missing required tx prebuild property txHex');
}
if (this.getChain() === 'tton') {
const { decode, encode } = await import('@bitgo/wasm-ton');
const toBounceable = (address: string) => {
const decoded = decode(this.getAddressDetails(address).address);
return encode(decoded.workchainId, decoded.addressHash, true);
};
const txBase64 = Buffer.from(rawTx, 'hex').toString('base64');
const explainedTx = explainTonTransaction({ txBase64 });
if (txParams.recipients !== undefined) {
const filteredRecipients = txParams.recipients.map((recipient) => ({
address: toBounceable(recipient.address),
amount: BigInt(recipient.amount),
}));
const filteredOutputs = explainedTx.outputs.map((output) => ({
address: toBounceable(output.address),
amount: BigInt(output.amount),
}));
if (!_.isEqual(filteredOutputs, filteredRecipients)) {
throw new Error('Tx outputs does not match with expected txParams recipients');
}
let totalAmount = new BigNumber(0);
for (const recipient of txParams.recipients) {
totalAmount = totalAmount.plus(recipient.amount);
}
if (!totalAmount.isEqualTo(explainedTx.outputAmount)) {
throw new Error('Tx total amount does not match with expected total amount field');
}
}
return true;
}
const txBuilder = this.getBuilder().from(Buffer.from(rawTx, 'hex').toString('base64'));
const transaction = await txBuilder.build();
const explainedTx = transaction.explainTransaction();
if (txParams.recipients !== undefined) {
const filteredRecipients = txParams.recipients?.map((recipient) => {
const destination = this.getAddressDetails(recipient.address);
return {
address: new TonWeb.Address(destination.address).toString(true, true, true),
amount: BigInt(recipient.amount),
};
});
const filteredOutputs = explainedTx.outputs.map((output) => {
return {
address: new TonWeb.Address(output.address).toString(true, true, true),
amount: BigInt(output.amount),
};
});
if (!_.isEqual(filteredOutputs, filteredRecipients)) {
throw new Error('Tx outputs does not match with expected txParams recipients');
}
let totalAmount = new BigNumber(0);
for (const recipients of txParams.recipients) {
totalAmount = totalAmount.plus(recipients.amount);
}
if (!totalAmount.isEqualTo(explainedTx.outputAmount)) {
throw new Error('Tx total amount does not match with expected total amount field');
}
}
return true;
}
async isWalletAddress(params: TssVerifyAddressOptions): Promise<boolean> {
const { keychains, address: newAddress, index } = params;
if (!this.isValidAddress(newAddress)) {
throw new InvalidAddressError(`invalid address: ${newAddress}`);
}
const [address, memoId] = newAddress.split('?memoId=');
// TON supports memoId for address tagging - verify it matches the index
if (memoId) {
return memoId === `${index}`;
}
const commonKeychain = extractCommonKeychain(keychains);
const MPC = await EDDSAMethods.getInitializedMpcInstance();
const derivationPath = 'm/' + index;
const derivedPublicKey = MPC.deriveUnhardened(commonKeychain, derivationPath).slice(0, 64);
const expectedAddress = await Utils.default.getAddressFromPublicKey(derivedPublicKey);
return address === expectedAddress;
}
async parseTransaction(params: TonParseTransactionOptions): Promise<ParsedTransaction> {
const factory = new TransactionBuilderFactory(coins.get(this.getChain()));
const transactionBuilder = factory.from(Buffer.from(params.txHex, 'hex').toString('base64'));
if (typeof params.toAddressBounceable === 'boolean') {
transactionBuilder.toAddressBounceable(params.toAddressBounceable);
}
if (typeof params.fromAddressBounceable === 'boolean') {
transactionBuilder.fromAddressBounceable(params.fromAddressBounceable);
}
const rebuiltTransaction = await transactionBuilder.build();
const parsedTransaction = rebuiltTransaction.toJson();
return {
inputs: [
{
address: parsedTransaction.sender,
amount: parsedTransaction.amount,
},
],
outputs: [
{
address: parsedTransaction.destination,
amount: parsedTransaction.amount,
},
],
};
}
generateKeyPair(seed?: Buffer): KeyPair {
const keyPair = seed ? new TonKeyPair({ seed }) : new TonKeyPair();
const keys = keyPair.getKeys();
if (!keys.prv) {
throw new Error('Missing prv in key generation.');
}
return {
pub: keys.pub,
prv: keys.prv,
};
}
isValidPub(pub: string): boolean {
throw new Error('Method not implemented.');
}
isValidAddress(address: string): boolean {
try {
const addressBase64 = address.replace(/\+/g, '-').replace(/\//g, '_');
const buf = Buffer.from(addressBase64.split('?memoId=')[0], 'base64');
return buf.length === 36;
} catch {
return false;
}
}
signTransaction(params: SignTransactionOptions): Promise<SignedTransaction> {
throw new Error('Method not implemented.');
}
/** @inheritDoc */
async getSignablePayload(serializedTx: string): Promise<Buffer> {
if (this.getChain() === 'tton') {
const tx = WasmTonTransaction.fromBytes(Buffer.from(serializedTx, 'base64'));
return Buffer.from(tx.signablePayload());
}
const factory = new TransactionBuilderFactory(coins.get(this.getChain()));
const rebuiltTransaction = await factory.from(serializedTx).build();
return rebuiltTransaction.signablePayload;
}
/** @inheritDoc */
async explainTransaction(params: Record<string, any>): Promise<TransactionExplanation> {
if (this.getChain() === 'tton') {
try {
const txBase64 = Buffer.from(params.txHex, 'hex').toString('base64');
return explainTonTransaction({ txBase64, toAddressBounceable: params.toAddressBounceable });
} catch {
throw new Error('Invalid transaction');
}
}
try {
const factory = new TransactionBuilderFactory(coins.get(this.getChain()));
const transactionBuilder = factory.from(Buffer.from(params.txHex, 'hex').toString('base64'));
const { toAddressBounceable, fromAddressBounceable } = params;
if (typeof toAddressBounceable === 'boolean') {
transactionBuilder.toAddressBounceable(toAddressBounceable);
}
if (typeof fromAddressBounceable === 'boolean') {
transactionBuilder.fromAddressBounceable(fromAddressBounceable);
}
const rebuiltTransaction = await transactionBuilder.build();
return rebuiltTransaction.explainTransaction();
} catch {
throw new Error('Invalid transaction');
}
}
protected getPublicNodeUrl(): string {
return Environments[this.bitgo.getEnv()].tonNodeUrl;
}
private getBuilder(): TransactionBuilderFactory {
return new TransactionBuilderFactory(coins.get(this.getChain()));
}
async recover(
params: MPCRecoveryOptions & { jettonMaster?: string; senderJettonAddress?: string }
): Promise<MPCTx | MPCSweepTxs> {
if (!params.bitgoKey) {
throw new Error('missing bitgoKey');
}
if (!params.recoveryDestination || !this.isValidAddress(params.recoveryDestination)) {
throw new Error('invalid recoveryDestination');
}
if (!params.apiKey) {
throw new Error('missing apiKey');
}
const bitgoKey = params.bitgoKey.replace(/\s/g, '');
const isUnsignedSweep = !params.userKey && !params.backupKey && !params.walletPassphrase;
// Build the transaction
const tonweb = new TonWeb(new TonWeb.HttpProvider(this.getPublicNodeUrl(), { apiKey: params.apiKey }));
const MPC = await EDDSAMethods.getInitializedMpcInstance();
const index = params.index || 0;
const currPath = params.seed ? getDerivationPath(params.seed) + `/${index}` : `m/${index}`;
const accountId = MPC.deriveUnhardened(bitgoKey, currPath).slice(0, 64);
const senderAddr = await Utils.default.getAddressFromPublicKey(accountId);
const balance = await tonweb.getBalance(senderAddr);
const jettonBalances: { minterAddress?: string; walletAddress: string; balance: string }[] = [];
if (params.senderJettonAddress) {
try {
const jettonWalletData = await tonweb.provider.call(params.senderJettonAddress, 'get_wallet_data');
const jettonBalance = jettonWalletData.stack[0][1];
if (jettonBalance && new BigNumber(jettonBalance).gt(0)) {
jettonBalances.push({
walletAddress: params.senderJettonAddress,
balance: jettonBalance,
});
}
} catch (e) {
throw new Error(`Failed to query jetton balance for address ${params.senderJettonAddress}: ${e.message}`);
}
}
const WalletClass = tonweb.wallet.all['v4R2'];
const wallet = new WalletClass(tonweb.provider, {
publicKey: tonweb.utils.hexToBytes(accountId),
wc: 0,
});
const seqnoResult = await wallet.methods.seqno().call();
const seqno: number = seqnoResult !== null && seqnoResult !== undefined ? seqnoResult : 0;
const factory = this.getBuilder();
const expireAt = Math.floor(Date.now() / 1e3) + 60 * 60 * 24 * 7;
let txBuilder: TransactionBuilder;
let unsignedTransaction: any;
let feeEstimate: number;
let transactionType: 'ton' | 'jetton';
if ((params.jettonMaster || params.senderJettonAddress) && jettonBalances.length > 0) {
const jettonInfo = jettonBalances[0];
const tonAmount = '50000000';
const forwardTonAmount = '1';
const totalRequiredTon = new BigNumber(tonAmount).plus(new BigNumber(forwardTonAmount));
if (new BigNumber(balance).lt(totalRequiredTon)) {
throw new Error(
`Insufficient TON balance for jetton transfer. Required: ${totalRequiredTon.toString()} nanoTON, Available: ${balance}`
);
}
txBuilder = factory
.getTokenTransferBuilder()
.sender(senderAddr)
.sequenceNumber(seqno)
.publicKey(accountId)
.expireTime(expireAt);
(txBuilder as TokenTransferBuilder).recipient(
params.recoveryDestination,
jettonInfo.walletAddress,
tonAmount,
jettonInfo.balance,
forwardTonAmount
);
unsignedTransaction = await txBuilder.build();
feeEstimate = parseInt(tonAmount, 10);
transactionType = 'jetton';
} else {
if (new BigNumber(balance).isEqualTo(0)) {
throw Error('Did not find address with TON balance to recover');
}
const tonFeeEstimate = await getFeeEstimate(wallet, params.recoveryDestination, balance, seqno as number);
const totalFeeEstimate = Math.round(
(tonFeeEstimate.source_fees.in_fwd_fee +
tonFeeEstimate.source_fees.storage_fee +
tonFeeEstimate.source_fees.gas_fee +
tonFeeEstimate.source_fees.fwd_fee) *
1.5
);
if (new BigNumber(totalFeeEstimate).gte(balance)) {
throw new Error(
`Insufficient TON balance for transaction. Required: ${totalFeeEstimate} nanoTON, Available: ${balance}`
);
}
txBuilder = factory
.getTransferBuilder()
.sender(senderAddr)
.sequenceNumber(seqno)
.publicKey(accountId)
.expireTime(expireAt);
(txBuilder as TransferBuilder).send({
address: params.recoveryDestination,
amount: new BigNumber(balance).minus(new BigNumber(totalFeeEstimate)).toString(),
});
unsignedTransaction = await txBuilder.build();
feeEstimate = totalFeeEstimate;
transactionType = 'ton';
}
if (!isUnsignedSweep) {
if (!params.userKey) {
throw new Error('missing userKey');
}
if (!params.backupKey) {
throw new Error('missing backupKey');
}
if (!params.walletPassphrase) {
throw new Error('missing wallet passphrase');
}
// Clean up whitespace from entered values
const userKey = params.userKey.replace(/\s/g, '');
const backupKey = params.backupKey.replace(/\s/g, '');
let userPrv;
try {
userPrv = this.bitgo.decrypt({
input: userKey,
password: params.walletPassphrase,
});
} catch (e) {
throw new Error(`Error decrypting user keychain: ${e.message}`);
}
const userSigningMaterial = JSON.parse(userPrv) as EDDSAMethodTypes.UserSigningMaterial;
let backupPrv;
try {
backupPrv = this.bitgo.decrypt({
input: backupKey,
password: params.walletPassphrase,
});
} catch (e) {
throw new Error(`Error decrypting backup keychain: ${e.message}`);
}
const backupSigningMaterial = JSON.parse(backupPrv) as EDDSAMethodTypes.BackupSigningMaterial;
const signatureHex = await EDDSAMethods.getTSSSignature(
userSigningMaterial,
backupSigningMaterial,
currPath,
unsignedTransaction
);
const publicKeyObj = { pub: senderAddr };
txBuilder.addSignature(publicKeyObj as PublicKey, signatureHex);
}
const walletCoin = this.getChain();
const coinSpecific = { commonKeychain: bitgoKey };
if (isUnsignedSweep) {
const completedTransaction = await txBuilder.build();
const serializedTx = completedTransaction.toBroadcastFormat();
const inputs: OvcInput[] = [];
for (const input of completedTransaction.inputs) {
inputs.push({
address: input.address,
valueString: input.value,
value: new BigNumber(input.value).toNumber(),
});
}
const outputs: OvcOutput[] = [];
for (const output of completedTransaction.outputs) {
outputs.push({
address: output.address,
valueString: output.value,
coinName: output.coin,
});
}
const spendAmount = completedTransaction.inputs.length === 1 ? completedTransaction.inputs[0].value : 0;
const parsedTx = { inputs: inputs, outputs: outputs, spendAmount: spendAmount, type: transactionType };
const feeInfo = { fee: feeEstimate, feeString: feeEstimate.toString() };
const transaction: MPCTx = {
serializedTx: serializedTx,
scanIndex: index,
coin: walletCoin,
signableHex: completedTransaction.signablePayload.toString('hex'),
derivationPath: currPath,
parsedTx: parsedTx,
feeInfo: feeInfo,
coinSpecific: coinSpecific,
};
return transaction;
}
const completedTransaction = await txBuilder.build();
const serializedTx = completedTransaction.toBroadcastFormat();
const transaction: MPCTx = {
serializedTx: serializedTx,
scanIndex: index,
};
return transaction;
}
/**
* Creates funds sweep recovery transaction(s) without BitGo
*
* @param {MPCSweepRecoveryOptions} params parameters needed to combine the signatures
* and transactions to create broadcastable transactions
*
* @returns {MPCTxs} array of the serialized transaction hex strings and indices
* of the addresses being swept
*/
async createBroadcastableSweepTransaction(params: MPCSweepRecoveryOptions): Promise<MPCTxs> {
const req = params.signatureShares;
const broadcastableTransactions: MPCTx[] = [];
let lastScanIndex = 0;
for (let i = 0; i < req.length; i++) {
const MPC = await EDDSAMethods.getInitializedMpcInstance();
const transaction = req[i].txRequest.transactions[0].unsignedTx;
if (!req[i].ovc || !req[i].ovc[0].eddsaSignature) {
throw new Error('Missing signature(s)');
}
const signature = req[i].ovc[0].eddsaSignature;
if (!transaction.signableHex) {
throw new Error('Missing signable hex');
}
const messageBuffer = Buffer.from(transaction.signableHex!, 'hex');
const result = MPC.verify(messageBuffer, signature);
if (!result) {
throw new Error('Invalid signature');
}
const signatureHex = Buffer.concat([Buffer.from(signature.R, 'hex'), Buffer.from(signature.sigma, 'hex')]);
const txBuilder = this.getBuilder().from(transaction.serializedTx as string);
if (!transaction.coinSpecific?.commonKeychain) {
throw new Error('Missing common keychain');
}
const commonKeychain = transaction.coinSpecific!.commonKeychain! as string;
if (!transaction.derivationPath) {
throw new Error('Missing derivation path');
}
const derivationPath = transaction.derivationPath as string;
const accountId = MPC.deriveUnhardened(commonKeychain, derivationPath).slice(0, 64);
const tonKeyPair = new TonKeyPair({ pub: accountId });
// add combined signature from ovc
txBuilder.addSignature({ pub: tonKeyPair.getKeys().pub }, signatureHex);
const signedTransaction = await txBuilder.build();
const serializedTx = signedTransaction.toBroadcastFormat();
broadcastableTransactions.push({
serializedTx: serializedTx,
scanIndex: transaction.scanIndex,
});
if (i === req.length - 1 && transaction.coinSpecific!.lastScanIndex) {
lastScanIndex = transaction.coinSpecific!.lastScanIndex as number;
}
}
return { transactions: broadcastableTransactions, lastScanIndex };
}
/** @inheritDoc */
auditDecryptedKey({ publicKey, prv, multiSigType }: AuditDecryptedKeyParams) {
if (multiSigType !== 'tss') {
throw new Error('Unsupported multiSigType');
}
auditEddsaPrivateKey(prv, publicKey ?? '');
}
}