-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.tsx
243 lines (199 loc) · 7.75 KB
/
index.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
import React, { useCallback, useEffect, useState } from "react";
import { Contract, ethers } from "ethers";
import { BigNumber } from "@ethersproject/bignumber";
import { BigNumberInput } from "big-number-input";
import { Button, Select, Text, TextField, Loader } from "@gnosis.pm/safe-react-components";
import { SafeInfo, SdkInstance } from "@gnosis.pm/safe-apps-sdk";
import DurationInput, { Duration } from "./DurationInput";
import erc20Abi from "../../abis/erc20";
import createEthStreamTxs from "../../utils/transactions/createEthStream";
import createStreamTxs from "../../utils/transactions/createStream";
import provider from "../../config/provider";
import { ButtonContainer, SelectContainer } from "../../theme/components";
import { Transaction } from "../../typings";
import { bigNumberToHumanFormat } from "../../utils";
import { getTokenList, TokenItem } from "../../config/tokens";
export type Props = {
appsSdk: SdkInstance;
safeInfo?: SafeInfo;
toggleShouldDisplayStreams: Function;
};
function CreateStreamForm({ appsSdk, safeInfo, toggleShouldDisplayStreams }: Props) {
/** State Variables **/
const [amountError, setAmountError] = useState<string | undefined>();
const [duration, setDuration] = useState<Duration>({
label: "Duration",
totalSeconds: BigNumber.from(0),
});
const [recipient, setRecipient] = useState<string>("");
const [selectedToken, setSelectedToken] = useState<TokenItem>();
const [streamAmount, setStreamAmount] = useState<string>("");
const [tokenBalance, setTokenBalance] = useState<string>("0");
const [tokenInstance, setTokenInstance] = useState<Contract>();
const [tokenList, setTokenList] = useState<TokenItem[]>();
/** Callbacks **/
const humanTokenBalance = useCallback((): string => {
return selectedToken ? bigNumberToHumanFormat(tokenBalance, selectedToken.decimals) : "";
}, [selectedToken, tokenBalance]);
const validateAmountValue = useCallback((): boolean => {
setAmountError(undefined);
const currentValueBN: BigNumber = BigNumber.from(streamAmount);
const comparisonValueBN: BigNumber = BigNumber.from(tokenBalance);
if (currentValueBN.gt(comparisonValueBN)) {
setAmountError(`You only have ${humanTokenBalance()} ${selectedToken && selectedToken.label} in your Safe`);
return false;
}
return true;
}, [humanTokenBalance, selectedToken, streamAmount, tokenBalance]);
const createStream = useCallback((): void => {
/* We call in this way to ensure all errors are displayed to user */
const amountValid = validateAmountValue();
if (!safeInfo || !selectedToken || !amountValid || !duration || !duration?.label || !duration?.totalSeconds) {
return;
}
/* TODO: Stream initiation must be approved by other owners within an hour */
const totalSeconds: number = duration.totalSeconds.toNumber();
const currentUnix: number = Math.floor(new Date().getTime() / 1000);
const startTime: BigNumber = BigNumber.from(currentUnix).add(3600);
const stopTime: BigNumber = startTime.add(totalSeconds);
const bnStreamAmount = BigNumber.from(streamAmount);
const safeStreamAmount = bnStreamAmount.sub(bnStreamAmount.mod(totalSeconds));
let txs: Transaction[];
if (selectedToken.id === "ETH") {
/* If streaming ETH we need to wrap it first. */
txs = createEthStreamTxs(
safeInfo.network,
recipient,
safeStreamAmount.toString(),
startTime.toString(),
stopTime.toString(),
);
} else {
txs = createStreamTxs(
safeInfo.network,
recipient,
safeStreamAmount.toString(),
tokenInstance?.address || "",
startTime.toString(),
stopTime.toString(),
);
}
appsSdk.sendTransactions(txs);
setStreamAmount("");
setRecipient("");
}, [appsSdk, duration, recipient, safeInfo, selectedToken, streamAmount, tokenInstance, validateAmountValue]);
const isButtonDisabled = useCallback((): boolean => {
return (
streamAmount.length === 0 ||
streamAmount === "0" ||
Boolean(amountError) ||
!duration.totalSeconds ||
duration.totalSeconds.isZero()
);
}, [amountError, duration, streamAmount]);
const onSelectItem = useCallback(
(id: string): void => {
if (!tokenList) {
return;
}
const newSelectedToken = tokenList.find(t => {
return t.id === id;
});
if (!newSelectedToken) {
return;
}
setSelectedToken(newSelectedToken);
},
[setSelectedToken, tokenList],
);
const onAmountChange = useCallback((value: string): void => {
setAmountError(undefined);
setStreamAmount(value);
}, []);
const onUpdateDuration = useCallback(
(newDuration: Duration): void => {
setDuration(newDuration);
},
[setDuration],
);
/** Side Effects **/
/* Load tokens list and initialize with DAI */
useEffect(() => {
if (!safeInfo) {
return;
}
const tokenListRes: TokenItem[] = getTokenList(safeInfo.network);
setTokenList(tokenListRes);
const findDaiRes: TokenItem | undefined = tokenListRes.find(t => t.id === "DAI");
setSelectedToken(findDaiRes);
}, [safeInfo]);
/* Clear the form every time the user changes the token */
useEffect(() => {
if (!selectedToken) {
return;
}
setTokenBalance("0");
setStreamAmount("");
setAmountError(undefined);
setTokenInstance(new ethers.Contract(selectedToken.address, erc20Abi, provider));
}, [selectedToken]);
useEffect(() => {
const getData = async () => {
if (!safeInfo || !selectedToken || !tokenInstance) {
return;
}
/* Wait until token is correctly updated */
if (selectedToken?.address.toLocaleLowerCase() !== tokenInstance?.address.toLocaleLowerCase()) {
return;
}
/* Get token Balance */
let newTokenBalance: string;
if (selectedToken.id === "ETH") {
newTokenBalance = ethers.utils.parseEther(safeInfo.ethBalance).toString();
} else {
newTokenBalance = await tokenInstance.balanceOf(safeInfo.safeAddress);
}
/* Update all the values in a row to avoid UI flickers */
setTokenBalance(newTokenBalance);
};
getData();
}, [safeInfo, selectedToken, tokenInstance]);
if (!selectedToken) {
return <Loader size="md" />;
}
return (
<>
<Text size="lg">What token do you want to use?</Text>
<SelectContainer>
<Select items={tokenList || []} activeItemId={selectedToken.id} onItemClick={onSelectItem} />
<Text size="lg">{humanTokenBalance()}</Text>
</SelectContainer>
<Text size="lg">How much do you want to stream in total?</Text>
<SelectContainer>
<BigNumberInput
decimals={selectedToken.decimals}
onChange={onAmountChange}
value={streamAmount}
renderInput={(props: any) => (
<TextField label="Amount" value={props.value} onChange={props.onChange} meta={{ error: amountError }} />
)}
/>
</SelectContainer>
<Text size="lg">Who would you like to stream to?</Text>
<SelectContainer>
<TextField label="Recipient" value={recipient} onChange={(event): void => setRecipient(event.target.value)} />
</SelectContainer>
<Text size="lg">For how long should the money be streamed?</Text>
<DurationInput duration={duration} onUpdateDuration={onUpdateDuration} />
<ButtonContainer>
<Button size="lg" color="primary" variant="contained" onClick={createStream} disabled={isButtonDisabled()}>
Create Stream
</Button>
<Button size="lg" color="secondary" variant="contained" onClick={() => toggleShouldDisplayStreams()}>
Manage Created Streams
</Button>
</ButtonContainer>
</>
);
}
export default CreateStreamForm;