-
Notifications
You must be signed in to change notification settings - Fork 1
/
exaple.txt
488 lines (415 loc) · 12.2 KB
/
exaple.txt
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
// Visual blocks
interface GasPrice {
class_let: Denom;
class_it: string;
class_be: string;
}
// Delete in [ {
interface {gas_prices: [GasPrice];}
interface Balance {
height: string;
result: [Coin];
}
type SendOptions = {
memo?: string;
chainName?: ChainName;
feeDenom?: Denom;
};
// Repeate operation with .
enum AccountType {
STANDARD_OLD = 'core/Account',
VESTING_OLD = 'core/LazyGradedVestingAccount',
NEW_OLD = 'core/LazyGradedVestingAccount',
}
export async function getBalance(
address: string,
chainName: ChainName,
): Promise<any> {
return get(chainName, `/bank/balances/${address}`);
}
function getValue(account: StandardAccount | VestingAccount): AccountValue {
return account.result.type === AccountType.STANDARD
? account.result.value
: account.result.value.BaseVestingAccount.BaseAccount;
}
async function getChainId(chainName: ChainName): Promise<string> {
const latest = await get(chainName, '/blocks/latest');
const { chain_id } = latest.block.header;
return chain_id;
}
async function getAccountInfo(
chainName: ChainName,
from: string,
): Promise<[string, string]> {
const account = await get(chainName, `/auth/accounts/${from}`);
console.log('account =', account);
const { account_number, sequence } = getValue(account);
return [account_number, sequence];
}
async function getGasEstimate(
msgSend: Record<string, any>,
feeDenom: Denom,
price: string,
chainName: ChainName,
adjustment?: string,
): Promise<Fee> {
// Gas prices are 0.015 u* for all denoms at the moment
let gas_adjustment: string;
if (adjustment) {
gas_adjustment = adjustment;
} else {
gas_adjustment = DEFAULT_GAS_COEFFICIENT;
}
const gasPrice: GasAdjustedPrice = {
gas_adjustment,
gas_prices: [
{
denom: feeDenom,
amount: price,
},
],
};
const fakeFee = {
fee: {
// Leave gas at 0 to get estimate
gas: '0',
// The amount is not important, the denom should be the fee denom
amount: [
{
denom: feeDenom,
amount: '1',
},
],
},
};
const estimateFeeTx = {
tx: {
msg: [msgSend],
...fakeFee,
},
...gasPrice,
};
console.log('estimateTx=', JSON.stringify(estimateFeeTx));
const gasEstimate = await post(chainName, '/txs/estimate_fee', estimateFeeTx);
const gasAdjusted = {
gas: gasEstimate.result.gas,
amount: gasEstimate.result.fees,
};
return gasAdjusted;
}
export class TerraThreshSigClient {
private mainnet: boolean;
private p2: Party2;
private p2MasterKeyShare: Party2Share;
private db: any;
private useAsyncBroadcast: boolean;
constructor(mainnet = false, useAsyncBroadcast = false) {
this.mainnet = mainnet;
const httpUrl = mainnet;
this.p2 = new Party2(P1_ENDPOINT);
this.useAsyncBroadcast = useAsyncBroadcast;
}
public async init() {
this.initDb();
return this.initMasterKey();
}
/**
* get the address of the specified index. If the index is omitted, will return the default address (of index 0).
* @param addressIndex HD index of the address to get
*/
public getAddress(addressIndex = 0): string {
const publicKey = this.getPublicKey(addressIndex);
const publicKeyHex = publicKey.encode('hex', true);
const publicKeyBuffer = Buffer.from(publicKeyHex, 'hex');
const address = terra.getAccAddress(publicKeyBuffer);
const dbAddress = this.db
.get('addresses')
.find({ address })
.value();
if (!dbAddress) {
this.db
.get('addresses')
.push({ address, index: addressIndex })
.write();
}
return address;
}
/**
* Execute a transfer transaction of two terra addresses
*/
public async transfer(
from: string,
to: string,
amount: string,
denom: Denom,
options?: SendOptions,
sendAll?: boolean,
dryRun?: boolean,
) {
const chainName: ChainName = (options && options.chainName) || 'vodka';
const chain_id = await getChainId(chainName);
if (sendAll) {
const balance = await getBalance(from, chainName);
console.log('balance=', balance);
amount = getAmountOfDenom(balance, denom);
console.log('Balance of', denom, 'is', amount);
// Lower amount by one to get correct gas estimation
amount = (Number(amount) - 1).toString();
}
let msgSend = terra.buildSend(
[
{
amount: amount,
denom: denom,
},
],
from,
to,
);
const [account_number, sequence] = await getAccountInfo(chainName, from);
console.log('msgSend=', msgSend);
const memo: string = (options && options.memo) || '';
const feeDenom: Denom = (options && options.feeDenom) || 'uluna';
// Need more gas when sending all, as gas estimation is for a failed transaction
const gasEstimate = await getGasEstimate(
msgSend,
feeDenom,
DEFULT_GAS_PRICE,
chainName,
);
console.log('gasEstimate=', gasEstimate);
// Update amount to deduct fees
if (sendAll) {
// Deduct the fees, add back the -1 we deducted for fee estimation
const updateAmount: number =
parseInt(amount) - parseInt(gasEstimate.amount[0].amount) + 1;
console.log('Updated amount=', updateAmount);
msgSend = terra.buildSend(
[
{
amount: updateAmount.toString(),
denom,
},
],
from,
to,
);
}
console.log('memo=', memo);
const stdTx = terra.buildStdTx([msgSend], gasEstimate, memo);
console.log('stdTX=', stdTx);
const signer = this.getMPCSigner(from);
const metaData: SignMetaData = {
sequence,
account_number,
chain_id,
};
// The nice thing is that our signer and the terra signer accept the same input
const signature: Signature = await getSingature(
stdTx.value,
signer,
metaData,
);
console.log('Manual Signature', signature);
const signedTx = terra.createSignedTx(stdTx.value, signature);
console.log('singedTx=', signedTx);
const broadcastBody = terra.createBroadcastBody(signedTx, 'block');
console.log('broadcastBody=', broadcastBody);
if (dryRun) {
console.log('------ Dry Run ----- ');
console.log(broadcastBody);
} else {
console.log(' ===== Executing ===== ');
console.log(broadcastBody);
const res = await post(chainName, `/txs`, JSON.parse(broadcastBody));
console.log('Send Res', res);
}
}
private initDb() {
ensureDirSync(CLIENT_DB_PATH);
const adapter = new FileSync(`${CLIENT_DB_PATH}/db.json`);
this.db = low(adapter);
this.db.defaults({ mkShare: null, addresses: [] }).write();
}
/**
* Initialize the client's master key.
* Will either generate a new one by the 2 party protocol, or restore one from previous session.
* @return {Promise}
*/
private async initMasterKey() {
this.p2MasterKeyShare = await this.restoreOrGenerateMasterKey();
}
/**
* @return {Elliptic.PublicKey} PubKey
*/
private getPublicKey(addressIndex: number) {
// assuming a single default address
const p2ChildShare = this.p2.getChildShare(
this.p2MasterKeyShare,
HD_COIN_INDEX,
addressIndex,
);
return p2ChildShare.getPublicKey();
}
private async restoreOrGenerateMasterKey(): Promise<Party2Share> {
const p2MasterKeyShare = this.db.get('mkShare').value();
if (p2MasterKeyShare) {
return p2MasterKeyShare;
}
return this.generateMasterKeyShare();
}
private async generateMasterKeyShare(): Promise<Party2Share> {
const p2MasterKeyShare: Party2Share = await this.p2.generateMasterKey();
this.db.set('mkShare', p2MasterKeyShare).write();
return p2MasterKeyShare;
}
private getMPCSigner(fromAddress: string) {
return async (signMessage: string) => {
const addressObj: any = this.db
.get('addresses')
.find({ address: fromAddress })
.value();
const addressIndex: number = addressObj.index;
const p2ChildShare: Party2Share = this.p2.getChildShare(
this.p2MasterKeyShare,
HD_COIN_INDEX,
addressIndex,
);
const signMessageString =
typeof signMessage === 'string'
? signMessage
: JSON.stringify(signMessage);
const signHash = Buffer.from(
CryptoJS.SHA256(signMessageString).toString(),
`hex`,
);
const signatureMPC: MPCSignature = await this.p2.sign(
signHash,
p2ChildShare,
HD_COIN_INDEX,
addressIndex,
);
const signature = signatureMPC.toBuffer();
console.log('sigBuffer=', signature);
const publicKeyBasePoint = this.getPublicKey(addressIndex);
const publicKeyHex = publicKeyBasePoint.encode('hex', true);
const publicKey = Buffer.from(publicKeyHex, 'hex');
console.log('publicKeyBuffer =', publicKey);
return { signature, publicKey };
};
}
}
/**
* // Get only the specific amount of a certain denom from the balance list
*/
function getAmountOfDenom(balanceResult: Balance, denom: Denom): string {
const value = balanceResult.result.find((res) => res.denom === denom);
return value ? value.amount : '';
}
function ensureDirSync(dirpath: string) {
try {
fs.mkdirSync(dirpath, { recursive: true });
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
/**
* Execute a transfer transaction using a mnemonic and regular libraries.
* Not using two party protocols
*/
export async function mnemonic_transfer(
mnemonic: string,
from: string,
to: string,
amount: string,
denom: Denom,
options?: SendOptions,
sendAll?: boolean,
dryRun?: boolean,
) {
const masterKey = terra.deriveMasterKeySync(mnemonic);
const keypair = terra.deriveKeypair(masterKey);
const chainName: ChainName = (options && options.chainName) || 'vodka';
const chain_id = await getChainId(chainName);
if (sendAll) {
const balance = await getBalance(from, chainName);
console.log('balance=', balance);
amount = getAmountOfDenom(balance, denom);
console.log('Balance of', denom, 'is', amount);
// Lower amount by one to get correct gas estimation
amount = (Number(amount) - 1).toString();
}
let msgSend = terra.buildSend(
[
{
amount: amount,
denom: denom,
},
],
from,
to,
);
const [account_number, sequence] = await getAccountInfo(chainName, from);
console.log('msgSend=', JSON.stringify(msgSend));
const memo: string = (options && options.memo) || '';
const feeDenom: Denom = (options && options.feeDenom) || 'uluna';
const gasEstimate = await getGasEstimate(
msgSend,
feeDenom,
DEFULT_GAS_PRICE,
chainName,
);
console.log('gasEstimate=', gasEstimate);
if (sendAll) {
const updateAmount: number =
parseInt(amount) - parseInt(gasEstimate.amount[0].amount);
console.log('Updated amount=', updateAmount);
msgSend = terra.buildSend(
[
{
amount: updateAmount.toString(),
denom,
},
],
from,
to,
);
}
console.log('memo=', memo);
console.log('msgSend=', JSON.stringify(msgSend));
const stdTx = terra.buildStdTx([msgSend], gasEstimate, memo);
console.log('stdTX=', stdTx);
const signer = await getSigner(keypair.privateKey.toString('hex'));
const metaData: SignMetaData = {
sequence,
account_number,
chain_id,
};
// The nice thing is that our signer and the terra signer accept the same input
const signature: Signature = await getSingature(
stdTx.value,
signer,
metaData,
);
console.log('Manual Signature', signature);
const jsonTx = stdTx.value;
const txSignature = terra.sign(jsonTx, keypair, {
sequence,
account_number,
chain_id,
});
console.log('txSignature=', txSignature);
const signedTx = terra.createSignedTx(stdTx.value, signature);
console.log('singedTx=', signedTx);
const broadcastBody = terra.createBroadcastBody(signedTx, 'block');
console.log('broadcastBody=', broadcastBody);
if (dryRun) {
console.log('------ Dry Run ----- ');
console.log(broadcastBody);
} else {
console.log(' ===== Executing ===== ');
console.log(broadcastBody);
const res = await post(chainName, `/txs`, JSON.parse(broadcastBody));
console.log('Send Res', res);
}
}