-
Notifications
You must be signed in to change notification settings - Fork 47
/
WithdrawStakingRewards.tsx
344 lines (322 loc) · 11.6 KB
/
WithdrawStakingRewards.tsx
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import {BigNumber} from 'bignumber.js'
import React from 'react'
import {IntlShape} from 'react-intl'
import {Platform} from 'react-native'
import {showErrorDialog} from '../../../legacy/actions'
import type {RawUtxo} from '../../../legacy/api/types'
import type {WithdrawalDialogSteps} from '../../../legacy/components/Delegation/types'
import {WITHDRAWAL_DIALOG_STEPS} from '../../../legacy/components/Delegation/types'
import {CONFIG} from '../../../legacy/config/config'
import {WrongPassword} from '../../../legacy/crypto/errors'
import {ISignRequest} from '../../../legacy/crypto/ISignRequest'
import KeyStore from '../../../legacy/crypto/KeyStore'
import {MultiToken} from '../../../legacy/crypto/MultiToken'
import {HaskellShelleyTxSignRequest} from '../../../legacy/crypto/shelley/HaskellShelleyTxSignRequest'
import type {DeviceId, DeviceObj, HWDeviceInfo} from '../../../legacy/crypto/shelley/ledgerUtils'
import walletManager, {SystemAuthDisabled} from '../../../legacy/crypto/walletManager'
import {errorMessages} from '../../../legacy/i18n/global-messages'
import LocalizableError from '../../../legacy/i18n/LocalizableError'
import type {ServerStatusCache} from '../../../legacy/state'
import type {DefaultAsset} from '../../../legacy/types/HistoryTransaction'
import {AppRouteNavigation} from '../../navigation'
import {WithdrawalDialog} from './WithdrawalDialog'
type Props = {
intl: IntlShape
navigation: AppRouteNavigation
utxos: Array<RawUtxo> | null
setLedgerDeviceId: (deviceID: DeviceId) => Promise<void>
setLedgerDeviceObj: (deviceObj: DeviceObj) => Promise<void>
isHW: boolean
isEasyConfirmationEnabled: boolean
hwDeviceInfo: HWDeviceInfo
submitTransaction: (request: ISignRequest, text: string) => Promise<void>
submitSignedTx: (text: string) => Promise<void>
defaultAsset: DefaultAsset
serverStatus: ServerStatusCache
onDone: () => void
}
type State = {
withdrawalDialogStep: WithdrawalDialogSteps
useUSB: boolean
signTxRequest: HaskellShelleyTxSignRequest | null
withdrawals: Array<{
address: string
amount: MultiToken
}> | null
deregistrations: Array<{
rewardAddress: string
refund: MultiToken
}> | null
balance: BigNumber
finalBalance: BigNumber
fees: BigNumber
error: {
errorMessage: string | null
errorLogs?: string | null
}
}
// eslint-disable-next-line react-prefer-function-component/react-prefer-function-component
export class WithdrawStakingRewards extends React.Component<Props, State> {
state = {
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.WARNING,
useUSB: false,
signTxRequest: null,
withdrawals: null,
deregistrations: null,
balance: new BigNumber(0),
finalBalance: new BigNumber(0),
fees: new BigNumber(0),
error: {
errorMessage: null,
errorLogs: null,
},
}
_shouldDeregister = false
/* withdrawal logic */
openWithdrawalDialog = () =>
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.WARNING,
})
onKeepOrDeregisterKey = async (shouldDeregister: boolean): Promise<void> => {
this._shouldDeregister = shouldDeregister
if (this.props.isHW && Platform.OS === 'android' && CONFIG.HARDWARE_WALLETS.LEDGER_NANO.ENABLE_USB_TRANSPORT) {
// toggle ledger transport switch modal
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.CHOOSE_TRANSPORT,
})
} else {
await this.createWithdrawalTx()
}
}
/* create withdrawal tx and move to confirm */
createWithdrawalTx = async (): Promise<void> => {
const {intl, utxos, defaultAsset, serverStatus} = this.props
try {
if (utxos == null) throw new Error('cannot get utxos') // should never happen
this.setState({withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.WAITING})
const signTxRequest = await walletManager.createWithdrawalTx(
utxos,
this._shouldDeregister,
serverStatus.serverTime,
)
if (signTxRequest instanceof HaskellShelleyTxSignRequest) {
const withdrawals = await signTxRequest.withdrawals()
const deregistrations = await signTxRequest.keyDeregistrations()
const balance = withdrawals.reduce(
(sum, curr) => (curr.amount == null ? sum : sum.joinAddCopy(curr.amount)),
new MultiToken([], {
defaultNetworkId: defaultAsset.networkId,
defaultIdentifier: defaultAsset.identifier,
}),
)
const fees = await signTxRequest.fee()
const finalBalance = balance
.joinAddCopy(
deregistrations.reduce(
(sum, curr) => (curr.refund == null ? sum : sum.joinAddCopy(curr.refund)),
new MultiToken([], {
defaultNetworkId: defaultAsset.networkId,
defaultIdentifier: defaultAsset.identifier,
}),
),
)
.joinSubtractCopy(fees)
this.setState({
signTxRequest,
withdrawals,
deregistrations,
balance: balance.getDefault(),
finalBalance: finalBalance.getDefault(),
fees: fees.getDefault(),
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.CONFIRM,
})
} else {
throw new Error('unexpected withdrawal tx type')
}
} catch (e) {
if (e instanceof LocalizableError) {
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.ERROR,
error: {
errorMessage: intl.formatMessage({
id: (e as any).id,
defaultMessage: (e as any).defaultMessage,
}),
},
})
} else {
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.ERROR,
error: {
errorMessage: intl.formatMessage(errorMessages.generalError.message, {message: (e as any).message}),
},
})
}
}
}
openLedgerConnect = () =>
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.LEDGER_CONNECT,
})
onChooseTransport = async (event: Record<string, unknown>, useUSB: boolean): Promise<void> => {
const {hwDeviceInfo} = this.props
this.setState({useUSB})
if (
(useUSB && hwDeviceInfo.hwFeatures.deviceObj == null) ||
(!useUSB && hwDeviceInfo.hwFeatures.deviceId == null)
) {
this.openLedgerConnect()
} else {
await this.createWithdrawalTx()
}
}
onConnectUSB = async (deviceObj: DeviceObj): Promise<void> => {
await this.props.setLedgerDeviceObj(deviceObj)
await this.createWithdrawalTx()
}
onConnectBLE = async (deviceId: DeviceId): Promise<void> => {
await this.props.setLedgerDeviceId(deviceId)
await this.createWithdrawalTx()
}
// TODO: this code has been copy-pasted from the tx confirmation page.
// Ideally, all this logic should be moved away and perhaps written as a
// redux action that can be reused in all components with tx signing and sending
onConfirm = async (_event: Record<string, unknown>, password: string | void): Promise<void> => {
const {signTxRequest, useUSB} = this.state
const {intl, navigation, isHW, isEasyConfirmationEnabled, submitTransaction, submitSignedTx} = this.props
if (signTxRequest == null) throw new Error('no tx data')
const submitTx = async (tx: string | ISignRequest, decryptedKey?: string) => {
if (decryptedKey == null && typeof tx === 'string') {
await submitSignedTx(tx)
} else if (decryptedKey != null && !(typeof tx === 'string' || tx instanceof String)) {
await submitTransaction(tx, decryptedKey)
}
navigation.reset({
index: 0,
routes: [
{
name: 'app-root',
state: {
routes: [
{name: 'wallet-selection'},
{
name: 'main-wallet-routes',
state: {
routes: [
{
name: 'history',
state: {
routes: [{name: 'history-list'}],
},
},
],
},
},
],
},
},
],
})
}
try {
if (isHW) {
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.WAITING_HW_RESPONSE,
})
if (signTxRequest == null) throw new Error('no tx data')
const signedTx = await walletManager.signTxWithLedger(signTxRequest, useUSB)
this.setState({withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.WAITING})
await submitTx(Buffer.from(signedTx.encodedTx).toString('base64'))
this.closeWithdrawalDialog()
return
}
if (isEasyConfirmationEnabled) {
try {
await walletManager.ensureKeysValidity()
navigation.navigate('biometrics', {
keyId: walletManager._id,
onSuccess: async (decryptedKey) => {
await submitTx(signTxRequest, decryptedKey)
},
onFail: () => navigation.goBack(),
})
} catch (e) {
if (e instanceof SystemAuthDisabled) {
this.closeWithdrawalDialog()
await walletManager.closeWallet()
await showErrorDialog(errorMessages.enableSystemAuthFirst, intl)
navigation.navigate('app-root', {
screen: 'wallet-selection',
})
return
} else {
throw e
}
}
return
}
try {
this.setState({withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.WAITING})
const decryptedData = await KeyStore.getData(walletManager._id, 'MASTER_PASSWORD', '', password, intl)
await submitTx(signTxRequest, decryptedData)
this.closeWithdrawalDialog()
} catch (e) {
if (e instanceof WrongPassword) {
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.ERROR,
error: {
errorMessage: intl.formatMessage(errorMessages.incorrectPassword.message),
errorLogs: null,
},
})
} else {
throw e
}
}
} catch (e) {
if (e instanceof LocalizableError) {
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.ERROR,
error: {
errorMessage: intl.formatMessage(
{id: (e as any).id, defaultMessage: (e as any).defaultMessage},
(e as any).values,
),
errorLogs: (e as any).values.response || null,
},
})
} else {
this.setState({
withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.ERROR,
error: {
errorMessage: intl.formatMessage(errorMessages.generalTxError.message),
errorLogs: (e as any).message || null,
},
})
}
}
}
closeWithdrawalDialog = () => this.setState({withdrawalDialogStep: WITHDRAWAL_DIALOG_STEPS.CLOSED}, this.props.onDone)
render() {
return (
<WithdrawalDialog
step={this.state.withdrawalDialogStep}
onKeepKey={() => this.onKeepOrDeregisterKey(false)}
onDeregisterKey={() => this.onKeepOrDeregisterKey(true)}
onChooseTransport={this.onChooseTransport}
useUSB={this.state.useUSB}
onConnectBLE={this.onConnectBLE}
onConnectUSB={this.onConnectUSB}
withdrawals={this.state.withdrawals}
deregistrations={this.state.deregistrations}
balance={this.state.balance}
finalBalance={this.state.finalBalance}
fees={this.state.fees}
onConfirm={this.onConfirm}
onRequestClose={this.closeWithdrawalDialog}
error={this.state.error}
/>
)
}
}