-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhooks.js
88 lines (77 loc) · 2.21 KB
/
hooks.js
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
import { useEffect, useReducer, useState } from "react";
import { extendEnvironment, extractImports } from "flow-cadut";
import * as fcl from "@onflow/fcl";
import { fetchRegistry, prepareEnvironments } from "../../utils";
import { useNetworkContext } from "../../contexts/NetworkContext";
const contractReducer = (state, action) => {
const { contracts, network } = action;
return {
...state,
[network]: {
...state[network],
...contracts,
},
};
};
export const useRegistry = () => {
const network = useNetworkContext() || "testnet";
const [registry, setRegistry] = useState({});
const [contracts, dispatch] = useReducer(contractReducer, {
testnet: {},
mainnet: {},
});
const getRegistry = async () => {
const data = await fetchRegistry();
const registry = prepareEnvironments(data);
extendEnvironment(registry);
setRegistry(registry);
};
useEffect(() => {
getRegistry().then();
}, []);
const fetchDependencies = (list) => {
const keys = Object.keys(list);
for (let i = 0; i < keys.length; i++) {
// TODO: check if it's cached
const name = keys[i];
const address = list[name];
const contract = contracts[network][name];
if (!contract) {
fetchContract(name, address);
}
}
};
const fetchContract = async (name, exactAddress) => {
let address = exactAddress;
if (!exactAddress && registry[network]) {
address = registry[network][name]
}
if(!address){
return false
}
try {
console.log("--------> ADDRESS:", {name, exactAddress, address})
const { contracts } = await fcl
.send([fcl.getAccount(address)])
.then(fcl.decode);
const code = contracts[name] || "";
const dependencies = extractImports(code);
fetchDependencies(dependencies);
// Update state
dispatch({
contracts,
network,
});
} catch (e) {
console.error(e);
}
};
const getContractCode = (name, address) => {
const contract = contracts[network][name];
if(!contract){
fetchContract(name, address).then();
}
return contract || "";
};
return { registry, contracts, fetchContract, getContractCode };
};