on cd270be help sign in
bridge/src/views/UrbitID/SetProxy.js
335 lines 9.3 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';
41const getL2ProxyName = proxy =>
42 proxy === PROXY_TYPE.MANAGEMENT
43 ? 'manage'
44 : proxy === PROXY_TYPE.SPAWN
45 ? 'spawn'
46 : proxy === PROXY_TYPE.TRANSFER
47 ? 'transfer'
48 : '';
50const proxyFromDetails = (details, contracts, proxyType) => {
51 switch (proxyType) {
52 case PROXY_TYPE.MANAGEMENT:
53 return details.managementProxy;
54 case PROXY_TYPE.SPAWN:
55 return details.spawnProxy;
56 case PROXY_TYPE.TRANSFER:
57 return details.transferProxy;
58 case PROXY_TYPE.VOTING:
59 if (eqAddr(details.votingProxy, contracts.delegatedSending.address)) {
60 return `${details.votingProxy} (invites contract)`;
61 } else {
62 return details.votingProxy;
63 }
64 default:
65 throw new Error(`Unknown proxyType: ${proxyType}`);
66 }
67};
69const getButtonText = proxyType => {
70 switch (proxyType) {
71 case PROXY_TYPE.MANAGEMENT:
72 return 'Set Management Proxy';
73 case PROXY_TYPE.SPAWN:
74 return 'Set Spawn Proxy';
75 case PROXY_TYPE.TRANSFER:
76 return 'Set Transfer Proxy';
77 default:
78 return 'Set Management Proxy';
79 }
80};
82function useSetProxy(proxyType) {
83 const { contracts } = useNetwork();
84 const { pointCursor } = usePointCursor();
85 const { syncDetails } = usePointCache();
87 const _contracts = need.contracts(contracts);
88 const _point = need.point(pointCursor);
90 const { construct, ...rest } = useEthereumTransaction(
91 useCallback(
92 address => {
93 const txArgs = [_contracts, _point, address];
95 switch (proxyType) {
96 case PROXY_TYPE.MANAGEMENT:
97 return azimuth.ecliptic.setManagementProxy(...txArgs);
98 case PROXY_TYPE.SPAWN:
99 return azimuth.ecliptic.setSpawnProxy(...txArgs);
100 case PROXY_TYPE.TRANSFER:
101 return azimuth.ecliptic.setTransferProxy(...txArgs);
102 case PROXY_TYPE.VOTING:
103 return azimuth.ecliptic.setVotingProxy(...txArgs);
104 default:
105 throw new Error(`Unknown proxyType ${proxyType}`);
106 }
107 },
108 [_contracts, _point, proxyType]
109 ),
110 useCallback(() => syncDetails(_point), [_point, syncDetails]),
111 GAS_LIMITS.SET_PROXY
112 );
114 // force-unset
115 const unset = useCallback(() => {
116 construct(ETH_ZERO_ADDR);
117 }, [construct]);
119 return {
120 construct,
121 unset,
122 ...rest,
123 };
126export default function SetProxy() {
127 const { data, pop } = useLocalRouter();
128 const { contracts } = useNetwork();
129 const { point, setLoading } = useRollerStore();
130 const {
131 setProxyAddress,
132 getPendingTransactions,
133 checkForUpdates,
134 } = useRoller();
135 const [newAddress, setNewAddress] = useState('');
137 const _contracts = need.contracts(contracts);
139 const humanProxyType = proxyTypeToHuman(data.proxyType);
140 const properProxyType = capitalize(humanProxyType);
142 const { isL2, isL2Spawn } = point;
144 const isL2Tx =
145 (data.proxyType === 'MANAGEMENT' && isL2) ||
146 (data.proxyType === 'SPAWN' && isL2Spawn) ||
147 (data.proxyType === 'TRANSFER' && isL2);
149 const {
150 construct,
151 unconstruct,
152 unset,
153 inputsLocked,
154 completed,
155 bind,
156 txHashes,
157 } = useSetProxy(data.proxyType);
159 const setProxy = useCallback(async () => {
160 setLoading(true);
161 if (newAddress === '') return;
162 try {
163 await setProxyAddress(getL2ProxyName(data.proxyType), newAddress);
165 checkForUpdates({
166 point: point.value,
167 message: `${point.patp}'s ${humanProxyType} proxy has been set!`,
168 });
170 getPendingTransactions(point.value);
171 pop();
172 } catch (error) {
173 // setError(error);
174 } finally {
175 setLoading(false);
176 }
177 }, [
178 newAddress,
179 getPendingTransactions,
180 point,
181 pop,
182 data.proxyType,
183 setProxyAddress,
184 setLoading,
185 checkForUpdates,
186 humanProxyType,
187 ]);
189 useEffect(() => {
190 if (completed) {
191 checkForUpdates({
192 point: point.value,
193 message: `${point.patp}'s ${humanProxyType} proxy has been set!`,
194 l1Txn: {
195 id: `${newAddress}-${point.value}`,
196 point: point.value,
197 type: proxyTypeToL1TxnType(data.proxyType),
198 hash: txHashes[0],
199 },
200 });
201 }
202 }, [completed]); // eslint-disable-line react-hooks/exhaustive-deps
204 const validateForm = useCallback((values, errors) => {
205 if (!values.unset && errors.address) {
206 return errors;
207 }
208 }, []);
210 const validate = useMemo(
211 () =>
212 composeValidator(
213 {
214 unset: buildCheckboxValidator(),
215 address: buildAddressValidator(),
216 },
217 validateForm
218 ),
219 [validateForm]
220 );
222 const onValues = useCallback(
223 ({ valid, values, form }) => {
224 if (valid) {
225 if (values.unset) {
226 unset();
227 form.change('address', '');
228 setNewAddress('');
229 } else {
230 construct(values.address);
231 setNewAddress(values.address);
232 }
233 } else {
234 unconstruct();
235 }
236 },
237 [construct, unconstruct, unset, setNewAddress]
238 );
240 const initialValues = useMemo(() => ({ unset: false }), []);
242 const proxyAddress = proxyFromDetails(point, _contracts, data.proxyType);
243 const isProxySet = !isZeroAddress(proxyAddress);
245 const header = useMemo(() => {
246 const pfix = completed ? 'New' : 'Edit';
247 return `${pfix} ${properProxyType} Key`;
248 }, [completed, properProxyType]);
250 return (
251 <Window>
252 <HeaderPane>
253 <Row className="header-row">
254 <h5>{header}</h5>
255 </Row>
256 </HeaderPane>
257 <BodyPane>
258 <Grid className="w-full">
259 {!completed && (
260 <>
261 <Grid.Item full as={Text} className="mb4 f5 gray4">
262 {proxyTypeToHumanDescription(data.proxyType)}
263 </Grid.Item>
264 <Grid.Item
265 full
266 as={Text}
267 className={cn('f6', {
268 green3: completed,
269 })}>
270 Current
271 </Grid.Item>
272 </>
273 )}
275 <BridgeForm
276 validate={validate}
277 onValues={onValues}
278 initialValues={initialValues}>
279 {({ handleSubmit, values }) => (
280 <>
281 <Grid.Item full as={Flex} row justify="between" align="center">
282 <Flex.Item
283 flex
284 as={Text}
285 className={cn('mono mv3 gray4', {
286 black: !completed && isProxySet,
287 gray4: !completed && !isProxySet,
288 green3: completed,
289 })}>
290 {isProxySet ? proxyAddress : 'Unset'}
291 </Flex.Item>
292 </Grid.Item>
294 {completed ? (
295 <Grid.Item full className="mb4" />
296 ) : (
297 <Grid.Item
298 full
299 as={AddressInput}
300 className="mv4"
301 name="address"
302 label={`New ${properProxyType} Address`}
303 disabled={inputsLocked || values.unset}
304 />
305 )}
307 <Grid.Item full as={FormError} />
309 {isL2Tx ? (
310 <Grid.Item
311 as={Button}
312 full
313 className="set-proxy"
314 center
315 solid
316 disabled={values.unset}
317 onClick={setProxy}>
318 {getButtonText(data.proxyType)}
319 </Grid.Item>
320 ) : (
321 <Grid.Item
322 full
323 as={InlineEthereumTransaction}
324 {...bind}
325 onReturn={() => pop()}
326 />
327 )}
328 </>
329 )}
330 </BridgeForm>
331 </Grid>
332 </BodyPane>
333 </Window>
334 );