on df0c310 help sign in
bridge/src/views/UrbitID/SetProxy.jsx
339 lines 9.5 kB history raw
1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
3import { Grid, Text, Flex, Button } from 'indigo-react';
4import * as azimuth from 'azimuth-js';
6import './SetProxy.scss';
8import { useNetwork } from 'store/network';
9import { usePointCache } from 'store/pointCache';
10import { usePointCursor } from 'store/pointCursor';
11import { useRollerStore } from 'store/rollerStore';
13import {
14 PROXY_TYPE,
15 proxyTypeToHuman,
16 proxyTypeToHumanDescription,
17 proxyTypeToL1TxnType,
18} from 'lib/proxy';
19import * as need from 'lib/need';
20import { useLocalRouter } from 'lib/LocalRouter';
21import { eqAddr, isZeroAddress } from 'lib/utils/address';
22import { capitalize } from 'lib/capitalize';
23import useEthereumTransaction from 'lib/useEthereumTransaction';
24import useRoller from 'lib/useRoller';
26import InlineEthereumTransaction from 'components/InlineEthereumTransaction';
27import { ETH_ZERO_ADDR, GAS_LIMITS } from 'lib/constants';
28import { AddressInput } from 'form/Inputs';
29import {
30 composeValidator,
31 buildCheckboxValidator,
32 buildAddressValidator,
33} from 'form/validators';
34import BridgeForm from 'form/BridgeForm';
35import FormError from 'form/FormError';
36import Window from 'components/L2/Window/Window';
37import HeaderPane from 'components/L2/Window/HeaderPane';
38import BodyPane from 'components/L2/Window/BodyPane';
39import { Row } from '@tlon/indigo-react';
41import './SetProxy.scss';
43const getL2ProxyName = proxy =>
44 proxy === PROXY_TYPE.MANAGEMENT
45 ? 'manage'
46 : proxy === PROXY_TYPE.SPAWN
47 ? 'spawn'
48 : proxy === PROXY_TYPE.TRANSFER
49 ? 'transfer'
50 : '';
52const proxyFromDetails = (details, contracts, proxyType) => {
53 switch (proxyType) {
54 case PROXY_TYPE.MANAGEMENT:
55 return details.managementProxy;
56 case PROXY_TYPE.SPAWN:
57 return details.spawnProxy;
58 case PROXY_TYPE.TRANSFER:
59 return details.transferProxy;
60 case PROXY_TYPE.VOTING:
61 if (eqAddr(details.votingProxy, contracts.delegatedSending.address)) {
62 return `${details.votingProxy} (invites contract)`;
63 } else {
64 return details.votingProxy;
65 }
66 default:
67 throw new Error(`Unknown proxyType: ${proxyType}`);
68 }
69};
71const getButtonText = proxyType => {
72 switch (proxyType) {
73 case PROXY_TYPE.MANAGEMENT:
74 return 'Set Management Proxy';
75 case PROXY_TYPE.SPAWN:
76 return 'Set Spawn Proxy';
77 case PROXY_TYPE.TRANSFER:
78 return 'Set Transfer Proxy';
79 default:
80 return 'Set Management Proxy';
81 }
82};
84function useSetProxy(proxyType) {
85 const { contracts } = useNetwork();
86 const { pointCursor } = usePointCursor();
87 const { syncDetails } = usePointCache();
89 const _contracts = need.contracts(contracts);
90 const _point = need.point(pointCursor);
92 const { construct, ...rest } = useEthereumTransaction(
93 useCallback(
94 address => {
95 const txArgs = [_contracts, _point, address];
97 switch (proxyType) {
98 case PROXY_TYPE.MANAGEMENT:
99 return azimuth.ecliptic.setManagementProxy(...txArgs);
100 case PROXY_TYPE.SPAWN:
101 return azimuth.ecliptic.setSpawnProxy(...txArgs);
102 case PROXY_TYPE.TRANSFER:
103 return azimuth.ecliptic.setTransferProxy(...txArgs);
104 case PROXY_TYPE.VOTING:
105 return azimuth.ecliptic.setVotingProxy(...txArgs);
106 default:
107 throw new Error(`Unknown proxyType ${proxyType}`);
108 }
109 },
110 [_contracts, _point, proxyType]
111 ),
112 useCallback(() => syncDetails(_point), [_point, syncDetails]),
113 GAS_LIMITS.SET_PROXY
114 );
116 // force-unset
117 const unset = useCallback(() => {
118 construct(ETH_ZERO_ADDR);
119 }, [construct]);
121 return {
122 construct,
123 unset,
124 ...rest,
125 };
128export default function SetProxy() {
129 const { data, pop } = useLocalRouter();
130 const { contracts } = useNetwork();
131 const { point, setLoading } = useRollerStore();
132 const {
133 setProxyAddress,
134 getPendingTransactions,
135 checkForUpdates,
136 } = useRoller();
137 const [newAddress, setNewAddress] = useState('');
139 const _contracts = need.contracts(contracts);
141 const humanProxyType = proxyTypeToHuman(data.proxyType);
142 const properProxyType = capitalize(humanProxyType);
144 const { isL2, isL2Spawn } = point;
146 const isL2Tx =
147 (data.proxyType === 'MANAGEMENT' && isL2) ||
148 (data.proxyType === 'SPAWN' && isL2Spawn) ||
149 (data.proxyType === 'TRANSFER' && isL2);
151 const {
152 construct,
153 unconstruct,
154 unset,
155 inputsLocked,
156 completed,
157 bind,
158 txHashes,
159 } = useSetProxy(data.proxyType);
161 const setProxy = useCallback(async () => {
162 setLoading(true);
163 if (newAddress === '') return;
164 try {
165 await setProxyAddress(getL2ProxyName(data.proxyType), newAddress);
167 checkForUpdates({
168 point: point,
169 message: `${point.patp}'s ${humanProxyType} proxy has been set!`,
170 });
172 getPendingTransactions(point.value);
173 pop();
174 } catch (error) {
175 // setError(error);
176 } finally {
177 setLoading(false);
178 }
179 }, [
180 newAddress,
181 getPendingTransactions,
182 point,
183 pop,
184 data.proxyType,
185 setProxyAddress,
186 setLoading,
187 checkForUpdates,
188 humanProxyType,
189 ]);
191 useEffect(() => {
192 if (completed) {
193 checkForUpdates({
194 point: point,
195 message: `${point.patp}'s ${humanProxyType} proxy has been set!`,
196 l1Txn: {
197 id: `${newAddress}-${point.value}`,
198 point: point.value,
199 type: proxyTypeToL1TxnType(data.proxyType),
200 hash: txHashes[0],
201 time: new Date().getTime(),
202 },
203 });
204 }
205 }, [completed]); // eslint-disable-line react-hooks/exhaustive-deps
207 const validateForm = useCallback((values, errors) => {
208 if (!values.unset && errors.address) {
209 return errors;
210 }
211 }, []);
213 const validate = useMemo(
214 () =>
215 composeValidator(
216 {
217 unset: buildCheckboxValidator(),
218 address: buildAddressValidator(),
219 },
220 validateForm
221 ),
222 [validateForm]
223 );
225 const onValues = useCallback(
226 ({ valid, values, form }) => {
227 if (valid) {
228 if (values.unset) {
229 unset();
230 form.change('address', '');
231 setNewAddress('');
232 } else {
233 construct(values.address);
234 setNewAddress(values.address);
235 }
236 } else {
237 unconstruct();
238 }
239 },
240 [construct, unconstruct, unset, setNewAddress]
241 );
243 const initialValues = useMemo(() => ({ unset: false }), []);
245 const proxyAddress = proxyFromDetails(point, _contracts, data.proxyType);
246 const isProxySet = !isZeroAddress(proxyAddress);
248 const header = useMemo(() => {
249 const pfix = completed ? 'New' : 'Edit';
250 return `${pfix} ${properProxyType} Key`;
251 }, [completed, properProxyType]);
253 return (
254 <Window className="set-proxy">
255 <HeaderPane>
256 <Row className="header-row">
257 <h5>{header}</h5>
258 </Row>
259 </HeaderPane>
260 <BodyPane>
261 <Grid className="w-full">
262 {!completed && (
263 <>
264 <Grid.Item full as={Text} className="mb4 f5">
265 {proxyTypeToHumanDescription(data.proxyType)}
266 </Grid.Item>
267 <Grid.Item
268 full
269 as={Text}
270 className={cn('f5', {
271 green3: completed,
272 })}>
273 Current
274 </Grid.Item>
275 </>
276 )}
278 <BridgeForm
279 validate={validate}
280 onValues={onValues}
281 initialValues={initialValues}>
282 {({ handleSubmit, values }) => (
283 <>
284 <Grid.Item full as={Flex} row justify="between" align="center">
285 <Flex.Item
286 flex
287 as={Text}
288 style={{ overflowWrap: 'anywhere' }}
289 className={cn('mono mv3 gray4', {
290 black: !completed && isProxySet,
291 gray4: !completed && !isProxySet,
292 green3: completed,
293 })}>
294 {isProxySet ? proxyAddress : 'Not set'}
295 </Flex.Item>
296 </Grid.Item>
298 {completed ? (
299 <Grid.Item full className="mb4" />
300 ) : (
301 <Grid.Item
302 full
303 as={AddressInput}
304 className="mv4"
305 name="address"
306 label={`New ${properProxyType} Address`}
307 disabled={inputsLocked || values.unset}
308 />
309 )}
311 <Grid.Item full as={FormError} />
313 {isL2Tx ? (
314 <Grid.Item
315 as={Button}
316 full
317 className="set-proxy"
318 center
319 solid
320 disabled={values.unset}
321 onClick={setProxy}>
322 {getButtonText(data.proxyType)}
323 </Grid.Item>
324 ) : (
325 <Grid.Item
326 full
327 as={InlineEthereumTransaction}
328 {...bind}
329 onReturn={() => pop()}
330 />
331 )}
332 </>
333 )}
334 </BridgeForm>
335 </Grid>
336 </BodyPane>
337 </Window>
338 );