/
WalletFromMnemonics.ts
81 lines (66 loc) · 2.73 KB
/
WalletFromMnemonics.ts
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
const {
BlockHeaders,
DerivationPath,
ErgoBoxes,
ErgoStateContext,
ExtSecretKey,
Mnemonic,
PreHeader,
SecretKey,
SecretKeys,
UnsignedTransaction,
Wallet,
} = require('ergo-lib-wasm-browser');
import request from 'superagent';
import JSONBig from 'json-bigint';
import { UnsignedTx } from './connector_types';
export default class SignerWallet {
private wallet!: typeof Wallet;
private blockContext!: Object[];
constructor() {}
async fromMnemonics(mnemonics: string): Promise<SignerWallet> {
this.blockContext = await request
.get('https://api.ergoplatform.com/api/v1/blocks/headers?limit=10')
.then((resp) => resp.body.items);
this.wallet = await createWallet(mnemonics, this.blockContext);
return this;
}
sign(unsignedTx: UnsignedTx): string {
const unspentBoxes = ErgoBoxes.from_boxes_json(unsignedTx.inputs);
const dataInputBoxes = ErgoBoxes.from_boxes_json(unsignedTx.dataInputs);
const tx = UnsignedTransaction.from_json(JSONBig.stringify(unsignedTx));
const signed = this._sign(tx, unspentBoxes, dataInputBoxes);
return signed.to_json();
}
private _sign(unsigned: typeof UnsignedTransaction, unspentBoxes: typeof ErgoBoxes, dataInputBoxes: typeof ErgoBoxes) {
const blockHeaders = BlockHeaders.from_json(this.blockContext);
const preHeader = PreHeader.from_block_header(blockHeaders.get(0));
const signContext = new ErgoStateContext(preHeader, blockHeaders);
const signed = this.wallet.sign_transaction(signContext, unsigned, unspentBoxes, dataInputBoxes);
return signed;
}
}
async function createWallet(mnemonics: string, context: Object) {
const seed = Mnemonic.to_seed(
// "prevent hair cousin critic embrace okay burger choice pilot rice sure clerk absurd patrol tent",
mnemonics,
'',
);
const blockContext = await request
.get('https://api.ergoplatform.com/api/v1/blocks/headers?limit=10')
.then((resp) => resp.body.items);
// derive the root extended key/secret
const extendedSecretKey = ExtSecretKey.derive_master(seed);
// derive the initial secret key, this is the change key and is also the owner of the boxes used as inputs
const changePath = DerivationPath.from_string("m/44'/429'/0'/0/0");
const changeSk = extendedSecretKey.derive(changePath);
const baseAddress = extendedSecretKey.public_key().to_address();
const blockHeaders = BlockHeaders.from_json(blockContext);
const preHeader = PreHeader.from_block_header(blockHeaders.get(0));
const stateCtx = new ErgoStateContext(preHeader, blockHeaders);
const dlogSecret = SecretKey.dlog_from_bytes(changeSk.secret_key_bytes());
const secretKeys = new SecretKeys();
secretKeys.add(dlogSecret);
const wallet = Wallet.from_secrets(secretKeys);
return wallet;
}