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;
}
const streamState = proxy({
export const streamState = proxy({
selectedAccount: null as ISelect | null,
logs: [] as ILog[],
socket: undefined as WebSocket | undefined,

View File

@@ -1,29 +1,28 @@
import { listen } from "@codingame/monaco-jsonrpc";
import { MonacoServices } from "@codingame/monaco-languageclient";
import React, { useEffect, useRef } from "react";
import { useSnapshot, ref } from "valtio";
import Editor, { loader } from "@monaco-editor/react";
import uniqBy from "lodash.uniqby";
import type monaco from "monaco-editor";
import { ArrowBendLeftUp } from "phosphor-react";
import { useTheme } from "next-themes";
import { useRouter } from "next/router";
import { ArrowBendLeftUp } from "phosphor-react";
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 uniqBy from "lodash.uniqby";
import Box from "./Box";
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 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({
paths: {
@@ -124,7 +123,6 @@ const HooksEditor = () => {
setMarkers(monacoRef.current);
}
}, [snap.active]);
return (
<Box
css={{
@@ -157,7 +155,7 @@ const HooksEditor = () => {
);
}
// create the websocket
// create the web socket
if (!subscriptionRef.current) {
monaco.languages.register({
id: "c",
@@ -166,12 +164,11 @@ const HooksEditor = () => {
mimetypes: ["text/plain"],
});
MonacoServices.install(monaco);
const webSocket: ReconnectingWebSocket = createWebSocket(
const webSocket = createWebSocket(
process.env.NEXT_PUBLIC_LANGUAGE_SERVER_API_ENDPOINT || ""
);
subscriptionRef.current = webSocket;
// listen when the websocket is opened
// listen when the web socket is opened
listen({
webSocket: webSocket as WebSocket,
onConnection: (connection) => {
@@ -183,14 +180,9 @@ const HooksEditor = () => {
// disposable.stop();
disposable.dispose();
} catch (err) {
toast.error('Connection to language server lost!')
console.error("Couldn't dispose the language server connection! ", err);
console.log("err", 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 {
FC, ReactNode, useCallback, useLayoutEffect, useRef, useState
useRef,
useLayoutEffect,
ReactNode,
FC,
useState,
useCallback,
} from "react";
import { Notepad, Prohibit } from "phosphor-react";
import useStayScrolled from "react-stay-scrolled";
import regexifyString from "regexify-string";
import { useSnapshot } from "valtio";
import { Box, Button, Flex, Heading, Link, Pre, Text } from ".";
import state, { ILog } from "../state";
import { AccountDialog } from "./Accounts";
import NextLink from "next/link";
import Container from "./Container";
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 {
title: string;
@@ -155,7 +160,7 @@ export const Log: FC<ILog> = ({
const enrichAccounts = useCallback(
(str?: string): ReactNode => {
if (!str) return null;
if (!str || !accounts.length) return null;
const pattern = `(${accounts.map((acc) => acc.address).join("|")})`;
const res = regexifyString({

View File

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

View File

@@ -33,6 +33,8 @@ export const addFaucetAccount = async (showToast: boolean = false) => {
return toast.error("You can only have maximum 6 accounts");
}
if (typeof window !== 'undefined') {
const toastId = showToast ? toast.loading("Creating account") : "";
const res = await fetch(`${window.location.origin}/api/faucet`, {
method: "POST",
@@ -90,4 +92,5 @@ export const addFunds = async (address: string) => {
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 { ref } from "valtio";
import { decodeBinary } from "../../utils/decodeBinary";
import Router from 'next/router';
import state from "../index";
import { saveFile } from "./saveFile";
import { decodeBinary } from "../../utils/decodeBinary";
import { ref } from "valtio";
/* compileCode sends the code of the active file to compile endpoint
* 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) => {
// Save the file to global state
saveFile(false);
if (!process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT) {
throw Error("Missing env!");
}
// Bail out if we're already compiling
if (state.compiling) {
// if compiling is ongoing return
return;
}
// Set loading state to true
state.compiling = true;
// Reset development log
state.logs = []
try {
const res = await fetch(process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT, {
method: "POST",
@@ -51,7 +46,6 @@ export const compileCode = async (activeId: number) => {
});
const json = await res.json();
state.compiling = false;
if (!json.success) {
state.logs.push({ type: "error", message: json.message });
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" });
}
state.logs.push({
type: "success",
message: `File ${state.files?.[activeId]?.name} compiled successfully. Ready to deploy.`,
link: Router.asPath.replace("develop", "deploy"),
linkText: "Go to deploy",
});
// Decode base64 encoded wasm that is coming back from the endpoint
const bufferData = await decodeBinary(json.output);
state.files[state.active].compiledContent = ref(bufferData);
state.files[state.active].lastCompiled = new Date();
// Import wabt from and create human readable version of wasm file and
// put it into state
import("wabt").then((wabt) => {
@@ -89,22 +80,12 @@ export const compileCode = async (activeId: number) => {
state.files[state.active].compiledWatContent = wast;
toast.success("Compiled successfully!", { position: "bottom-center" });
});
} catch (err: any) {
const error = err as Error
// TODO: Centralized error handling? Just a thought
if(error.message.includes("Failed to fetch")) {
state.logs.push({
type: "error",
message: "No connection to the compiler server!",
});
} else {
state.logs.push({
type: "error",
message: "Error occured while compiling!",
});
}
} catch (err) {
console.log(err);
state.logs.push({
type: "error",
message: "Error occured while compiling!",
});
state.compiling = false;
}
};

View File

@@ -1,10 +1,9 @@
import toast from "react-hot-toast";
import { derive, sign } from "xrpl-accountlib";
import { AnyJson } from "xrpl-client";
import { SetHookData } from "../../components/SetHookDialog";
import calculateHookOn, { TTS } from "../../utils/hookOnCalculator";
import state, { IAccount } from "../index";
import toast from "react-hot-toast";
import state, { IAccount } from "../index";
import calculateHookOn, { TTS } from "../../utils/hookOnCalculator";
import { SetHookData } from "../../components/SetHookDialog";
const hash = async (string: 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
* 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 (
!state.files ||
state.files.length === 0 ||
!state.files?.[state.active]?.compiledContent
) {
console.log("ebin1")
return;
}
if (!state.files?.[state.active]?.compiledContent) {
console.log("ebin2")
return;
}
if (!state.client) {
console.log("ebin3")
return;
}
const HookNamespace = await hash(arrayBufferToHex(
@@ -140,7 +136,6 @@ export const deployHook = async (account: IAccount & { name?: string }, data: Se
});
}
} catch (err) {
console.log("Ebin")
console.log(err);
state.deployLogs.push({
type: "error",
@@ -225,4 +220,4 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
}
return submitRes;
}
};
};

View File

@@ -1,5 +1,5 @@
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 normalizeUrl from "normalize-url";
import ReconnectingWebSocket from "reconnecting-websocket";
@@ -37,7 +37,7 @@ export function createUrl(path: string): string {
return normalizeUrl(`${protocol}://${location.host}${location.pathname}${path}`);
}
export function createWebSocket(url: string): ReconnectingWebSocket {
export function createWebSocket(url: string) {
const socketOptions = {
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000,
@@ -47,4 +47,4 @@ export function createWebSocket(url: string): ReconnectingWebSocket {
debug: false
};
return new ReconnectingWebSocket(url, [], socketOptions);
}
}