Compare commits

..

2 Commits

Author SHA1 Message Date
muzam1l
04e2274dbf some refactoring 2022-04-06 14:42:39 +05:30
muzam1l
842b8a5226 Set debug stream default account from transaction account 2022-04-04 21:29:08 +05:30
8 changed files with 98 additions and 112 deletions

View File

@@ -10,7 +10,7 @@ interface ISelect<T = string> {
value: T; value: T;
} }
const streamState = proxy({ export const streamState = proxy({
selectedAccount: null as ISelect | null, selectedAccount: null as ISelect | null,
logs: [] as ILog[], logs: [] as ILog[],
socket: undefined as WebSocket | undefined, socket: undefined as WebSocket | undefined,

View File

@@ -1,29 +1,28 @@
import { listen } from "@codingame/monaco-jsonrpc"; import React, { useEffect, useRef } from "react";
import { MonacoServices } from "@codingame/monaco-languageclient"; import { useSnapshot, ref } from "valtio";
import Editor, { loader } from "@monaco-editor/react"; import Editor, { loader } from "@monaco-editor/react";
import uniqBy from "lodash.uniqby";
import type monaco from "monaco-editor"; import type monaco from "monaco-editor";
import { ArrowBendLeftUp } from "phosphor-react";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { ArrowBendLeftUp } from "phosphor-react"; import uniqBy from "lodash.uniqby";
import React, { useEffect, useRef } from "react";
import toast from "react-hot-toast";
import ReconnectingWebSocket from "reconnecting-websocket";
import { ref, useSnapshot } from "valtio";
import state from "../state";
import { saveFile } from "../state/actions";
import { apiHeaderFiles } from "../state/constants";
import dark from "../theme/editor/amy.json";
import light from "../theme/editor/xcode_default.json";
import { createLanguageClient, createWebSocket } from "../utils/languageClient";
import docs from "../xrpl-hooks-docs/docs";
import Box from "./Box"; import Box from "./Box";
import Container from "./Container"; import Container from "./Container";
import dark from "../theme/editor/amy.json";
import light from "../theme/editor/xcode_default.json";
import { saveFile } from "../state/actions";
import { apiHeaderFiles } from "../state/constants";
import state from "../state";
import EditorNavigation from "./EditorNavigation"; import EditorNavigation from "./EditorNavigation";
import Text from "./Text"; import Text from "./Text";
import { MonacoServices } from "@codingame/monaco-languageclient";
import { createLanguageClient, createWebSocket } from "../utils/languageClient";
import { listen } from "@codingame/monaco-jsonrpc";
import ReconnectingWebSocket from "reconnecting-websocket";
import docs from "../xrpl-hooks-docs/docs";
loader.config({ loader.config({
paths: { paths: {
@@ -124,7 +123,6 @@ const HooksEditor = () => {
setMarkers(monacoRef.current); setMarkers(monacoRef.current);
} }
}, [snap.active]); }, [snap.active]);
return ( return (
<Box <Box
css={{ css={{
@@ -157,7 +155,7 @@ const HooksEditor = () => {
); );
} }
// create the websocket // create the web socket
if (!subscriptionRef.current) { if (!subscriptionRef.current) {
monaco.languages.register({ monaco.languages.register({
id: "c", id: "c",
@@ -166,12 +164,11 @@ const HooksEditor = () => {
mimetypes: ["text/plain"], mimetypes: ["text/plain"],
}); });
MonacoServices.install(monaco); MonacoServices.install(monaco);
const webSocket = createWebSocket(
const webSocket: ReconnectingWebSocket = createWebSocket(
process.env.NEXT_PUBLIC_LANGUAGE_SERVER_API_ENDPOINT || "" process.env.NEXT_PUBLIC_LANGUAGE_SERVER_API_ENDPOINT || ""
); );
subscriptionRef.current = webSocket; subscriptionRef.current = webSocket;
// listen when the websocket is opened // listen when the web socket is opened
listen({ listen({
webSocket: webSocket as WebSocket, webSocket: webSocket as WebSocket,
onConnection: (connection) => { onConnection: (connection) => {
@@ -183,14 +180,9 @@ const HooksEditor = () => {
// disposable.stop(); // disposable.stop();
disposable.dispose(); disposable.dispose();
} catch (err) { } catch (err) {
toast.error('Connection to language server lost!') console.log("err", err);
console.error("Couldn't dispose the language server connection! ", err);
} }
}); });
connection.onDispose(() => {
toast.error('Connection to language server lost!')
})
// TODO: Check if we need to listen to more connection events
}, },
}); });
} }

View File

@@ -1,17 +1,22 @@
import NextLink from "next/link";
import { Notepad, Prohibit } from "phosphor-react";
import { import {
FC, ReactNode, useCallback, useLayoutEffect, useRef, useState useRef,
useLayoutEffect,
ReactNode,
FC,
useState,
useCallback,
} from "react"; } from "react";
import { Notepad, Prohibit } from "phosphor-react";
import useStayScrolled from "react-stay-scrolled"; import useStayScrolled from "react-stay-scrolled";
import regexifyString from "regexify-string"; import NextLink from "next/link";
import { useSnapshot } from "valtio";
import { Box, Button, Flex, Heading, Link, Pre, Text } from ".";
import state, { ILog } from "../state";
import { AccountDialog } from "./Accounts";
import Container from "./Container"; import Container from "./Container";
import LogText from "./LogText"; import LogText from "./LogText";
import state, { ILog } from "../state";
import { Pre, Link, Heading, Button, Text, Flex, Box } from ".";
import regexifyString from "regexify-string";
import { useSnapshot } from "valtio";
import { AccountDialog } from "./Accounts";
interface ILogBox { interface ILogBox {
title: string; title: string;
@@ -155,7 +160,7 @@ export const Log: FC<ILog> = ({
const enrichAccounts = useCallback( const enrichAccounts = useCallback(
(str?: string): ReactNode => { (str?: string): ReactNode => {
if (!str) return null; if (!str || !accounts.length) return null;
const pattern = `(${accounts.map((acc) => acc.address).join("|")})`; const pattern = `(${accounts.map((acc) => acc.address).join("|")})`;
const res = regexifyString({ const res = regexifyString({

View File

@@ -18,6 +18,7 @@ import transactionsData from "../../content/transactions.json";
import state from "../../state"; import state from "../../state";
import { sendTransaction } from "../../state/actions"; import { sendTransaction } from "../../state/actions";
import { getSplit, saveSplit } from "../../state/actions/persistSplits"; import { getSplit, saveSplit } from "../../state/actions/persistSplits";
import { streamState } from "../../components/DebugStream";
const DebugStream = dynamic(() => import("../../components/DebugStream"), { const DebugStream = dynamic(() => import("../../components/DebugStream"), {
ssr: false, ssr: false,
@@ -37,6 +38,11 @@ type TxFields = Omit<
>; >;
type OtherFields = (keyof Omit<TxFields, "Destination">)[]; type OtherFields = (keyof Omit<TxFields, "Destination">)[];
interface AccountOption {
label: string;
value: string;
}
interface Props { interface Props {
header?: string; header?: string;
} }
@@ -44,7 +50,7 @@ interface Props {
const Transaction: FC<Props> = ({ header, ...props }) => { const Transaction: FC<Props> = ({ header, ...props }) => {
const snap = useSnapshot(state); const snap = useSnapshot(state);
const transactionsOptions = transactionsData.map((tx) => ({ const transactionsOptions = transactionsData.map(tx => ({
value: tx.TransactionType, value: tx.TransactionType,
label: tx.TransactionType, label: tx.TransactionType,
})); }));
@@ -52,23 +58,24 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
typeof transactionsOptions[0] | null typeof transactionsOptions[0] | null
>(null); >(null);
const accountOptions = snap.accounts.map((acc) => ({ const accountOptions: AccountOption[] = snap.accounts.map(acc => ({
label: acc.name, label: acc.name,
value: acc.address, value: acc.address,
})); }));
const [selectedAccount, setSelectedAccount] = useState<
typeof accountOptions[0] | null
>(null);
const destAccountOptions = snap.accounts const [selectedAccount, setSelectedAccount] = useState<AccountOption | null>(
.map((acc) => ({ null
);
const destAccountOptions: AccountOption[] = snap.accounts
.map(acc => ({
label: acc.name, label: acc.name,
value: acc.address, value: acc.address,
})) }))
.filter((acc) => acc.value !== selectedAccount?.value); .filter(acc => acc.value !== selectedAccount?.value);
const [selectedDestAccount, setSelectedDestAccount] = useState<
typeof destAccountOptions[0] | null const [selectedDestAccount, setSelectedDestAccount] =
>(null); useState<AccountOption | null>(null);
const [txIsLoading, setTxIsLoading] = useState(false); const [txIsLoading, setTxIsLoading] = useState(false);
const [txIsDisabled, setTxIsDisabled] = useState(false); const [txIsDisabled, setTxIsDisabled] = useState(false);
@@ -77,7 +84,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
useEffect(() => { useEffect(() => {
const transactionType = selectedTransaction?.value; const transactionType = selectedTransaction?.value;
const account = snap.accounts.find( const account = snap.accounts.find(
(acc) => acc.address === selectedAccount?.value acc => acc.address === selectedAccount?.value
); );
if (!account || !transactionType || txIsLoading) { if (!account || !transactionType || txIsLoading) {
setTxIsDisabled(true); setTxIsDisabled(true);
@@ -88,7 +95,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
useEffect(() => { useEffect(() => {
let _txFields: TxFields | undefined = transactionsData.find( let _txFields: TxFields | undefined = transactionsData.find(
(tx) => tx.TransactionType === selectedTransaction?.value tx => tx.TransactionType === selectedTransaction?.value
); );
if (!_txFields) return setTxFields({}); if (!_txFields) return setTxFields({});
_txFields = { ..._txFields } as TxFields; _txFields = { ..._txFields } as TxFields;
@@ -105,7 +112,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
const submitTest = useCallback(async () => { const submitTest = useCallback(async () => {
const account = snap.accounts.find( const account = snap.accounts.find(
(acc) => acc.address === selectedAccount?.value acc => acc.address === selectedAccount?.value
); );
const TransactionType = selectedTransaction?.value; const TransactionType = selectedTransaction?.value;
if (!account || !TransactionType || txIsDisabled) return; if (!account || !TransactionType || txIsDisabled) return;
@@ -116,7 +123,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
let options = { ...txFields }; let options = { ...txFields };
options.Destination = selectedDestAccount?.value; options.Destination = selectedDestAccount?.value;
(Object.keys(options) as (keyof TxFields)[]).forEach((field) => { (Object.keys(options) as (keyof TxFields)[]).forEach(field => {
let _value = options[field]; let _value = options[field];
// convert currency // convert currency
if (typeof _value === "object" && _value.type === "currency") { if (typeof _value === "object" && _value.type === "currency") {
@@ -182,9 +189,14 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
setTxIsLoading(false); setTxIsLoading(false);
}, []); }, []);
const handleSetAccount = (acc: AccountOption) => {
setSelectedAccount(acc);
streamState.selectedAccount = acc;
};
const usualFields = ["TransactionType", "Amount", "Account", "Destination"]; const usualFields = ["TransactionType", "Amount", "Account", "Destination"];
const otherFields = Object.keys(txFields).filter( const otherFields = Object.keys(txFields).filter(
(k) => !usualFields.includes(k) k => !usualFields.includes(k)
) as OtherFields; ) as OtherFields;
return ( return (
<Box css={{ position: "relative", height: "calc(100% - 28px)" }} {...props}> <Box css={{ position: "relative", height: "calc(100% - 28px)" }} {...props}>
@@ -217,7 +229,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
hideSelectedOptions hideSelectedOptions
css={{ width: "70%" }} css={{ width: "70%" }}
value={selectedTransaction} value={selectedTransaction}
onChange={(tt) => setSelectedTransaction(tt as any)} onChange={(tt: any) => setSelectedTransaction(tt)}
/> />
</Flex> </Flex>
<Flex <Flex
@@ -239,7 +251,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
css={{ width: "70%" }} css={{ width: "70%" }}
options={accountOptions} options={accountOptions}
value={selectedAccount} value={selectedAccount}
onChange={(acc) => setSelectedAccount(acc as any)} onChange={(acc: any) => handleSetAccount(acc)} // TODO make react-select have correct types for acc
/> />
</Flex> </Flex>
{txFields.Amount !== undefined && ( {txFields.Amount !== undefined && (
@@ -258,7 +270,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
</Text> </Text>
<Input <Input
value={txFields.Amount.value} value={txFields.Amount.value}
onChange={(e) => onChange={e =>
setTxFields({ setTxFields({
...txFields, ...txFields,
Amount: { type: "currency", value: e.target.value }, Amount: { type: "currency", value: e.target.value },
@@ -289,11 +301,11 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
options={destAccountOptions} options={destAccountOptions}
value={selectedDestAccount} value={selectedDestAccount}
isClearable isClearable
onChange={(acc) => setSelectedDestAccount(acc as any)} onChange={(acc: any) => setSelectedDestAccount(acc)}
/> />
</Flex> </Flex>
)} )}
{otherFields.map((field) => { {otherFields.map(field => {
let _value = txFields[field]; let _value = txFields[field];
let value = typeof _value === "object" ? _value.value : _value; let value = typeof _value === "object" ? _value.value : _value;
value = value =
@@ -319,7 +331,7 @@ const Transaction: FC<Props> = ({ header, ...props }) => {
</Text> </Text>
<Input <Input
value={value} value={value}
onChange={(e) => onChange={e =>
setTxFields({ setTxFields({
...txFields, ...txFields,
[field]: [field]:
@@ -376,7 +388,7 @@ const Test = () => {
gutterSize={4} gutterSize={4}
gutterAlign="center" gutterAlign="center"
style={{ height: "calc(100vh - 60px)" }} style={{ height: "calc(100vh - 60px)" }}
onDragEnd={(e) => saveSplit("testVertical", e)} onDragEnd={e => saveSplit("testVertical", e)}
> >
<Flex <Flex
row row
@@ -398,21 +410,19 @@ const Test = () => {
width: "100%", width: "100%",
height: "100%", height: "100%",
}} }}
onDragEnd={(e) => saveSplit("testHorizontal", e)} onDragEnd={e => saveSplit("testHorizontal", e)}
> >
<Box css={{ width: "55%", px: "$2" }}> <Box css={{ width: "55%", px: "$2" }}>
<Tabs <Tabs
keepAllAlive keepAllAlive
forceDefaultExtension forceDefaultExtension
defaultExtension=".json" defaultExtension=".json"
onCreateNewTab={(name) => onCreateNewTab={name => setTabHeaders(tabHeaders.concat(name))}
setTabHeaders(tabHeaders.concat(name)) onCloseTab={index =>
}
onCloseTab={(index) =>
setTabHeaders(tabHeaders.filter((_, idx) => idx !== index)) setTabHeaders(tabHeaders.filter((_, idx) => idx !== index))
} }
> >
{tabHeaders.map((header) => ( {tabHeaders.map(header => (
<Tab key={header} header={header}> <Tab key={header} header={header}>
<Transaction header={header} /> <Transaction header={header} />
</Tab> </Tab>

View File

@@ -33,6 +33,8 @@ export const addFaucetAccount = async (showToast: boolean = false) => {
return toast.error("You can only have maximum 6 accounts"); return toast.error("You can only have maximum 6 accounts");
} }
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const toastId = showToast ? toast.loading("Creating account") : ""; const toastId = showToast ? toast.loading("Creating account") : "";
const res = await fetch(`${window.location.origin}/api/faucet`, { const res = await fetch(`${window.location.origin}/api/faucet`, {
method: "POST", method: "POST",
@@ -90,4 +92,5 @@ export const addFunds = async (address: string) => {
currAccount.xrp = (Number(currAccount.xrp) + (json.xrp * 1000000)).toString(); currAccount.xrp = (Number(currAccount.xrp) + (json.xrp * 1000000)).toString();
} }
} }
}
}

View File

@@ -1,10 +1,10 @@
import Router from 'next/router';
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { ref } from "valtio"; import Router from 'next/router';
import { decodeBinary } from "../../utils/decodeBinary";
import state from "../index"; import state from "../index";
import { saveFile } from "./saveFile"; import { saveFile } from "./saveFile";
import { decodeBinary } from "../../utils/decodeBinary";
import { ref } from "valtio";
/* compileCode sends the code of the active file to compile endpoint /* compileCode sends the code of the active file to compile endpoint
* If all goes well you will get base64 encoded wasm file back with * If all goes well you will get base64 encoded wasm file back with
@@ -15,22 +15,17 @@ import { saveFile } from "./saveFile";
export const compileCode = async (activeId: number) => { export const compileCode = async (activeId: number) => {
// Save the file to global state // Save the file to global state
saveFile(false); saveFile(false);
if (!process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT) { if (!process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT) {
throw Error("Missing env!"); throw Error("Missing env!");
} }
// Bail out if we're already compiling // Bail out if we're already compiling
if (state.compiling) { if (state.compiling) {
// if compiling is ongoing return // if compiling is ongoing return
return; return;
} }
// Set loading state to true // Set loading state to true
state.compiling = true; state.compiling = true;
// Reset development log
state.logs = [] state.logs = []
try { try {
const res = await fetch(process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT, { const res = await fetch(process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT, {
method: "POST", method: "POST",
@@ -51,7 +46,6 @@ export const compileCode = async (activeId: number) => {
}); });
const json = await res.json(); const json = await res.json();
state.compiling = false; state.compiling = false;
if (!json.success) { if (!json.success) {
state.logs.push({ type: "error", message: json.message }); state.logs.push({ type: "error", message: json.message });
if (json.tasks && json.tasks.length > 0) { if (json.tasks && json.tasks.length > 0) {
@@ -63,19 +57,16 @@ export const compileCode = async (activeId: number) => {
} }
return toast.error(`Couldn't compile!`, { position: "bottom-center" }); return toast.error(`Couldn't compile!`, { position: "bottom-center" });
} }
state.logs.push({ state.logs.push({
type: "success", type: "success",
message: `File ${state.files?.[activeId]?.name} compiled successfully. Ready to deploy.`, message: `File ${state.files?.[activeId]?.name} compiled successfully. Ready to deploy.`,
link: Router.asPath.replace("develop", "deploy"), link: Router.asPath.replace("develop", "deploy"),
linkText: "Go to deploy", linkText: "Go to deploy",
}); });
// Decode base64 encoded wasm that is coming back from the endpoint // Decode base64 encoded wasm that is coming back from the endpoint
const bufferData = await decodeBinary(json.output); const bufferData = await decodeBinary(json.output);
state.files[state.active].compiledContent = ref(bufferData); state.files[state.active].compiledContent = ref(bufferData);
state.files[state.active].lastCompiled = new Date(); state.files[state.active].lastCompiled = new Date();
// Import wabt from and create human readable version of wasm file and // Import wabt from and create human readable version of wasm file and
// put it into state // put it into state
import("wabt").then((wabt) => { import("wabt").then((wabt) => {
@@ -89,22 +80,12 @@ export const compileCode = async (activeId: number) => {
state.files[state.active].compiledWatContent = wast; state.files[state.active].compiledWatContent = wast;
toast.success("Compiled successfully!", { position: "bottom-center" }); toast.success("Compiled successfully!", { position: "bottom-center" });
}); });
} catch (err: any) { } catch (err) {
const error = err as Error console.log(err);
state.logs.push({
// TODO: Centralized error handling? Just a thought type: "error",
if(error.message.includes("Failed to fetch")) { message: "Error occured while compiling!",
state.logs.push({ });
type: "error",
message: "No connection to the compiler server!",
});
} else {
state.logs.push({
type: "error",
message: "Error occured while compiling!",
});
}
state.compiling = false; state.compiling = false;
} }
}; };

View File

@@ -1,10 +1,9 @@
import toast from "react-hot-toast";
import { derive, sign } from "xrpl-accountlib"; import { derive, sign } from "xrpl-accountlib";
import { AnyJson } from "xrpl-client"; import toast from "react-hot-toast";
import { SetHookData } from "../../components/SetHookDialog";
import calculateHookOn, { TTS } from "../../utils/hookOnCalculator";
import state, { IAccount } from "../index";
import state, { IAccount } from "../index";
import calculateHookOn, { TTS } from "../../utils/hookOnCalculator";
import { SetHookData } from "../../components/SetHookDialog";
const hash = async (string: string) => { const hash = async (string: string) => {
const utf8 = new TextEncoder().encode(string); const utf8 = new TextEncoder().encode(string);
@@ -52,22 +51,19 @@ function arrayBufferToHex(arrayBuffer?: ArrayBuffer | null) {
* hex string, signs the transaction and deploys it to * hex string, signs the transaction and deploys it to
* Hooks testnet. * Hooks testnet.
*/ */
export const deployHook = async (account: IAccount & { name?: string }, data: SetHookData): Promise<AnyJson | undefined> => { export const deployHook = async (account: IAccount & { name?: string }, data: SetHookData) => {
if ( if (
!state.files || !state.files ||
state.files.length === 0 || state.files.length === 0 ||
!state.files?.[state.active]?.compiledContent !state.files?.[state.active]?.compiledContent
) { ) {
console.log("ebin1")
return; return;
} }
if (!state.files?.[state.active]?.compiledContent) { if (!state.files?.[state.active]?.compiledContent) {
console.log("ebin2")
return; return;
} }
if (!state.client) { if (!state.client) {
console.log("ebin3")
return; return;
} }
const HookNamespace = await hash(arrayBufferToHex( const HookNamespace = await hash(arrayBufferToHex(
@@ -140,7 +136,6 @@ export const deployHook = async (account: IAccount & { name?: string }, data: Se
}); });
} }
} catch (err) { } catch (err) {
console.log("Ebin")
console.log(err); console.log(err);
state.deployLogs.push({ state.deployLogs.push({
type: "error", type: "error",
@@ -225,4 +220,4 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
} }
return submitRes; return submitRes;
} }
}; };

View File

@@ -1,5 +1,5 @@
import { MessageConnection } from "@codingame/monaco-jsonrpc"; import { MessageConnection } from "@codingame/monaco-jsonrpc";
import { CloseAction, createConnection, ErrorAction, MonacoLanguageClient } from "@codingame/monaco-languageclient"; import { MonacoLanguageClient, ErrorAction, CloseAction, createConnection } from "@codingame/monaco-languageclient";
import Router from "next/router"; import Router from "next/router";
import normalizeUrl from "normalize-url"; import normalizeUrl from "normalize-url";
import ReconnectingWebSocket from "reconnecting-websocket"; import ReconnectingWebSocket from "reconnecting-websocket";
@@ -37,7 +37,7 @@ export function createUrl(path: string): string {
return normalizeUrl(`${protocol}://${location.host}${location.pathname}${path}`); return normalizeUrl(`${protocol}://${location.host}${location.pathname}${path}`);
} }
export function createWebSocket(url: string): ReconnectingWebSocket { export function createWebSocket(url: string) {
const socketOptions = { const socketOptions = {
maxReconnectionDelay: 10000, maxReconnectionDelay: 10000,
minReconnectionDelay: 1000, minReconnectionDelay: 1000,
@@ -47,4 +47,4 @@ export function createWebSocket(url: string): ReconnectingWebSocket {
debug: false debug: false
}; };
return new ReconnectingWebSocket(url, [], socketOptions); return new ReconnectingWebSocket(url, [], socketOptions);
} }