-
Notifications
You must be signed in to change notification settings - Fork 0
/
Application.jsx
287 lines (258 loc) · 8.3 KB
/
Application.jsx
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
import React, { createContext, useContext, useReducer, useEffect } from 'react';
import 'json5';
import 'utils/installSESLockdown';
import { makeCapTP, E, Far } from '@agoric/captp';
import { makeAsyncIterableFromNotifier as iterateNotifier } from '@agoric/notifier';
import {
activateWebSocket,
deactivateWebSocket,
getActiveSocket,
} from '../utils/fetchWebSocket';
import { dappConfig, refreshConfigFromWallet } from '../utils/config';
import {
reducer,
defaultState,
setPurses,
setAssets,
setConnected,
resetState,
updateVault,
setAutoswap,
setApproved,
updateOffers,
setError,
} from '../store/store';
import {
updateBrandPetnames,
storeAllBrandsFromTerms,
} from '../utils/storeBrandInfo';
/* eslint-disable */
let walletP;
/* eslint-enable */
export { walletP };
export const ApplicationContext = createContext();
export function useApplicationContext() {
return useContext(ApplicationContext);
}
function watchVault(id, dispatch) {
console.log('vaultWatched', id);
// There is no UINotifier for offers that haven't been accepted, but
// we still want to show that the offer exists
const status = 'Pending Wallet Acceptance';
dispatch(
updateVault({
id,
vault: { status },
}),
);
async function vaultUpdater() {
const uiNotifier = E(walletP).getUINotifier(id);
for await (const value of iterateNotifier(uiNotifier)) {
console.log('======== VAULT', id, value);
dispatch(
updateVault({ id, vault: { ...value, status: 'Loan Initiated' } }),
);
}
}
vaultUpdater().catch(err => {
console.error('Vault watcher exception', id, err);
dispatch(updateVault({ id, vault: { status: 'Error in offer', err } }));
});
}
function watchOffers(dispatch, INSTANCE_BOARD_ID) {
const watchedVaults = new Set();
async function offersUpdater() {
const offerNotifier = E(walletP).getOffersNotifier();
for await (const offers of iterateNotifier(offerNotifier)) {
for (const {
id,
instanceHandleBoardId,
continuingInvitation,
} of offers) {
if (
instanceHandleBoardId === INSTANCE_BOARD_ID &&
!watchedVaults.has(id) &&
continuingInvitation === undefined // AdjustBalances and CloseVault offers use continuingInvitation
) {
watchedVaults.add(id);
watchVault(id, dispatch);
}
}
console.log('======== OFFERS', offers);
dispatch(updateOffers(offers));
}
}
offersUpdater().catch(err => console.error('Offers watcher exception', err));
}
// CMT (danish): We do not require treasury in this app
// const setupTreasury = async (dispatch, brandToInfo, zoe, board, instanceID) => {
// const instance = await E(board).getValue(instanceID);
// const treasuryAPIP = E(zoe).getPublicFacet(instance);
// const [treasuryAPI, terms, collaterals] = await Promise.all([
// treasuryAPIP,
// E(zoe).getTerms(instance),
// E(treasuryAPIP).getCollaterals(),
// ]);
// const {
// issuers: { RUN: runIssuer },
// brands: { RUN: runBrand },
// } = terms;
// dispatch(setTreasury({ instance, treasuryAPI, runIssuer, runBrand }));
// await storeAllBrandsFromTerms({
// dispatch,
// terms,
// brandToInfo,
// });
// console.log('SET COLLATERALS', collaterals);
// dispatch(setCollaterals(collaterals));
// return { terms, collaterals };
// };
const setupAMM = async (dispatch, brandToInfo, zoe, board, instanceID) => {
const instance = await E(board).getValue(instanceID);
const [ammAPI, terms] = await Promise.all([
E(zoe).getPublicFacet(instance),
E(zoe).getTerms(instance),
]);
// TODO this uses getTerms.brands, but that includes utility tokens, etc.
// We need a query/notifier for what are the pools supported
const {
brands: { Central: centralBrand, ...otherBrands },
} = terms;
console.log('AMM brands retrieved', otherBrands);
dispatch(setAutoswap({ instance, ammAPI, centralBrand, otherBrands }));
await storeAllBrandsFromTerms({
dispatch,
terms,
brandToInfo,
});
};
/* eslint-disable complexity, react/prop-types */
export default function Provider({ children }) {
const [state, dispatch] = useReducer(reducer, defaultState);
const { brandToInfo } = state;
useEffect(() => {
// Receive callbacks from the wallet connection.
const otherSide = Far('needDappApproval', {
needDappApproval(_dappOrigin, _suggestedDappPetname) {
dispatch(setApproved(false));
},
dappApproved(_dappOrigin) {
dispatch(setApproved(true));
},
});
let walletAbort;
let walletDispatch;
activateWebSocket({
async onConnect() {
const { CONTRACT_NAME, AMM_NAME } = dappConfig;
dispatch(setConnected(true));
const socket = getActiveSocket();
const {
abort: ctpAbort,
dispatch: ctpDispatch,
getBootstrap,
} = makeCapTP(
CONTRACT_NAME,
obj => socket.send(JSON.stringify(obj)),
otherSide,
);
walletAbort = ctpAbort;
walletDispatch = ctpDispatch;
walletP = getBootstrap();
await refreshConfigFromWallet(walletP);
const {
INSTALLATION_BOARD_ID,
INSTANCE_BOARD_ID,
RUN_ISSUER_BOARD_ID,
AMM_INSTALLATION_BOARD_ID,
AMM_INSTANCE_BOARD_ID,
} = dappConfig;
const zoe = E(walletP).getZoe();
const board = E(walletP).getBoard();
if (board) {
setApproved(true);
}
// else{
// setApproved(false);
// }
await Promise.all([
// setupTreasury(dispatch, brandToInfo, zoe, board, INSTANCE_BOARD_ID),
setupAMM(dispatch, brandToInfo, zoe, board, AMM_INSTANCE_BOARD_ID),
]);
// The moral equivalent of walletGetPurses()
async function watchPurses() {
const pn = E(walletP).getPursesNotifier();
for await (const purses of iterateNotifier(pn)) {
dispatch(setPurses(purses));
// console.info('THESE ARE PURSES: ', purses);
dispatch(setAssets(purses));
}
}
watchPurses().catch(err =>
console.error('FIGME: got watchPurses err', err),
);
async function watchBrands() {
console.log('BRANDS REQUESTED');
const issuersN = E(walletP).getIssuersNotifier();
for await (const issuers of iterateNotifier(issuersN)) {
updateBrandPetnames({
dispatch,
brandToInfo,
issuersFromNotifier: issuers,
});
}
}
watchBrands().catch(err => {
console.error('got watchBrands err', err);
});
await Promise.all([
E(walletP).suggestInstallation('Installation', INSTALLATION_BOARD_ID),
E(walletP).suggestInstance('Instance', INSTANCE_BOARD_ID),
E(walletP).suggestInstallation(
`${AMM_NAME}Installation`,
AMM_INSTALLATION_BOARD_ID,
),
E(walletP).suggestInstance(
`${AMM_NAME}Instance`,
AMM_INSTANCE_BOARD_ID,
),
E(walletP).suggestIssuer('RUN', RUN_ISSUER_BOARD_ID),
]);
watchOffers(dispatch, INSTANCE_BOARD_ID);
},
onDisconnect() {
dispatch(setConnected(false));
dispatch(setApproved(false));
console.log('Running on Disconnect');
walletAbort && walletAbort();
dispatch(resetState());
},
onMessage(data) {
const obj = JSON.parse(data);
console.log('Printing Object empty: ', obj);
console.log(!obj.exception);
if (obj.exception) {
console.log(obj.exception.body);
dispatch(
setError({
name:
'Zoe purse balance is 0.First send Runs to zoe purse using your wallet.Then Refresh browser to continue.',
}),
);
} else {
console.log('wallet Disconnect:', obj?.payload?.payload === false);
if (obj?.payload?.payload === false) {
setApproved(false);
}
walletDispatch && walletDispatch(obj);
}
},
});
return deactivateWebSocket;
}, []);
return (
<ApplicationContext.Provider value={{ state, dispatch, walletP }}>
{children}
</ApplicationContext.Provider>
);
}