diff --git a/components/LSP/useLanguageServer.js b/components/LSP/useLanguageServer.js index ff3e2d2..494f7e7 100644 --- a/components/LSP/useLanguageServer.js +++ b/components/LSP/useLanguageServer.js @@ -1,9 +1,13 @@ -import { useState, useEffect } from "react"; +import { useState, useEffect, useMemo, useRef } from "react"; import { monaco } from "react-monaco-editor"; import { MonacoServices } from "monaco-languageclient/lib/monaco-services"; import { CadenceLanguageServer } from "./language-server"; import { createCadenceLanguageClient } from "./language-client"; +import { useNetworkContext } from "../../contexts/NetworkContext"; +import { setEnvironment } from "flow-cadut"; +import { useRegistryContext } from "../Registry"; +import { debounce } from "../../utils"; let monacoServicesInstalled = false; @@ -39,6 +43,9 @@ const launchLanguageClient = async ( }; export default function useLanguageServer() { + const network = useNetworkContext() || "testnet"; + const { registry, contracts, getContractCode } = useRegistryContext(); + let initialCallbacks = { // The actual callback will be set as soon as the language server is initialized toServer: null, @@ -63,28 +70,44 @@ export default function useLanguageServer() { const [languageClient, setLanguageClient] = useState(null); const [callbacks, setCallbacks] = useState(initialCallbacks); - const getCode = (address) => { - // TODO: Fetch code from address. - /* - This is probably can't be implemented right now as server expects only address, - but not the name of the contract. - */ - return ""; + const timer = useRef(null) + + const getCode = (importStatement) => { + const [address,contractName] = importStatement.split(".") + const code = getContractCode(contractName, address) || "" + if(code === ""){ + console.log(`%c+++++++++++++ NOT FOUND!!!!!!!!!! ${contractName}`,"color: red") + } + return code }; - const restartServer = () => { + const restartServer = ()=>{ console.log("Restarting server..."); startLanguageServer(callbacks, getCode, { setLanguageServer, setCallbacks, }).then(); - }; + } + + const debouncedRestart = () => { + if(timer.current){ + clearTimeout(timer.current); + } + timer.current = setTimeout(()=>{ + console.log("Restart language server") + if(languageServer){ + languageServer.updateCodeGetter(getCode) + // restartServer() + } + }, 2000); + } useEffect(() => { // The Monaco Language Client services have to be installed globally, once. // An editor must be passed, which is only used for commands. // As the Cadence language server is not providing any commands this is OK + setEnvironment(network); console.log("Installing monaco services"); if (!monacoServicesInstalled) { @@ -101,6 +124,12 @@ export default function useLanguageServer() { } }, [languageServer]); + useEffect(()=>{ + if(languageServer){ + languageServer.updateCodeGetter(getCode) + } + },[registry, contracts]) + return { languageClient, languageServer, diff --git a/components/Registry/hooks.js b/components/Registry/hooks.js new file mode 100644 index 0000000..29d1028 --- /dev/null +++ b/components/Registry/hooks.js @@ -0,0 +1,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 }; +}; diff --git a/components/Registry/index.js b/components/Registry/index.js new file mode 100644 index 0000000..3c8312c --- /dev/null +++ b/components/Registry/index.js @@ -0,0 +1,15 @@ +import { createContext, useContext } from "react"; +import { useRegistry } from "./hooks"; + +export const RegistryContext = createContext({}); +export const useRegistryContext = () => useContext(RegistryContext); + +export default function RegistryProvider(props) { + const registry = useRegistry(); + const { children } = props; + return ( + + {children} + + ); +} diff --git a/package.json b/package.json index a2c8755..8b87034 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "@onflow/fcl": "^0.0.77", "@picocss/pico": "^1.4.1", "copy-webpack-plugin": "^10.2.4", - "flow-cadut": "^0.1.15-alpha.26", + "flow-cadut": "^0.1.16-alpha.3", "monaco-editor": "^0.31.1", "monaco-editor-webpack-plugin": "^7.0.1", "monaco-languageclient": "^0.18.1", diff --git a/pages/_app.js b/pages/_app.js index 9cf4947..2522742 100644 --- a/pages/_app.js +++ b/pages/_app.js @@ -6,6 +6,7 @@ import * as fcl from "@onflow/fcl"; import { NetworkProvider } from "../contexts/NetworkContext"; import { configureForNetwork } from "../flow/config"; import React, { useState } from "react"; +import RegistryProvider from "../components/Registry"; function MyApp({ Component, pageProps }) { const [network, setNetwork] = useState(); @@ -45,7 +46,9 @@ function MyApp({ Component, pageProps }) {
- + + +
diff --git a/pages/index.js b/pages/index.js index 1bf02c5..f1d7913 100644 --- a/pages/index.js +++ b/pages/index.js @@ -1,6 +1,7 @@ import React, { useEffect, useState } from "react"; import Head from "next/head"; import dynamic from "next/dynamic"; +import * as fcl from "@onflow/fcl"; import { executeScript, sendTransaction, @@ -14,16 +15,17 @@ import { import Transaction from "../components/Transaction"; import CadenceEditor from "../components/CadenceEditor"; +import Registry from "../components/Registry"; import { useNetworkContext } from "../contexts/NetworkContext"; import { buttonLabels } from "../templates/labels"; import { baseTransaction, flovatarTotalSupply } from "../templates/code"; -import * as fcl from "@onflow/fcl"; - import "../flow/config.js"; import { configureForNetwork } from "../flow/config"; -import { debounce, fetchRegistry, prepareEnvironments } from "../utils"; +import { debounce } from "../utils"; +import { useRegistryContext } from "../components/Registry"; +import { cdc } from "@onflow/fcl"; const CadenceChecker = dynamic( () => import("../components/LSP/CadenceChecker"), @@ -65,20 +67,31 @@ const prepareFinalImports = async (list, setFinal) => { }; export default function Home() { + const initCode = cdc` + // + import FlovatarComponent from 0x0cf264811b95d465 + + pub fun main(): UInt64 { + return FlovatarComponent.totalSupply + } + `(); + + // HOOKS const [monacoReady, setMonacoReady] = useState(false); const [code, updateScriptCode] = useState(flovatarTotalSupply); const [result, setResult] = useState(); const [user, setUser] = useState(); - const [registry, setRegistry] = useState(null); const [importList, setImportList] = useState({}); const [finalImports, setFinalImports] = useState([]); - const network = useNetworkContext() || "testnet"; - const templateInfo = getTemplateInfo(code); - const { type, signers, args } = templateInfo; + // CONTEXTS + const fullRegistry = useRegistryContext(); + const { registry, contracts, fetchContract } = fullRegistry; + + console.log({fullRegistry}) - // METHDOS + // METHODS const updateImports = async () => { const env = await getEnvironment(network); const newCode = replaceImportAddresses(code, env); @@ -87,7 +100,6 @@ export default function Home() { const send = async () => { await setEnvironment(network); extendEnvironment(registry); - switch (true) { // Script Handling case type === "script": { @@ -126,36 +138,46 @@ export default function Home() { break; } }; - const getRegistry = async () => { - const data = await fetchRegistry(); - const registry = prepareEnvironments(data); - extendEnvironment(registry); - setRegistry(registry); + + const fetchContracts = () => { + if (fetchContract) { + const contracts = Object.keys(importList); + for (let i = 0; i < contracts.length; i++) { + const name = contracts[i]; + fetchContract(name); + } + } }; + // CONSTANTS + const templateInfo = getTemplateInfo(code); + const { type, signers, args } = templateInfo; + const fclAble = signers && signers === 1 && type === "transaction"; + const disabled = + type === "unknown" || type === "contract" || !monacoReady || signers > 1; + // EFFECTS useEffect(() => { fcl.unauthenticate(); fcl.currentUser().subscribe(setUser); - - getRegistry().then(); }, []); useEffect(() => { setEnvironment(network); - if (registry !== null) { + if (registry) { extendEnvironment(registry); } }, [network]); useEffect(() => getImports(code, setImportList), [code]); - useEffect( - () => prepareFinalImports(importList, setFinalImports), - [importList, network] - ); + useEffect(() => { + prepareFinalImports(importList, setFinalImports); + }, [importList, network]); + useEffect(() => { + fetchContracts(); + }, [importList]); - const fclAble = signers && signers === 1 && type === "transaction"; - const disabled = - type === "unknown" || type === "contract" || !monacoReady || signers > 1; + // TODO: Refresh editor to enable recheck + // RENDER return (
diff --git a/templates/code.js b/templates/code.js index e28a873..089208a 100644 --- a/templates/code.js +++ b/templates/code.js @@ -1,19 +1,22 @@ -export const baseScript = ` +import { cdc } from "@onflow/fcl"; + +export const baseScript = cdc` // This is the most basic script you can execute on Flow Network pub fun main():Int { return 42 } -`.slice(1); // remove new line at the bof +`(); -export const flovatarTotalSupply = ` +export const flovatarTotalSupply = cdc` +/// pragma title Flovatar Total Supply import Flovatar from 0x01 pub fun main():UInt64{ return Flovatar.totalSupply } -`.slice(1); // remove new line at the bof +`(); -export const baseTransaction = ` +export const baseTransaction = cdc` // This is the most basic transaction you can execute on Flow Network transaction() { prepare(signer: AuthAccount) { @@ -23,4 +26,4 @@ transaction() { } } -`.slice(1); // remove new line at the bof +`();