This repository has been archived by the owner on Jul 31, 2020. It is now read-only.
forked from input-output-hk/js-chain-libs
-
Notifications
You must be signed in to change notification settings - Fork 3
/
wasmWrapper.js
250 lines (230 loc) · 7.03 KB
/
wasmWrapper.js
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
// @flow
import config from 'config';
import type { AccountKeys, NodeSettings } from '../reducers/types';
import type {
PrivateKey as InternalPrivateKey,
Counter,
Delegation,
TransactionOutput
} from '../models';
import feeCalculator from './feeCalculator';
import { totalParts } from './proportionsHelper';
const wasmBindings = import('js-chain-libs/js_chain_libs');
export async function getAccountFromPrivateKey(
secret: InternalPrivateKey
): Promise<AccountKeys> {
const { PrivateKey } = await wasmBindings;
const privateKey: PrivateKey = PrivateKey.from_bech32(secret);
return getAccountDataFromPrivateKey(privateKey);
}
export async function getAccountFromSeed(
seed: Uint8Array
): Promise<AccountKeys> {
const { PrivateKey } = await wasmBindings;
const privateKey: PrivateKey = PrivateKey.from_normal_bytes(
seed.slice(0, 32)
);
return getAccountDataFromPrivateKey(privateKey);
}
async function getAccountDataFromPrivateKey(
privateKey: any
): Promise<AccountKeys> {
const {
PublicKey,
Account,
AccountIdentifier,
AddressDiscrimination
} = await wasmBindings;
const publicKey: PublicKey = privateKey.to_public();
const secret = privateKey.to_bech32();
const account: Account = Account.single_from_public_key(publicKey);
const identifier: AccountIdentifier = account.to_identifier();
const networkDiscrimination: AddressDiscrimination =
config.get('networkDiscrimination') === 'testnet'
? AddressDiscrimination.Test
: AddressDiscrimination.Production;
const address: string = account
.to_address(networkDiscrimination)
.to_string(config.get('addressPrefix'));
return {
address,
privateKey: secret,
identifier: identifier.to_hex()
};
}
export async function buildDelegateTransaction(
newDelegation: Delegation,
secret: InternalPrivateKey,
accountCounter: Counter,
nodeSettings: NodeSettings
): Promise<{ id: string, transaction: Uint8Array, fee: number }> {
const {
PoolId,
Certificate,
StakeDelegation,
DelegationType,
DelegationRatio,
PoolDelegationRatios,
PoolDelegationRatio,
PrivateKey,
PublicKey
} = await wasmBindings;
const privateKey: PrivateKey = PrivateKey.from_bech32(secret);
const sourcePublicKey: PublicKey = privateKey.to_public();
let delegationType: DelegationType;
const pools: Array<PoolId> = Object.keys(newDelegation);
if (pools.length === 0) {
delegationType = DelegationType.non_delegated();
} else if (pools.length === 1) {
delegationType = DelegationType.full(PoolId.from_hex(pools[0]));
} else {
const poolDelegationRatios = PoolDelegationRatios.new();
pools.forEach(poolId =>
poolDelegationRatios.add(
PoolDelegationRatio.new(
PoolId.from_hex(poolId),
newDelegation[poolId].parts
)
)
);
delegationType = DelegationType.ratio(
DelegationRatio.new(totalParts(newDelegation), poolDelegationRatios)
);
}
// Create certificate
const certificate: Certificate = Certificate.stake_delegation(
StakeDelegation.new(delegationType, sourcePublicKey)
);
return buildTransaction(secret, nodeSettings, accountCounter, certificate);
}
export async function buildSendFundsTransaction(
destination: string,
amount: number,
secret: InternalPrivateKey,
accountCounter: number,
nodeSettings: NodeSettings
): Promise<{ id: string, transaction: Uint8Array, fee: number }> {
return buildTransaction(secret, nodeSettings, accountCounter, undefined, {
amount,
address: destination
});
}
async function buildTransaction(
secret: string,
nodeSettings: NodeSettings,
accountCounter: number,
certificate?: any,
output?: TransactionOutput
) {
if (!certificate && !output) {
console.error(
'it doesnt make sense to send a transaction with only an input'
);
} else if (certificate && output) {
console.error(
'in the wallet theres no way of sending a trasaction with both an output and a certificate, this is an error'
);
}
const {
OutputPolicy,
Address,
TransactionBuilder,
InputOutput,
InputOutputBuilder,
Payload,
Witnesses,
PayloadAuthData,
Transaction,
TransactionBuilderSetWitness,
TransactionBuilderSetAuthData,
TransactionBuilderSetIOs,
StakeDelegationAuthData,
AccountBindingSignature,
Input,
Value,
Fee,
Fragment,
PrivateKey,
Witness,
SpendingCounter,
Hash,
Account,
// eslint-disable-next-line camelcase
uint8array_to_hex
} = await wasmBindings;
const { calculateFee } = feeCalculator(nodeSettings);
const privateKey: PrivateKey = PrivateKey.from_bech32(secret);
const sourceAccount: Account = Account.single_from_public_key(
privateKey.to_public()
);
const computedFee: number = calculateFee(
1,
output ? 1 : 0,
certificate ? 1 : 0
);
const iobuilder: InputOutputBuilder = InputOutputBuilder.empty();
let inputAmount;
if (output) {
inputAmount = output.amount + computedFee;
iobuilder.add_output(
Address.from_string(output.address),
Value.from_str(output.amount.toString())
);
} else {
inputAmount = computedFee;
}
const input: Input = Input.from_account(
sourceAccount,
Value.from_str(inputAmount.toString())
);
iobuilder.add_input(input);
const feeAlgorithm: Fee = Fee.linear_fee(
Value.from_str(nodeSettings.fees.constant.toString()),
Value.from_str(nodeSettings.fees.coefficient.toString()),
Value.from_str(nodeSettings.fees.certificate.toString())
);
// The amount is exact, that's why we use `forget()`
const IOs: InputOutput = iobuilder.seal_with_output_policy(
certificate ? Payload.certificate(certificate) : Payload.no_payload(),
feeAlgorithm,
OutputPolicy.forget()
);
const txbuilder: TransactionBuilder = new TransactionBuilder();
const builderSetIOs: TransactionBuilderSetIOs = certificate
? txbuilder.payload(certificate)
: txbuilder.no_payload();
const builderSetWitness: TransactionBuilderSetWitness = builderSetIOs.set_ios(
IOs.inputs(),
IOs.outputs()
);
const witness: Witness = Witness.for_account(
Hash.from_hex(nodeSettings.block0Hash),
builderSetWitness.get_auth_data_for_witness(),
privateKey,
SpendingCounter.from_u32(accountCounter)
);
const witnesses: Witness = Witnesses.new();
witnesses.add(witness);
const builderSignCertificate: TransactionBuilderSetAuthData = builderSetWitness.set_witnesses(
witnesses
);
const signature: PayloadAuthData = certificate
? PayloadAuthData.for_stake_delegation(
StakeDelegationAuthData.new(
AccountBindingSignature.new_single(
PrivateKey.from_bech32(secret),
builderSignCertificate.get_auth_data()
)
)
)
: PayloadAuthData.for_no_payload();
const signedTx: Transaction = builderSignCertificate.set_payload_auth(
signature
);
const message: Fragment = Fragment.from_transaction(signedTx);
return {
transaction: message.as_bytes(),
id: uint8array_to_hex(message.id().as_bytes()),
fee: computedFee
};
}