-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathDepositWithdrawModal.tsx
More file actions
357 lines (322 loc) · 10.9 KB
/
DepositWithdrawModal.tsx
File metadata and controls
357 lines (322 loc) · 10.9 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
import { Decimal } from "@cosmjs/math";
import { isDeliverTxFailure } from "@cosmjs/stargate";
import { bech32 } from "bech32";
import React, { useCallback } from "react";
import { useForm } from "react-hook-form";
import { StyleSheet, View } from "react-native";
import ModalBase from "./ModalBase";
import arrowDivideSVG from "../../../assets/icons/arrow-divide.svg";
import { useFeedbacks } from "../../context/FeedbacksProvider";
import { useBalances } from "../../hooks/useBalances";
import useSelectedWallet from "../../hooks/useSelectedWallet";
import {
getCosmosNetwork,
getIBCCurrency,
getNativeCurrency,
getNetwork,
keplrCurrencyFromNativeCurrencyInfo,
} from "../../networks";
import { neutral77, primaryColor } from "../../utils/style/colors";
import {
fontRegular13,
fontRegular14,
fontRegular16,
} from "../../utils/style/fonts";
import { layout } from "../../utils/style/layout";
import { capitalize, tinyAddress } from "../../utils/text";
import { BrandText } from "../BrandText";
import { NetworkIcon } from "../NetworkIcon";
import { SVG } from "../SVG";
import { MaxButton } from "../buttons/MaxButton";
import { PrimaryButton } from "../buttons/PrimaryButton";
import { TextInputCustom } from "../inputs/TextInputCustom";
import { SpacerColumn, SpacerRow } from "../spacer";
import { getKeplrSigningStargateClient } from "@/networks/signer";
import { TransactionForm } from "@/utils/types/wallet";
type DepositModalProps = {
variation: "deposit" | "withdraw";
isVisible: boolean;
targetCurrency?: string;
networkId: string;
onClose: () => void;
};
export const DepositWithdrawModal: React.FC<DepositModalProps> = ({
variation,
isVisible,
onClose,
targetCurrency: targetCurrencyDenom,
networkId,
}) => {
const { setToastError } = useFeedbacks();
const selectedWallet = useSelectedWallet(); // FIXME: this could not match networkId
const ibcTargetCurrency = getIBCCurrency(networkId, targetCurrencyDenom);
const nativeTargetCurrency = getNativeCurrency(
ibcTargetCurrency?.sourceNetwork,
ibcTargetCurrency?.sourceDenom,
);
const sourceNetworkId =
variation === "withdraw" ? networkId : ibcTargetCurrency?.sourceNetwork;
const sourceNetwork = getNetwork(sourceNetworkId);
const destinationNetworkId =
variation === "withdraw" ? ibcTargetCurrency?.sourceNetwork : networkId;
const destinationNetwork = getNetwork(destinationNetworkId);
const fromAccount =
variation === "withdraw"
? selectedWallet?.address
: convertCosmosAddress(selectedWallet?.address, sourceNetworkId);
const toAccount =
variation === "withdraw"
? convertCosmosAddress(selectedWallet?.address, destinationNetworkId)
: selectedWallet?.address;
const { balances } = useBalances(sourceNetworkId, fromAccount);
const { control, setValue, handleSubmit } = useForm<TransactionForm>();
const ModalHeader = useCallback(
() => (
<View style={styles.rowCenter}>
<NetworkIcon networkId={networkId} size={32} />
<SpacerRow size={3} />
<BrandText style={[fontRegular16]}>
{variation === "deposit" ? "Deposit on" : "Withdraw from"}{" "}
{getNetwork(networkId)?.displayName || "Unknown"}
</BrandText>
</View>
),
[variation, networkId],
);
const maxAtomics =
(variation === "withdraw"
? balances.find((bal) => bal.denom === ibcTargetCurrency?.denom)
: balances.find((bal) => bal.denom === ibcTargetCurrency?.sourceDenom)
)?.amount || "0";
const max = Decimal.fromAtomics(
maxAtomics,
nativeTargetCurrency?.decimals || 0,
).toString();
return (
<ModalBase
visible={isVisible}
onClose={onClose}
Header={ModalHeader}
width={460}
>
<View style={styles.container}>
<BrandText style={[fontRegular14, styles.selfCenter]}>
{capitalize(variation)} {nativeTargetCurrency?.displayName}
</BrandText>
<SpacerColumn size={1.5} />
<View style={[styles.rowCenter, styles.w100, { zIndex: 2 }]}>
<View style={[styles.jcCenter, { zIndex: 2, flex: 1 }]}>
<View style={[styles.rowAllCenter, { zIndex: 2 }]}>
<NetworkIcon size={64} networkId={sourceNetworkId || "unknown"} />
</View>
<SpacerColumn size={1.5} />
<BrandText style={fontRegular14}>
From {sourceNetwork?.displayName || "Unknown"}
</BrandText>
<SpacerColumn size={1} />
<TextInputCustom<TransactionForm>
control={control}
variant="labelOutside"
name="fromAddress"
label=""
defaultValue={tinyAddress(fromAccount, 19)}
rules={{ required: true }}
disabled
/>
</View>
<SpacerRow size={1} />
<View style={styles.arrow}>
<SVG source={arrowDivideSVG} width={36} height={6} />
</View>
<SpacerRow size={1} />
<View style={[styles.jcCenter, { flex: 1 }]}>
<View style={[styles.rowAllCenter, { zIndex: 2 }]}>
<NetworkIcon
size={64}
networkId={destinationNetworkId || "unknown"}
/>
</View>
<SpacerColumn size={1.5} />
<BrandText style={fontRegular14}>
To {destinationNetwork?.displayName || "Unknown"}
</BrandText>
<SpacerColumn size={1} />
<TextInputCustom<TransactionForm>
control={control}
variant="labelOutside"
name="toAddress"
defaultValue={tinyAddress(toAccount, 19)}
label=""
rules={{ required: true }}
disabled
/>
</View>
</View>
<SpacerColumn size={4} />
{ibcTargetCurrency && (
<TextInputCustom<TransactionForm>
control={control}
variant="labelOutside"
label="Select Amount"
name="amount"
currency={keplrCurrencyFromNativeCurrencyInfo(nativeTargetCurrency)}
rules={{ required: true, max }}
placeHolder="0"
subtitle={
<BrandText style={[fontRegular13, { color: neutral77 }]}>
Available:{" "}
<BrandText style={[fontRegular13, { color: primaryColor }]}>
{max}
</BrandText>
</BrandText>
}
>
<MaxButton onPress={() => setValue("amount", max)} />
</TextInputCustom>
)}
<SpacerColumn size={4} />
<BrandText style={styles.estimatedText}>
Estimated Time: 20 Seconds
</BrandText>
<SpacerColumn size={1} />
<PrimaryButton
size="M"
text={capitalize(variation)}
fullWidth
disabled={max === "0"}
loader
onPress={handleSubmit(async (formValues) => {
try {
const sender = fromAccount;
if (!sender) {
throw new Error("no sender");
}
const receiver = toAccount;
if (!receiver) {
throw new Error("no receiver");
}
if (!nativeTargetCurrency) {
throw new Error("no native target currency");
}
if (!ibcTargetCurrency) {
throw new Error("no target currency");
}
if (!sourceNetwork) {
throw new Error("no source network");
}
if (!sourceNetworkId) {
throw new Error("missing source network id");
}
if (!destinationNetworkId) {
throw new Error("missing destination network id");
}
const denom =
variation === "withdraw"
? ibcTargetCurrency.denom
: ibcTargetCurrency.sourceDenom;
if (!denom) {
throw new Error("no source denom");
}
const amount = Decimal.fromUserInput(
formValues.amount,
nativeTargetCurrency.decimals,
).atomics;
const timeoutSeconds = 30;
const port =
variation === "withdraw"
? ibcTargetCurrency.destinationChannelPort
: ibcTargetCurrency.sourceChannelPort;
const channelId =
variation === "withdraw"
? ibcTargetCurrency.destinationChannelId
: ibcTargetCurrency.sourceChannelId;
const client =
await getKeplrSigningStargateClient(sourceNetworkId);
const tx = await client.sendIbcTokens(
sender,
receiver,
{ amount, denom },
port,
channelId,
undefined,
(Date.now() + timeoutSeconds * 1000) * 1000000,
"auto",
);
if (isDeliverTxFailure(tx)) {
console.error(variation, "tx failed", tx);
setToastError({ title: "Transaction failed", message: "" });
}
// FIXME: find out if it's possible to check for ibc ack
} catch (err) {
console.error(variation, "failed", err);
if (err instanceof Error) {
setToastError({
title: "Failed to " + variation,
message: err.message,
});
}
}
onClose();
})}
/>
</View>
</ModalBase>
);
};
// FIXME: remove StyleSheet.create
// eslint-disable-next-line no-restricted-syntax
const styles = StyleSheet.create({
selfCenter: {
alignSelf: "center",
},
w100: { width: "100%" },
rowCenter: {
flexDirection: "row",
alignItems: "center",
},
leftChevron: {
position: "absolute",
left: -(layout.spacing_x3 * 2),
},
rightChevron: {
position: "absolute",
right: -(layout.spacing_x3 * 2),
},
jcCenter: {
justifyContent: "center",
alignItems: "center",
},
rowAllCenter: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
flex: 1,
},
arrow: {
alignSelf: "flex-start",
marginTop: 64 / 2,
},
container: {
paddingBottom: layout.spacing_x3,
},
estimatedText: StyleSheet.flatten([fontRegular14, { color: neutral77 }]),
});
const convertCosmosAddress = (
sourceAddress: string | undefined,
targetNetworkId: string | undefined,
) => {
if (!sourceAddress) {
return undefined;
}
const targetNetwork = getCosmosNetwork(targetNetworkId);
if (!targetNetwork) {
return undefined;
}
try {
const decoded = bech32.decode(sourceAddress);
return bech32.encode(targetNetwork.addressPrefix, decoded.words);
} catch (err) {
console.warn("failed to convert cosmos address", sourceAddress, err);
return undefined;
}
};