-
Notifications
You must be signed in to change notification settings - Fork 8
/
Router.tsx
183 lines (166 loc) · 5.02 KB
/
Router.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
import { useCallback, useEffect, useMemo } from 'react';
import { BrowserRouter, Route, Routes, Navigate } from 'react-router-dom';
import WS_RPC from '@vite/vitejs-ws';
import { accountBlock, ViteAPI } from '@vite/vitejs';
import Landing from '../pages/Landing';
import AppHome from '../pages/AppHome';
import { connect } from '../utils/globalContext';
import { State, ViteBalanceInfo } from '../utils/types';
import Toast from './Toast';
import { VCSessionKey } from '../utils/viteConnect';
import { networkList } from '../utils/constants';
import PageContainer from './PageContainer';
import CafeContract from '../contracts/Cafe';
import History from '../pages/History';
import { copyToClipboardAsync } from '../utils/strings';
const providerTimeout = 60000;
const providerOptions = { retryTimes: 10, retryInterval: 5000 };
type Props = State;
const Router = ({ i18n, setState, vpAddress, vcInstance, activeNetworkIndex }: Props) => {
const activeAddress = useMemo(() => {
return vpAddress || vcInstance?.accounts[0];
}, [vpAddress, vcInstance]);
useEffect(() => {
setState({ activeAddress });
}, [setState, activeAddress]);
const rpc = useMemo(() => {
const rpcUrl = networkList[activeNetworkIndex]?.rpcUrl;
if (rpcUrl) {
return new WS_RPC(rpcUrl, providerTimeout, providerOptions);
}
}, [activeNetworkIndex]);
const viteApi = useMemo(() => {
return new ViteAPI(rpc, () => {
// console.log('client connected');
});
}, [rpc]);
useEffect(() => setState({ viteApi }), [setState, viteApi]);
const getBalanceInfo = useCallback(
(address: string) => {
return viteApi.getBalanceInfo(address);
},
[viteApi]
);
const subscribe = useCallback(
(event: string, ...args: any) => {
return viteApi.subscribe(event, ...args);
},
[viteApi]
);
const updateViteBalanceInfo = useCallback(() => {
if (vcInstance?.accounts[0]) {
getBalanceInfo(vcInstance.accounts[0])
// @ts-ignore
.then((res: ViteBalanceInfo) => {
setState({ viteBalanceInfo: res });
})
.catch((e) => {
console.log(e);
setState({ toast: e, vcInstance: undefined });
localStorage.removeItem(VCSessionKey);
// Sometimes on page load, this will catch with
// Error: CONNECTION ERROR: Couldn't connect to node wss://buidl.vite.net/gvite/ws.
});
}
}, [setState, getBalanceInfo, vcInstance]);
useEffect(updateViteBalanceInfo, [updateViteBalanceInfo]);
// useEffect(() => {
// if (window.vitePassport) {
// window.vitePassport
// .getConnectedAddress()
// .then((data) => {
// console.log('data', data);
// })
// .catch((err) => {
// console.log('err', err);
// });
// }
// }, []);
useEffect(() => {
if (vcInstance) {
subscribe('newAccountBlocksByAddr', vcInstance.accounts[0])
.then((event: any) => {
event.on(() => {
updateViteBalanceInfo();
});
})
.catch((err: any) => console.warn(err));
}
return () => viteApi.unsubscribeAll();
}, [setState, subscribe, vcInstance, viteApi, updateViteBalanceInfo]);
const callContract = useCallback(
async (
contract: typeof CafeContract,
methodName: string,
params: any[] = [],
tokenId?: string,
amount?: string
) => {
if (!activeAddress) {
return;
}
const network = networkList[activeNetworkIndex];
if (!network) {
throw new Error(i18n.unsupportedNetwork);
}
if (vpAddress && network.rpcUrl !== (await window.vitePassport!.getNetwork()).rpcUrl) {
throw new Error(i18n.vitePassportNetworkDoesNotMatchDappNetworkUrl);
}
const methodAbi = contract.abi.find(
(x: any) => x.name === methodName && x.type === 'function'
);
if (!methodAbi) {
throw new Error(`method not found: ${methodName}`);
}
// @ts-ignore
const toAddress = contract.address[network.name.toLowerCase()];
if (!toAddress) {
throw new Error(i18n.unsupportedNetwork);
}
const blockParams = {
address: activeAddress,
abi: methodAbi,
toAddress,
params,
tokenId,
amount,
};
if (vpAddress === activeAddress && window?.vitePassport) {
return window.vitePassport.writeAccountBlock('callContract', blockParams);
} else if (vcInstance) {
return vcInstance.signAndSendTx([
{ block: accountBlock.createAccountBlock('callContract', blockParams).accountBlock },
]);
}
},
[activeAddress, activeNetworkIndex, vcInstance, vpAddress, i18n]
);
useEffect(() => {
setState({ callContract });
}, [setState, callContract]);
useEffect(() => {
setState({
copyWithToast: (text = '') => {
if (copyToClipboardAsync(text)) {
setState({ toast: i18n.successfullyCopied });
} else {
setState({ toast: 'clipboard API not supported' });
}
},
});
}, [setState, i18n]);
return (
<BrowserRouter>
<PageContainer>
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/app" element={<AppHome />} />
<Route path="/history" element={<History />} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</PageContainer>
<Toast />
</BrowserRouter>
);
};
export default connect(Router);