repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tag/Tag.tsx
import { FC, useMemo } from "react"; import styled, { css } from "styled-components"; import Img from "../Img"; import LangIcon from "../LangIcon"; import { OrString, PgFramework, PgLanguage, TutorialCategory, TutorialDetailKey, TutorialLevel, } from "../../utils/pg"; import { useDifferentBackground } from "../../hooks"; interface TagProps { kind: OrString<TutorialDetailKey>; value: any; } const Tag: FC<TagProps> = ({ kind, ...props }) => { switch (kind) { case "level": return <Level {...props} children={props.value} />; case "framework": return <Framework {...props} />; case "languages": return <Language {...props} />; case "categories": return <Category {...props} />; default: return <span {...props}></span>; } }; const Level = styled.span<{ children: TutorialLevel }>` ${({ children, theme }) => { const state = children === "Beginner" ? "success" : children === "Intermediate" ? "warning" : children === "Advanced" ? "info" : "error"; return css` padding: 0.25rem 0.5rem; background: ${theme.colors.state[state].bg}; color: ${theme.colors.state[state].color} !important; border-radius: ${theme.default.borderRadius}; font-size: ${theme.font.other.size.xsmall}; font-weight: bold; text-transform: uppercase; `; }} `; const Boxed = styled.div` ${({ theme }) => css` padding: 0.5rem 0.75rem; width: fit-content; display: flex; align-items: center; color: ${theme.colors.default.textSecondary}; border-radius: ${theme.default.borderRadius}; box-shadow: ${theme.default.boxShadow}; font-size: ${theme.font.other.size.small}; font-weight: bold; & *:first-child { margin-right: 0.5rem; } `} `; interface FrameworkProps { value: FrameworkName; } const Framework: FC<FrameworkProps> = ({ value, ...props }) => { const framework = useMemo(() => PgFramework.get(value), [value]); const { ref } = useDelayedDifferentBackground(); return ( <Boxed ref={ref} {...props}> <FrameworkImage src={framework.icon} $circle={framework.circleImage} /> {value} </Boxed> ); }; const FrameworkImage = styled(Img)<{ $circle?: boolean }>` ${({ $circle }) => css` width: 1rem; height: 1rem; ${$circle && "border-radius: 50%"}; `} `; interface LanguageProps { value: LanguageName; } const Language: FC<LanguageProps> = ({ value, ...props }) => { const { ref } = useDelayedDifferentBackground(); const path = "file." + PgLanguage.all.find((lang) => lang.name === value)?.extension.at(0); return ( <Boxed ref={ref} {...props}> <LangIcon path={path} /> {value} </Boxed> ); }; interface CategoryProps { value: TutorialCategory; } const Category: FC<CategoryProps> = ({ value, ...props }) => { const { ref } = useDelayedDifferentBackground(); return ( <Boxed ref={ref} {...props}> {value} </Boxed> ); }; /** * Add a delay to decide the parent background because the parent background may * also be using `useDifferentBackground` hook. */ const useDelayedDifferentBackground = () => useDifferentBackground(10); export default Tag;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Tag/index.ts
export { default } from "./Tag";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Editor.tsx
import { useEffect, lazy, Suspense, useState } from "react"; import styled, { css } from "styled-components"; import { SpinnerWithBg } from "../Loading"; import { Id } from "../../constants"; import { PgCommon, PgExplorer, PgTheme } from "../../utils/pg"; const Home = lazy(() => import("./Home")); const Monaco = lazy(() => import("./Monaco")); export const Editor = () => { const [showHome, setShowHome] = useState<boolean>(); // Decide which editor to show useEffect(() => { const { dispose } = PgExplorer.onNeedRender( PgCommon.debounce( () => setShowHome(!PgExplorer.tabs.length), { delay: 50 } // To fix flickering on workspace deletion ) ); return dispose; }, []); // Save explorer metadata useEffect(() => { // Save metadata to IndexedDB every 5s const saveMetadataIntervalId = PgCommon.setIntervalOnFocus(() => { PgExplorer.saveMeta().catch(); }, 5000); return () => clearInterval(saveMetadataIntervalId); }, []); if (showHome === undefined) return null; return ( <Suspense fallback={<SpinnerWithBg loading size="2rem" />}> <Wrapper>{showHome ? <Home /> : <Monaco />}</Wrapper> </Suspense> ); }; const Wrapper = styled.div` ${({ theme }) => css` width: 100%; height: 100%; overflow: auto; /** * Changing the home background only changes the part that is in view and * the remaining parts still have 'main.default.bg' which causes problem if * they are different. This selector selects the current element when home * is in view and sets the background to 'home.default.bg'. * * The reason we are setting the background in this element is also partly * due to Monaco editor's incompatibility with background-image property. * We are able to solve this problem by seting the editor's background to * transparent and set this(wrapper) element's background to background-image. */ &:has(> #${Id.HOME}) { background: ${theme.components.main.primary.home.default.bg ?? theme.components.main.default.bg}; } ${PgTheme.convertToCSS(theme.components.editor.wrapper)}; `} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/index.ts
export { Editor } from "./Editor";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Home/resources.ts
export interface ResourceProps { title: string; text: string; url: string; src: string; circleImage?: boolean; } const ROOT_DIR = "/icons/platforms/"; export const RESOURCES: ResourceProps[] = [ { title: "Cookbook", text: "Detailed explanations and guides for building applications on Solana.", url: "https://solanacookbook.com/", src: "https://solanacookbook.com/solana_cookbook_darkmode.svg", }, { title: "Anchor", text: "Everything related to developing on Solana with Anchor framework.", url: "https://www.anchor-lang.com/docs/high-level-overview", src: "https://www.anchor-lang.com/_next/image?url=%2Flogo.png&w=32&q=75", }, { title: "Seahorse", text: "Write Anchor-compatible Solana programs in Python.", url: "https://www.seahorse.dev/using-seahorse/accounts", src: "https://pbs.twimg.com/profile_images/1556384244598964226/S3cx06I2_400x400.jpg", circleImage: true, }, { title: "SolDev", text: "Solana content aggregator with easy discoverability for all your development needs.", url: "https://soldev.app/", src: ROOT_DIR + "soldev.png", }, { title: "Solana Docs", text: "The core Solana documentation used to provide deep understanding of Solana concepts.", url: "https://docs.solana.com/", src: ROOT_DIR + "solana.png", }, { title: "Metaplex Docs", text: "Documentation for understanding how to work with NFTs on Solana using the Metaplex Standards.", url: "https://developers.metaplex.com/", src: ROOT_DIR + "metaplex.png", }, ];
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Home/Home.tsx
import { FC, useEffect, useState } from "react"; import styled, { css } from "styled-components"; import Button from "../../Button"; import Img from "../../Img"; import Link from "../../Link"; import { ResourceProps, RESOURCES } from "./resources"; import { TutorialProps, TUTORIALS } from "./tutorials"; import { External, ShortArrow } from "../../Icons"; import { Id, PROJECT_NAME } from "../../../constants"; import { PgTheme } from "../../../utils/pg"; const Home = () => { // This prevents unnecessarily fetching the home content for a frame when the // app is first mounted const [show, setShow] = useState(false); useEffect(() => { setShow(true); }, []); if (!show) return null; return ( <Wrapper id={Id.HOME}> <ProjectTitle>{PROJECT_NAME}</ProjectTitle> <ContentWrapper> <ResourcesWrapper> <ResourcesTitle>Resources</ResourcesTitle> <ResourceCardsWrapper> {RESOURCES.map((r, i) => ( <Resource key={i} {...r} /> ))} </ResourceCardsWrapper> </ResourcesWrapper> <TutorialsWrapper> <TutorialsTitle>Tutorials</TutorialsTitle> <TutorialCardsWrapper> {TUTORIALS.map((t, i) => ( <Tutorial key={i} {...t} /> ))} </TutorialCardsWrapper> <Link href="/tutorials"> <PlaygroundTutorialsButton kind="icon"> Playground tutorials <ShortArrow /> </PlaygroundTutorialsButton> </Link> </TutorialsWrapper> </ContentWrapper> </Wrapper> ); }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.main.primary.home.default)}; `} `; const ProjectTitle = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.main.primary.home.title)}; `} `; const ContentWrapper = styled.div` display: flex; flex-wrap: wrap; width: 100%; `; const ResourcesWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.resources.default )}; `} `; const ResourcesTitle = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.main.primary.home.resources.title)}; `} `; const ResourceCardsWrapper = styled.div` display: flex; flex-wrap: wrap; `; const Resource: FC<ResourceProps> = ({ title, text, url, src, circleImage, }) => ( <ResourceWrapper> <ResourceTitle> <ResourceImg src={src} $circleImage={circleImage} /> {title} </ResourceTitle> <ResourceDescription>{text}</ResourceDescription> <ResourceButtonWrapper> <Link href={url}> <ResourceButton rightIcon={<External />}>Learn more</ResourceButton> </Link> </ResourceButtonWrapper> </ResourceWrapper> ); const ResourceWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.resources.card.default )}; `} `; const ResourceTitle = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.resources.card.title )}; `} `; const ResourceImg = styled(Img)<{ $circleImage?: boolean }>` ${({ theme, $circleImage }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.resources.card.image )}; ${$circleImage && "border-radius: 50%"}; `}; `; const ResourceDescription = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.resources.card.description )}; `} `; const ResourceButtonWrapper = styled.div` width: 100%; height: 20%; `; const ResourceButton = styled(Button)` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.resources.card.button )}; `} `; const TutorialsWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS( theme.components.main.primary.home.tutorials.default )}; `} `; const TutorialsTitle = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.main.primary.home.tutorials.title)}; `} `; const TutorialCardsWrapper = styled.div``; const Tutorial: FC<TutorialProps> = ({ title, url }) => { const src = getSrc(url); return ( <Link href={url}> <TutorialWrapper> {src && <TutorialIcon src={src} />} <TutorialTitle>{title}</TutorialTitle> </TutorialWrapper> </Link> ); }; const getSrc = (url: string) => { let src = ""; if (url.includes("youtube.com")) src = "youtube.png"; else if (url.includes("dev.to")) src = "devto.png"; if (src) return "/icons/platforms/" + src; }; const TutorialWrapper = styled.div` ${({ theme }) => css` ${PgTheme.convertToCSS(theme.components.main.primary.home.tutorials.card)}; `} `; const TutorialIcon = styled(Img)` height: 1rem; margin-right: 0.75rem; `; const TutorialTitle = styled.span``; const PlaygroundTutorialsButton = styled(Button)` ${({ theme }) => css` color: ${theme.colors.default.primary}; padding: 0.25rem 0.5rem; svg { margin-left: 0.25rem; } &::hover { text-decoration: underline; } `} `; export default Home;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Home/index.ts
export { default } from "./Home";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Home/tutorials.ts
export interface TutorialProps { title: string; url: string; } export const TUTORIALS: TutorialProps[] = [ { title: "Build a Blog DApp using Solana Playground", url: "https://www.youtube.com/watch?v=PWvbMWyuYNQ", }, { title: "Build a Todo DApp using Solana Playground", url: "https://www.youtube.com/watch?v=3_zoGgffxac", }, { title: "Build TikTok DApp using Solana Playground", url: "https://www.youtube.com/watch?v=qIGs3XWybgU", }, { title: "A Guide to Full Stack Development on Solana", url: "https://dev.to/edge-and-node/the-complete-guide-to-full-stack-solana-development-with-react-anchor-rust-and-phantom-3291", }, ];
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/CodeMirror.tsx
import { useEffect, useMemo, useRef, useState } from "react"; import styled, { css, useTheme } from "styled-components"; import { EditorView } from "@codemirror/view"; import { Compartment, EditorState } from "@codemirror/state"; import { autosave, defaultExtensions, getThemeExtension } from "./extensions"; import { EventName } from "../../../constants"; import { PgExplorer, PgProgramInfo, PgTerminal, PgCommon, PgPackage, PgCommand, PgTheme, PgFramework, } from "../../../utils/pg"; import { useKeybind, useSendAndReceiveCustomEvent } from "../../../hooks"; const CodeMirror = () => { const theme = useTheme(); const editorTheme = useMemo( () => { const editorStyles = theme.components.editor; return EditorView.theme( { // Editor "&": { height: "100%", background: editorStyles.default.bg, color: editorStyles.default.color, fontFamily: editorStyles.default.fontFamily, fontSize: editorStyles.default.fontSize, }, // Cursor "& .cm-cursor": { borderLeft: "2px solid " + editorStyles.default.cursorColor, }, // Gutters "& .cm-gutters": { background: editorStyles.gutter.bg, color: editorStyles.gutter.color, borderRight: editorStyles.gutter.borderRight, }, "& .cm-activeLineGutter": { background: editorStyles.gutter.activeBg, color: editorStyles.gutter.activeColor, }, "& .cm-gutterElement:nth-child(1)": { padding: "0.125rem", }, "& .cm-scroller": { fontFamily: editorStyles.default.fontFamily, }, // Line "& .cm-line": { border: "1.5px solid transparent", }, "& .cm-activeLine": { background: editorStyles.default.activeLine.bg, borderColor: editorStyles.default.activeLine.borderColor, borderRightColor: "transparent", borderLeftColor: "transparent", }, // Selection "& .cm-selectionBackground, &.cm-focused .cm-selectionBackground, & .cm-selectionMatch": { background: editorStyles.default.selection.bg, color: editorStyles.default.selection.color, }, // Tooltip ".cm-tooltip": { background: editorStyles.tooltip.bg, color: editorStyles.tooltip.color, border: "1px solid " + editorStyles.tooltip.borderColor, }, ".cm-tooltip-autocomplete": { "& > ul": { "& > li > div.cm-completionIcon": { marginRight: "0.5rem", }, "& > li[aria-selected]": { background: editorStyles.tooltip.selectedBg, color: editorStyles.tooltip.selectedColor, }, }, }, // Panels ".cm-panels": { background: theme.colors.default.bgSecondary, color: theme.colors.default.textPrimary, width: "fit-content", height: "fit-content", position: "absolute", top: 0, right: "10%", left: "auto", zIndex: 2, }, // Search ".cm-searchMatch": { background: editorStyles.default.searchMatch.bg, color: editorStyles.default.searchMatch.color, }, ".cm-searchMatch-selected": { background: editorStyles.default.searchMatch.selectedBg, color: editorStyles.default.searchMatch.color, }, // Search popup ".cm-panel.cm-search": { background: theme.colors.default.bgSecondary, "& input, & button, & label": { margin: ".2em .6em .2em 0", }, "& input[type=checkbox]": { marginRight: ".2em", }, "& label": { fontSize: "80%", "&:nth-of-type(3)": { marginRight: "1.5rem", }, }, "& button[name=close]": { position: "absolute", top: "0.25rem", right: "0.25rem", margin: 0, width: "1rem", height: "1rem", color: theme.colors.default.textPrimary, backgroundColor: "inherit", borderRadius: "0.25rem", }, "& button:hover": { cursor: "pointer", background: theme.colors.default.bgPrimary, }, }, }, { dark: theme.isDark } ); }, //eslint-disable-next-line react-hooks/exhaustive-deps [theme.name, theme.components.editor.default.fontFamily] ); const codemirrorRef = useRef<HTMLDivElement>(null); const [editor, setEditor] = useState<EditorView>(); // Create editor useEffect(() => { if (!codemirrorRef.current) return; if (codemirrorRef.current.hasChildNodes()) { codemirrorRef.current.removeChild(codemirrorRef.current.firstChild!); } setEditor( new EditorView({ parent: codemirrorRef.current, }) ); // eslint-disable-next-line react-hooks/exhaustive-deps }, [editorTheme]); // When user switches files or editor changed useEffect(() => { if (!editor) return; let positionDataIntervalId: NodeJS.Timer; const { dispose } = PgExplorer.onDidOpenFile((curFile) => { if (!curFile) return; // Clear previous state positionDataIntervalId && clearInterval(positionDataIntervalId); // Change editor state const languageCompartment = new Compartment(); const extensions = [ defaultExtensions(), editorTheme, getThemeExtension(theme.highlight), autosave(curFile, 500), languageCompartment.of([]), ]; // Create editor state editor.setState( EditorState.create({ doc: curFile.content, extensions, }) ); // Lazy load language extensions (async () => { let languageExtensions; switch (PgExplorer.getCurrentFileLanguage()?.name) { case "Rust": { const { rustExtensions } = await import( "./extensions/languages/rust" ); const framework = await PgFramework.getFromFiles(); languageExtensions = rustExtensions(framework?.name === "Anchor"); break; } case "Python": { const { pythonExtensions } = await import( "./extensions/languages/python" ); languageExtensions = pythonExtensions(); break; } case "JavaScript": { const { javascriptExtensions } = await import( "./extensions/languages/javascript" ); languageExtensions = javascriptExtensions(false); break; } case "TypeScript": { const { javascriptExtensions } = await import( "./extensions/languages/javascript" ); languageExtensions = javascriptExtensions(true); } } if (languageExtensions) { editor.dispatch({ effects: languageCompartment.reconfigure(languageExtensions), }); } })(); // Get position data const position = PgExplorer.getEditorPosition(curFile.path); // Scroll to the saved position and set the cursor position editor.dispatch( { effects: EditorView.scrollIntoView( position.topLineNumber ? editor.state.doc.line(position.topLineNumber).from : 0, { y: "start", yMargin: 0, } ), }, { selection: { anchor: position.cursor.from, head: position.cursor.to }, } ); // Focus the editor editor.focus(); // Save position data positionDataIntervalId = setInterval(() => { PgExplorer.saveEditorPosition(curFile.path, { cursor: { from: editor.state.selection.main.anchor, to: editor.state.selection.main.head, }, topLineNumber: editor.state.doc.lineAt( editor.lineBlockAtHeight( editor.scrollDOM.getBoundingClientRect().top - editor.documentTop ).from ).number, }); }, 1000); }); return () => { clearInterval(positionDataIntervalId); dispose(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [editor]); // Editor custom events useEffect(() => { if (!editor) return; const handleFocus = () => { if (!editor.hasFocus) editor.focus(); }; document.addEventListener(EventName.EDITOR_FOCUS, handleFocus); return () => { document.removeEventListener(EventName.EDITOR_FOCUS, handleFocus); }; }, [editor]); // Format event useSendAndReceiveCustomEvent( EventName.EDITOR_FORMAT, async (ev?: { lang: LanguageName; fromTerminal: boolean }) => { if (!editor) return; const lang = PgExplorer.getCurrentFileLanguage(); if (!lang) return; let formatRust; const isCurrentFileRust = lang.name === "Rust"; if (isCurrentFileRust) { formatRust = async () => { const { rustfmt } = await PgPackage.import("rustfmt"); const currentContent = editor.state.doc.toString(); let result; try { result = rustfmt(currentContent); } catch (e: any) { result = { error: () => e.message }; } if (result.error()) { PgTerminal.log(PgTerminal.error("Unable to format the file.")); return; } const formattedCode = result.code!(); let cursorOffset = editor.state.selection.ranges[0].from; const currentLine = editor.state.doc.lineAt(cursorOffset); const isFirstOrLastLine = currentLine.number !== 1 || currentLine.number !== editor.state.doc.lines; if (!isFirstOrLastLine) { const beforeLine = editor.state.doc.line(currentLine.number - 1); const afterLine = editor.state.doc.line(currentLine.number + 1); const searchText = currentContent.substring( beforeLine.from, afterLine.to ); const searchIndex = formattedCode.indexOf(searchText); if (searchIndex !== -1) { // Check if there are multiple instances of the same searchText const nextSearchIndex = formattedCode.indexOf( searchText, searchIndex + searchText.length ); if (nextSearchIndex === -1) { cursorOffset = searchIndex + cursorOffset - beforeLine.from; } } } editor.dispatch({ changes: { from: 0, to: currentContent.length, insert: formattedCode, }, selection: { anchor: cursorOffset, head: cursorOffset, }, }); if (ev?.fromTerminal) { PgTerminal.log(PgTerminal.success("Format successful.")); } }; } const isCurrentFileJsLike = PgExplorer.isCurrentFileJsLike(); let formatJSTS; if (isCurrentFileJsLike) { formatJSTS = async () => { const { formatWithCursor } = await import("prettier/standalone"); const { default: parserTypescript } = await import( "prettier/parser-typescript" ); const currentContent = editor.state.doc.toString(); const result = formatWithCursor(currentContent, { parser: "typescript", plugins: [parserTypescript], cursorOffset: editor.state.selection.ranges[0].from, }); editor.dispatch({ changes: { from: 0, to: currentContent.length, insert: result.formatted, }, selection: { anchor: result.cursorOffset, head: result.cursorOffset, }, }); if (ev?.fromTerminal) { PgTerminal.log(PgTerminal.success("Format successful.")); } }; } const isCurrentFileJSON = lang.name === "JSON"; let formatJSON; if (isCurrentFileJSON) { formatJSON = () => { const currentContent = editor.state.doc.toString(); const formattedCode = PgCommon.prettyJSON(JSON.parse(currentContent)); let cursorOffset = editor.state.selection.ranges[0].from; const currentLine = editor.state.doc.lineAt(cursorOffset); if (currentLine.number !== 1) { const beforeLine = editor.state.doc.line(currentLine.number - 1); const afterLine = editor.state.doc.line(currentLine.number + 1); const searchText = currentContent.substring( beforeLine.from, afterLine.to ); const searchIndex = formattedCode.indexOf(searchText); if (searchIndex !== -1) { // Check if there are multiple instances of the same searchText const nextSearchIndex = formattedCode.indexOf( searchText, searchIndex + searchText.length ); if (nextSearchIndex === -1) { cursorOffset = searchIndex + cursorOffset - beforeLine.from; } } } editor.dispatch({ changes: { from: 0, to: currentContent.length, insert: formattedCode, }, selection: { anchor: cursorOffset, head: cursorOffset, }, }); }; } // From keybind if (!ev) { if (isCurrentFileRust) { formatRust && (await formatRust()); } else if (isCurrentFileJsLike) { formatJSTS && (await formatJSTS()); } else if (isCurrentFileJSON) { formatJSON && formatJSON(); } return; } // From terminal switch (ev.lang) { case "Rust": { if (!isCurrentFileRust) { PgTerminal.log( PgTerminal.warning("Current file is not a Rust file.") ); return; } formatRust && (await formatRust()); break; } case "TypeScript": { if (!isCurrentFileJsLike) { PgTerminal.log( PgTerminal.warning("Current file is not a JS/TS file.") ); return; } formatJSTS && (await formatJSTS()); } } }, [editor] ); // Format on keybind useKeybind( "Ctrl+S", () => { if (editor?.hasFocus) { PgTerminal.process(async () => { await PgCommon.sendAndReceiveCustomEvent(EventName.EDITOR_FORMAT); }); } }, [editor] ); // Update program id useEffect(() => { if (!editor) return; const getProgramIdStartAndEndIndex = ( content: string, isPython?: boolean ) => { const findText = isPython ? "declare_id" : "declare_id!"; const findTextIndex = content.indexOf(findText); if (!content || !findTextIndex || findTextIndex === -1) return; const quoteStartIndex = findTextIndex + findText.length + 1; const quoteChar = content[quoteStartIndex]; const quoteEndIndex = content.indexOf(quoteChar, quoteStartIndex + 1); return [quoteStartIndex, quoteEndIndex]; }; const updateId = async () => { const programPkStr = PgProgramInfo.getPkStr(); if (!programPkStr) return; // Update in editor const currentLang = PgExplorer.getCurrentFileLanguage(); const isRust = currentLang?.name === "Rust"; const isPython = currentLang?.name === "Python"; if (!isRust && !isPython) return; const editorContent = editor.state.doc.toString(); const indices = getProgramIdStartAndEndIndex(editorContent, isPython); if (!indices) return; const [quoteStartIndex, quoteEndIndex] = indices; try { editor.dispatch({ changes: { from: quoteStartIndex + 1, to: quoteEndIndex, insert: programPkStr, }, }); } catch (e: any) { console.log("Program ID update error:", e.message); } }; const { dispose } = PgCommon.batchChanges(updateId, [ PgCommand.build.onDidRunStart, PgProgramInfo.onDidChangePk, ]); return dispose; }, [editor]); return <Wrapper ref={codemirrorRef} />; }; const Wrapper = styled.div` ${({ theme }) => css` ${PgTheme.getScrollbarCSS({ allChildren: true, borderRadius: 0, height: "0.75rem", width: "0.75rem", })}; & ::-webkit-scrollbar-track { background: ${theme.components.main.default.bg}; border-left: 1px solid ${theme.colors.default.border}; } & ::-webkit-scrollbar-corner { background: ${theme.components.main.default.bg}; } `} `; export default CodeMirror;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/index.ts
export { default } from "./CodeMirror";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/extensions.ts
import { keymap, highlightSpecialChars, drawSelection, highlightActiveLine, dropCursor, rectangularSelection, crosshairCursor, lineNumbers, highlightActiveLineGutter, scrollPastEnd, } from "@codemirror/view"; import { Extension, EditorState } from "@codemirror/state"; import { indentOnInput, bracketMatching, foldGutter, foldKeymap, } from "@codemirror/language"; import { defaultKeymap, history, historyKeymap, indentWithTab, } from "@codemirror/commands"; import { autocompletion, completionKeymap, closeBrackets, closeBracketsKeymap, } from "@codemirror/autocomplete"; import { highlightSelectionMatches, searchKeymap, search, } from "@codemirror/search"; import { lintKeymap } from "@codemirror/lint"; export const defaultExtensions = (): Extension[] => { return [ lineNumbers(), highlightActiveLineGutter(), highlightSpecialChars(), history(), foldGutter(), drawSelection(), dropCursor(), EditorState.allowMultipleSelections.of(true), indentOnInput(), bracketMatching(), closeBrackets(), autocompletion(), rectangularSelection(), crosshairCursor(), highlightActiveLine(), highlightSelectionMatches(), search({ top: true }), scrollPastEnd(), keymap.of([ ...defaultKeymap, ...closeBracketsKeymap, ...historyKeymap, ...foldKeymap, ...completionKeymap, ...lintKeymap, ...searchKeymap, indentWithTab, ]), ]; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/index.ts
export { autosave } from "./autosave"; export { getThemeExtension } from "./theme"; export * from "./extensions";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/snippets/rust.ts
/* eslint-disable no-template-curly-in-string */ import { Completion, snippetCompletion as snip, } from "@codemirror/autocomplete"; /** Rust language snippets */ export const RUST_SNIPPETS: Completion[] = [ snip("struct ${1:MyStruct} {\n\t${2}\n}", { label: "create struct(cst)", type: "class", info: "Create struct", }), snip("pub struct ${1:MyStruct} {\n\t${2}\n}", { label: "create pub struct(cpst)", type: "class", info: "Create pub struct", }), snip("enum ${1:MyEnum} {\n\t${2}\n}", { label: "create enum(cen)", type: "class", info: "Create enum", }), snip("pub enum ${1:MyEnum} {\n\t${2}\n}", { label: "create pub enum(cpen)", type: "class", info: "Create pub enum", }), ]; /** Common snippets for Native and Anchor */ export const COMMON_SNIPPETS: Completion[] = [ snip('declare_id!("${1}");${2}', { label: "declare id(di)", type: "function", info: "Declare program id", }), snip("#[derive(${Trait})]", { label: "derive(drv)", type: "function", info: "Derive a trait", }), snip('msg!("${message}");', { label: "message(msg)", type: "function", info: "Log program message", }), ]; /** Native specific snippets */ export const NATIVE_SNIPPETS: Completion[] = [ snip("#[derive(BorshSerialize, BorshDeserialize)]", { label: "serialize deserialize(sd)", type: "function", info: "Derive Borsh de-serialize", }), ]; /** Anchor specific snippets */ export const ANCHOR_SNIPPETS: Completion[] = [ // Use statements snip("use anchor_lang::prelude::*;", { label: "use anchor prelude(uap)", type: "namespace", info: "Use anchor prelude", }), // Macros snip("require!(${condition}, ${CustomError});", { label: "require(rq)", type: "function", info: "Require macro", }), // Procedural macros snip("#[derive(AnchorSerialize, AnchorDeserialize)]", { label: "serialize deserialize(sd)", type: "function", info: "Derive Anchor de-serialize", }), snip("#[account(mut)]", { label: "mut attribute(mat)", type: "function", info: "Mut attribute", }), snip("#[account(mut)]\npub ${mut_account}: Account<'info, ${MutAccount}>,", { label: "mut account(mac)", type: "function", info: "Mut account", }), snip("#[account(init, payer = signer, space = ${space})]", { label: "init attribute(iat)", type: "function", info: "Init attribute", }), snip( "#[account(\n\tinit,\n\tpayer = signer,\n\tspace = ${space},\n\tseeds = [${2}],\n\tbump\n)]", { label: "init attribute with seeds(iats)", type: "function", info: "Init attribute with seeds", } ), snip( "#[account(init, payer = signer, space = ${space})]\npub ${new_account}: Account<'info, ${NewAccount}>,", { label: "init account(iac)", type: "function", info: "Init account", } ), snip( "#[account(\n\tinit,\n\tpayer = signer,\n\tspace = ${1:space},\n\tseeds = [${2}],\n\tbump\n)]\npub ${new_account}: Account<'info, ${NewAccount}>,", { label: "init account with seeds(iacs)", type: "function", info: "Init account with seeds", } ), // Creators snip( "#[program]\nmod ${my_program} {\n\tuse super::*;\n\tpub fn ${init}(ctx: Context<${MyContext}>) -> Result<()> {\n\t\tOk(())\n\t}\n}", { label: "create program(cpr)", type: "interface", info: "Create program", } ), snip( "pub fn ${name}(ctx: Context<${MyContext}>) -> Result<()> {\n\tOk(())\n}", { label: "create instruction(cin)", type: "function", info: "Create Anchor instruction", } ), snip( "#[derive(Accounts)]\npub struct ${MyContext}<'info> {\n\t#[account(mut)]\n\tpub ${signer}: Signer<'info>,\n}", { label: "create context(cctx)", type: "class", info: "Create context", } ), snip( "#[account]\n#[derive(Default)]\npub struct ${MyAccount} {\n\tpub ${field}: ${u64},\n}", { label: "create account(cac)", type: "class", info: "Create account", } ), snip("#[event]\npub struct ${1:EventName} {\n\t${2}\n}", { label: "create event(cev)", type: "class", info: "Create event", }), snip("#[constant]\npub const ${CONSTANT}: ${type} = ${value};", { label: "create constant(ccnst)", type: "function", info: "Create constant", }), // Errors snip( '#[error_code]\npub enum ${MyError} {\n\t#[msg("${Custom Error Message}")]\n\t${CustomErrorName},\n}', { label: "create custom error(cce)", type: "enum", info: "Create custom error", } ), snip('#[msg("${Custom error message}")]\n${CustomErrorName},', { label: "custom error field(cef)", type: "enum", info: "Define custom error variant", }), // Properties snip("pub system_program: Program<'info, System>,", { label: "system program(sp)", type: "property", info: "Add system program account", }), snip("pub token_program: Program<'info, Token>,", { label: "token program(tp)", type: "property", info: "Add token program account", }), snip("pub rent: Sysvar<'info, Rent>,", { label: "rent sysvar(sysr)", type: "property", info: "Add rent sysvar account", }), snip("pub clock: Sysvar<'info, Clock>,", { label: "clock sysvar(sysc)", type: "property", info: "Add clock sysvar account", }), snip("#[account(mut)]\npub signer: Signer<'info>,", { label: "signer(sig)", type: "property", info: "Add signer account", }), ];
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/snippets/python.ts
/* eslint-disable no-template-curly-in-string */ import { Completion, snippetCompletion as snip, } from "@codemirror/autocomplete"; /** Python language snippets */ export const PYTHON_SNIPPETS: Completion[] = []; /** Seahorse specific snippets */ export const SEAHORSE_SNIPPETS: Completion[] = [ snip("from seahorse.prelude import *", { label: "import seahorse prelude(isp)", type: "namespace", info: "Import Seahorse Prelude", }), snip("declare_id('${1}')${2}", { label: "declare id(di)", type: "function", info: "Declare program id", }), snip("print('${1:message}')", { label: "print(msg)", type: "function", info: "Log program message", }), snip("assert ${1:condition}, '${2:error message}'", { label: "assert(asrt)", type: "function", info: "Assert a statement, throw error with the specified message if assertion fails", }), // Creators snip( "@instruction\ndef ${1:instruction_name}(${2:signer}: Signer):\n\t${3}", { label: "create instruction(cin)", type: "function", info: "Create Seahorse instruction", } ), snip("class ${1:AccountName}(Account):\n\t${2:property}: ${3:type}", { label: "create account(cac)", type: "class", info: "Create program account", }), snip( "class ${1:EventName}(Event):\n\t${2:property}: ${3:type}\n\n\tdef __init__(self, ${2:property}: ${3:type}):\n\t\tself.${2:property} = ${2:property}\n\t\t${4}", { label: "create event(cev)", type: "class", info: "Create program event", } ), ];
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/languages/rust.ts
import { rustLanguage } from "@codemirror/lang-rust"; import { ifNotIn, completeFromList, Completion, } from "@codemirror/autocomplete"; import { indentUnit, LanguageSupport } from "@codemirror/language"; import { ANCHOR_SNIPPETS, COMMON_SNIPPETS, NATIVE_SNIPPETS, RUST_SNIPPETS, } from "../snippets/rust"; export const rustExtensions = (isAnchor: boolean) => { const snippets: Completion[] = RUST_SNIPPETS.concat(COMMON_SNIPPETS); if (isAnchor) snippets.push(...ANCHOR_SNIPPETS); else snippets.push(...NATIVE_SNIPPETS); const support = rustLanguage.data.of({ autocomplete: ifNotIn( ["LineComment", "BlockComment", "String", "Char"], completeFromList(snippets) ), }); return [new LanguageSupport(rustLanguage, support), indentUnit.of(" ")]; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/languages/javascript.ts
import { javascript } from "@codemirror/lang-javascript"; export const javascriptExtensions = (isTypescript: boolean) => { return [javascript({ typescript: isTypescript })]; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/languages/python.ts
import { pythonLanguage } from "@codemirror/lang-python"; import { ifNotIn, completeFromList, Completion, } from "@codemirror/autocomplete"; import { LanguageSupport } from "@codemirror/language"; import { PYTHON_SNIPPETS, SEAHORSE_SNIPPETS } from "../snippets/python"; export const pythonExtensions = () => { const snippets: Completion[] = PYTHON_SNIPPETS.concat(SEAHORSE_SNIPPETS); const support = pythonLanguage.data.of({ autocomplete: ifNotIn( ["LineComment", "BlockComment", "String"], completeFromList(snippets) ), }); return [new LanguageSupport(pythonLanguage, support)]; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/autosave/autosave.ts
import { EditorView, ViewUpdate } from "@codemirror/view"; import { PgExplorer, FullFile } from "../../../../../utils/pg"; export const autosave = (curFile: FullFile, ms: number) => { let timeoutId: NodeJS.Timeout; return EditorView.updateListener.of((v: ViewUpdate) => { // Runs when the editor content changes if (v.docChanged) { timeoutId && clearTimeout(timeoutId); timeoutId = setTimeout(async () => { const args: [string, string] = [curFile.path, v.state.doc.toString()]; // Save to state PgExplorer.saveFileToState(...args); // Saving to state is enough if it's a temporary project if (PgExplorer.isTemporary) return; // Save to `indexedDB` try { await PgExplorer.fs.writeFile(...args); } catch (e: any) { console.log(`Error saving file ${curFile.path}. ${e.message}`); } }, ms); } }); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/autosave/index.ts
export * from "./autosave";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/theme/index.ts
export { getThemeExtension } from "./theme";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/CodeMirror/extensions/theme/theme.ts
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language"; import { tags as t } from "@lezer/highlight"; import type { Highlight } from "../../../../../utils/pg"; export const getThemeExtension = (h: Highlight) => { return syntaxHighlighting( HighlightStyle.define([ { tag: t.typeName, ...h.typeName, }, { tag: t.variableName, ...h.variableName, }, { tag: t.namespace, ...h.namespace, }, { tag: t.macroName, ...h.macroName, }, { tag: t.function(t.variableName), ...h.functionCall, }, { tag: t.function(t.propertyName), ...h.functionDef, }, { tag: t.definitionKeyword, ...h.definitionKeyword, }, { tag: t.moduleKeyword, ...h.moduleKeyword, }, { tag: t.modifier, ...h.modifier, }, { tag: t.controlKeyword, ...h.controlKeyword, }, { tag: t.operatorKeyword, ...h.operatorKeyword, }, { tag: t.keyword, ...h.keyword, }, { tag: t.self, ...h.self, }, { tag: t.bool, ...h.bool, }, { tag: t.integer, ...h.integer, }, { tag: t.literal, ...h.literal, }, { tag: t.string, ...h.string, }, { tag: t.character, ...h.character, }, { tag: t.operator, ...h.operator, }, { tag: t.derefOperator, ...h.derefOperator, }, { tag: t.special(t.variableName), ...h.specialVariable, }, { tag: t.lineComment, ...h.lineComment, }, { tag: t.blockComment, ...h.blockComment, }, { tag: t.meta, ...h.meta, }, { tag: t.invalid, ...h.invalid, }, { tag: t.constant(t.variableName), ...h.typeName, }, { tag: t.regexp, ...h.regexp, }, { tag: t.tagName, ...h.tagName }, { tag: t.attributeName, ...h.attributeName }, { tag: t.attributeValue, ...h.attributeValue }, { tag: t.annotation, ...h.annotion, }, ]) ); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/Monaco.tsx
import { useEffect, useRef, useState } from "react"; import styled, { useTheme } from "styled-components"; import * as monaco from "monaco-editor"; import { initLanguages } from "./languages"; import { SpinnerWithBg } from "../../Loading"; import { EventName } from "../../../constants"; import { PgCommand, PgCommon, PgExplorer, PgLanguage, PgPackage, PgProgramInfo, PgTerminal, PgTheme, } from "../../../utils/pg"; import { useAsyncEffect, useKeybind, useSendAndReceiveCustomEvent, } from "../../../hooks"; const Monaco = () => { const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor>(); const [isThemeSet, setIsThemeSet] = useState(false); const monacoRef = useRef<HTMLDivElement>(null); // Set default options useEffect(() => { // Compiler options const compilerOptions: monaco.languages.typescript.CompilerOptions = { lib: ["es2020"], target: monaco.languages.typescript.ScriptTarget.ES2017, module: monaco.languages.typescript.ModuleKind.ESNext, moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs, allowNonTsExtensions: true, allowSyntheticDefaultImports: true, }; monaco.languages.typescript.typescriptDefaults.setCompilerOptions( compilerOptions ); monaco.languages.typescript.javascriptDefaults.setCompilerOptions( compilerOptions ); // Diagnostic options monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({ diagnosticCodesToIgnore: [ 1375, // top level await 2686, // UMD global because of module ], }); }, []); const theme = useTheme(); // Set theme useAsyncEffect(async () => { const editorStyles = theme.components.editor; if (theme.isDark) { /** Convert the colors to hex values when necessary */ const toHexColors = (colors: Record<string, string>) => { for (const key in colors) { const color = colors[key]; colors[key] = color === "transparent" || color === "inherit" ? "#00000000" : color; } return colors; }; monaco.editor.defineTheme(theme.name, { base: "vs-dark", inherit: true, colors: toHexColors({ /////////////////////////////// General ////////////////////////////// foreground: editorStyles.default.color, errorForeground: theme.colors.state.error.color, descriptionForeground: theme.colors.default.textSecondary, focusBorder: theme.colors.default.primary + theme.default.transparency!.high, /////////////////////////////// Editor /////////////////////////////// "editor.foreground": editorStyles.default.color, "editor.background": editorStyles.default.bg, "editorCursor.foreground": editorStyles.default.cursorColor, "editor.lineHighlightBackground": editorStyles.default.activeLine.bg, "editor.lineHighlightBorder": editorStyles.default.activeLine.borderColor, "editor.selectionBackground": editorStyles.default.selection.bg, "editor.inactiveSelectionBackground": editorStyles.default.searchMatch.bg, "editorGutter.background": editorStyles.gutter.bg, "editorLineNumber.foreground": editorStyles.gutter.color, "editorError.foreground": theme.colors.state.error.color, "editorWarning.foreground": theme.colors.state.warning.color, ////////////////////////////// Dropdown ////////////////////////////// "dropdown.background": editorStyles.tooltip.bg, "dropdown.foreground": editorStyles.tooltip.color, /////////////////////////////// Widget /////////////////////////////// "editorWidget.background": editorStyles.tooltip.bg, "editorHoverWidget.background": editorStyles.tooltip.bg, "editorHoverWidget.border": editorStyles.tooltip.borderColor, //////////////////////////////// List //////////////////////////////// "list.hoverBackground": theme.colors.state.hover.bg!, "list.activeSelectionBackground": editorStyles.tooltip.selectedBg, "list.activeSelectionForeground": editorStyles.tooltip.selectedColor, "list.inactiveSelectionBackground": editorStyles.tooltip.bg, "list.inactiveSelectionForeground": editorStyles.tooltip.color, "list.highlightForeground": theme.colors.state.info.color, //////////////////////////////// Input /////////////////////////////// "input.background": theme.components.input.bg!, "input.foreground": theme.components.input.color, "input.border": theme.components.input.borderColor, "inputOption.activeBorder": theme.colors.default.primary + theme.default.transparency.high, "input.placeholderForeground": theme.colors.default.textSecondary, "inputValidation.infoBackground": theme.colors.state.info.bg!, "inputValidation.infoBorder": theme.colors.state.info.color, "inputValidation.warningBackground": theme.colors.state.warning.bg!, "inputValidation.warningBorder": theme.colors.state.warning.color, "inputValidation.errorBackground": theme.colors.state.error.bg!, "inputValidation.errorBorder": theme.colors.state.error.color, /////////////////////////////// Minimap ////////////////////////////// "minimap.background": editorStyles.minimap.bg, "minimap.selectionHighlight": editorStyles.minimap.selectionHighlight, ////////////////////////////// Peek view ///////////////////////////// "peekView.border": editorStyles.peekView.borderColor, "peekViewTitle.background": editorStyles.peekView.title.bg, "peekViewTitleLabel.foreground": editorStyles.peekView.title.labelColor, "peekViewTitleDescription.foreground": editorStyles.peekView.title.descriptionColor, "peekViewEditor.background": editorStyles.peekView.editor.bg, "peekViewEditor.matchHighlightBackground": editorStyles.peekView.editor.matchHighlightBg, "peekViewEditorGutter.background": editorStyles.peekView.editor.gutterBg, "peekViewResult.background": editorStyles.peekView.result.bg, "peekViewResult.lineForeground": editorStyles.peekView.result.lineColor, "peekViewResult.fileForeground": editorStyles.peekView.result.fileColor, "peekViewResult.selectionBackground": editorStyles.peekView.result.selectionBg, "peekViewResult.selectionForeground": editorStyles.peekView.result.selectionColor, "peekViewResult.matchHighlightBackground": editorStyles.peekView.result.matchHighlightBg, ////////////////////////////// Inlay hint //////////////////////////// "editorInlayHint.background": editorStyles.inlayHint.bg, "editorInlayHint.foreground": editorStyles.inlayHint.color, "editorInlayHint.parameterBackground": editorStyles.inlayHint.parameterBg, "editorInlayHint.parameterForeground": editorStyles.inlayHint.parameterColor, "editorInlayHint.typeBackground": editorStyles.inlayHint.typeBg, "editorInlayHint.typeForeground": editorStyles.inlayHint.typeColor, }), rules: [], }); monaco.editor.setTheme(theme.name); } else { monaco.editor.setTheme("vs"); } // Initialize language grammars and configurations const { dispose } = await PgCommon.transition(() => { return initLanguages(PgTheme.convertToTextMateTheme(theme)); }); setIsThemeSet(true); return dispose; }, [theme]); // Set font useEffect(() => { editor?.updateOptions({ fontFamily: theme.components.editor.default.fontFamily, }); }, [editor, theme]); // Set tab size useEffect(() => { if (!editor) return; const { dispose } = editor.onDidChangeModel((ev) => { if (!ev.newModelUrl) return; const model = monaco.editor.getModel(ev.newModelUrl); if (!model) return; switch (model.getLanguageId()) { case "javascript": case "typescript": case "json": model.updateOptions({ tabSize: 2 }); } }); return dispose; }, [editor]); // Create editor useEffect(() => { if (editor || !isThemeSet || !monacoRef.current) return; setEditor( monaco.editor.create(monacoRef.current, { automaticLayout: true, fontLigatures: true, }) ); }, [editor, isThemeSet]); // Dispose editor useEffect(() => { if (editor) return () => editor.dispose(); }, [editor]); // Set editor state useEffect(() => { if (!editor) return; let positionDataIntervalId: NodeJS.Timer; const switchFile = PgExplorer.onDidOpenFile((curFile) => { // Clear previous state if (positionDataIntervalId) clearInterval(positionDataIntervalId); if (!curFile) return; // FIXME: TS assumes the file is a script(with global scoping rules) if // there are no `import` or `export` statements. This results with problems // such as conflicting declarations and getting autocompletion for variables // that are not actually in scope. // // `moduleDetection` compiler option has been added in TypeScript 4.7 // (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#control-over-module-detection) // but it is not yet available in Monaco editor. // // In order to fix this issue, dispose all of the other JS/TS models if // the current file is a JS/TS file. Unfortunately, this causes flickering // when switching between JS/TS files because models are being disposed and // recreated each time instead of only the first time. // https://github.com/microsoft/monaco-editor/issues/1083 if (PgLanguage.getIsPathJsLike(curFile.path)) { monaco.editor .getModels() .filter((model) => { return ( // Only check client and tests dir otherwise `target/types` model // will also get disposed (model.uri.path.includes(PgExplorer.PATHS.CLIENT_DIRNAME) || model.uri.path.includes(PgExplorer.PATHS.TESTS_DIRNAME)) && PgLanguage.getIsPathJsLike(model.uri.path) && model.uri.path !== curFile.path && !model.getValue().includes("import") ); }) .forEach((model) => model.dispose()); } // Check whether the model has already been created const model = monaco.editor .getModels() .find((model) => model.uri.path === curFile.path) ?? monaco.editor.createModel( curFile.content!, undefined, monaco.Uri.parse(curFile.path) ); editor.setModel(model); // Get position data const position = PgExplorer.getEditorPosition(curFile.path); // Scroll to the saved line editor.setScrollTop( position.topLineNumber ? editor.getTopForLineNumber(position.topLineNumber) : 0 ); // Set the cursor position const startPosition = model.getPositionAt(position.cursor.from); const endPosition = model.getPositionAt(position.cursor.to); editor.setSelection({ startLineNumber: startPosition.lineNumber, startColumn: startPosition.column, endLineNumber: endPosition.lineNumber, endColumn: endPosition.column, }); // Focus the editor editor.focus(); // Save position data positionDataIntervalId = setInterval(() => { const selection = editor.getSelection(); if (!selection) return; PgExplorer.saveEditorPosition(curFile.path, { cursor: { from: model.getOffsetAt(selection.getStartPosition()), to: model.getOffsetAt(selection.getEndPosition()), }, topLineNumber: editor.getVisibleRanges()[0].startLineNumber, }); }, 1000); }); const disposeModelsFromPath = (path: string) => { // Dispose self and all child models monaco.editor .getModels() .filter((model) => model.uri.path.startsWith(path)) .forEach((model) => model.dispose()); }; const renameItem = PgExplorer.onDidRenameItem(disposeModelsFromPath); const deleteItem = PgExplorer.onDidDeleteItem(disposeModelsFromPath); return () => { clearInterval(positionDataIntervalId); switchFile.dispose(); renameItem.dispose(); deleteItem.dispose(); monaco.editor.getModels().forEach((model) => model.dispose()); }; }, [editor]); // Auto save useEffect(() => { if (!editor) return; let timeoutId: NodeJS.Timeout; const { dispose } = editor.onDidChangeModelContent(() => { timeoutId && clearTimeout(timeoutId); timeoutId = setTimeout(async () => { if (!PgExplorer.currentFilePath) return; const args: [string, string] = [ PgExplorer.currentFilePath, editor.getValue(), ]; // Save to state PgExplorer.saveFileToState(...args); // Saving to state is enough if it's a temporary project if (PgExplorer.isTemporary) return; // Save to `indexedDB` try { await PgExplorer.fs.writeFile(...args); } catch (e: any) { console.log( `Error saving file ${PgExplorer.currentFilePath}. ${e.message}` ); } }, 500); }); return () => { clearTimeout(timeoutId); dispose(); }; }, [editor]); // Editor custom events useEffect(() => { if (!editor) return; const handleFocus = () => { if (!editor.hasTextFocus()) editor.focus(); }; document.addEventListener(EventName.EDITOR_FOCUS, handleFocus); return () => { document.removeEventListener(EventName.EDITOR_FOCUS, handleFocus); }; }, [editor]); // Format event useSendAndReceiveCustomEvent( EventName.EDITOR_FORMAT, async (ev?: { lang: LanguageName; fromTerminal: boolean }) => { if (!editor) return; const lang = PgExplorer.getCurrentFileLanguage(); if (!lang) return; let formatRust; const isCurrentFileRust = lang.name === "Rust"; if (isCurrentFileRust) { formatRust = async () => { const currentContent = editor.getValue(); const model = editor.getModel(); if (!model) return; const { rustfmt } = await PgPackage.import("rustfmt"); let result; try { result = rustfmt(currentContent); } catch (e: any) { result = { error: () => e.message }; } if (result.error()) { PgTerminal.log(PgTerminal.error("Unable to format the file.")); return; } const pos = editor.getPosition(); if (!pos) return; let cursorOffset = model.getOffsetAt(pos); const currentLine = model.getLineContent(pos.lineNumber); const beforeLine = model.getLineContent(pos.lineNumber - 1); const afterLine = pos.lineNumber === model.getLineCount() ? "" : model.getLineContent(pos.lineNumber + 1); const searchText = [beforeLine, currentLine, afterLine].reduce( (acc, cur) => acc + cur + "\n", "" ); const formattedCode = result.code!(); const searchIndex = formattedCode.indexOf(searchText); if (searchIndex !== -1) { // Check if there are multiple instances of the same searchText const nextSearchIndex = formattedCode.indexOf( searchText, searchIndex + searchText.length ); if (nextSearchIndex === -1) { cursorOffset = searchIndex + cursorOffset - model.getOffsetAt({ lineNumber: pos.lineNumber - 1, column: 0, }); } } const endLineNumber = model.getLineCount(); const endColumn = model.getLineContent(endLineNumber).length + 1; // Execute edits pushes the changes to the undo stack editor.executeEdits(null, [ { text: formattedCode, range: { startLineNumber: 1, endLineNumber, startColumn: 0, endColumn, }, }, ]); const resultPos = model.getPositionAt(cursorOffset); editor.setPosition(resultPos); if (ev?.fromTerminal) { PgTerminal.log(PgTerminal.success("Format successful.")); } }; } const isCurrentFileJsLike = PgExplorer.isCurrentFileJsLike(); let formatJSTS; if (isCurrentFileJsLike) { formatJSTS = async () => { const currentContent = editor.getValue(); const model = editor.getModel(); if (!model) return; const { formatWithCursor } = await import("prettier/standalone"); const { default: parserTypescript } = await import( "prettier/parser-typescript" ); const pos = editor.getPosition() ?? { lineNumber: 1, column: 0 }; const result = formatWithCursor(currentContent, { parser: "typescript", plugins: [parserTypescript], cursorOffset: model.getOffsetAt(pos), }); const endLineNumber = model.getLineCount(); const endColumn = model.getLineContent(endLineNumber).length + 1; // Execute edits pushes the changes to the undo stack editor.executeEdits(null, [ { text: result.formatted, range: { startLineNumber: 1, endLineNumber, startColumn: 0, endColumn, }, }, ]); const resultPos = model.getPositionAt(result.cursorOffset); editor.setPosition(resultPos); if (ev?.fromTerminal) { PgTerminal.log(PgTerminal.success("Format successful.")); } }; } const isCurrentFileJSON = lang.name === "JSON"; let formatJSON; if (isCurrentFileJSON) { formatJSON = () => { const model = editor.getModel(); if (!model) return; const pos = editor.getPosition(); if (!pos) return; let cursorOffset = model.getOffsetAt(pos); const currentLine = model.getLineContent(pos.lineNumber); const beforeLine = model.getLineContent(pos.lineNumber - 1); const afterLine = model.getLineContent(pos.lineNumber + 1); const searchText = [beforeLine, currentLine, afterLine].reduce( (acc, cur) => acc + cur + "\n", "" ); const formattedCode = PgCommon.prettyJSON( JSON.parse(editor.getValue()) ); const searchIndex = formattedCode.indexOf(searchText); if (searchIndex !== -1) { // Check if there are multiple instances of the same searchText const nextSearchIndex = formattedCode.indexOf( searchText, searchIndex + searchText.length ); if (nextSearchIndex === -1) { cursorOffset = searchIndex + cursorOffset - model.getOffsetAt({ lineNumber: pos.lineNumber - 1, column: 0, }); } } const endLineNumber = model.getLineCount(); const endColumn = model.getLineContent(endLineNumber).length + 1; // Execute edits pushes the changes to the undo stack editor.executeEdits(null, [ { text: formattedCode, range: { startLineNumber: 1, endLineNumber, startColumn: 0, endColumn, }, }, ]); const resultPos = model.getPositionAt(cursorOffset); editor.setPosition(resultPos); }; } // From keybind if (!ev) { if (isCurrentFileRust) { formatRust && (await formatRust()); } else if (isCurrentFileJsLike) { formatJSTS && (await formatJSTS()); } else if (isCurrentFileJSON) { formatJSON && formatJSON(); } return; } // From terminal switch (ev.lang) { case "Rust": { if (!isCurrentFileRust) { PgTerminal.log( PgTerminal.warning("Current file is not a Rust file.") ); return; } formatRust && (await formatRust()); break; } case "TypeScript": { if (!isCurrentFileJsLike) { PgTerminal.log( PgTerminal.warning("Current file is not a JS/TS file.") ); return; } formatJSTS && (await formatJSTS()); } } }, [editor] ); // Format on keybind useKeybind( "Ctrl+S", () => { if (editor?.hasTextFocus()) { PgTerminal.process(async () => { await PgCommon.sendAndReceiveCustomEvent(EventName.EDITOR_FORMAT); }); } }, [editor] ); // Initialize language extensions useEffect(() => { const disposables = monaco.languages.getLanguages().map((language) => { return monaco.languages.onLanguage(language.id, async () => { try { const { init } = await import(`./languages/${language.id}/init`); await init(); } catch (e: any) { if (!e.message?.includes("Cannot find module")) { throw new Error(`Failed to initialize '${language.id}': ${e}`); } } }); }); return () => disposables.forEach(({ dispose }) => dispose()); }, []); // Update program id useEffect(() => { if (!editor) return; const getProgramIdStartAndEndIndex = ( content: string, isPython: boolean ) => { const findText = isPython ? "declare_id" : "declare_id!"; const findTextIndex = content.indexOf(findText); if (!content || !findTextIndex || findTextIndex === -1) return; const quoteStartIndex = findTextIndex + findText.length + 1; const quoteChar = content[quoteStartIndex]; const quoteEndIndex = content.indexOf(quoteChar, quoteStartIndex + 1); return [quoteStartIndex, quoteEndIndex]; }; const updateId = async () => { const programPkStr = PgProgramInfo.getPkStr(); if (!programPkStr) return; // Update in editor const currentLang = PgExplorer.getCurrentFileLanguage(); const isRust = currentLang?.name === "Rust"; const isPython = currentLang?.name === "Python"; if (!isRust && !isPython) return; const editorContent = editor.getValue(); const indices = getProgramIdStartAndEndIndex(editorContent, isPython); if (!indices) return; const [quoteStartIndex, quoteEndIndex] = indices; const model = editor.getModel(); if (!model) return; const startPos = model.getPositionAt(quoteStartIndex + 1); const endPos = model.getPositionAt(quoteEndIndex); const range = monaco.Range.fromPositions(startPos, endPos); try { editor.executeEdits(null, [{ range, text: programPkStr }]); } catch (e: any) { console.log("Program ID update error:", e.message); } }; const { dispose } = PgCommon.batchChanges(updateId, [ PgCommand.build.onDidRunStart, PgProgramInfo.onDidChangePk, ]); return dispose; }, [editor]); return ( <SpinnerWithBg loading={!isThemeSet} size="2rem"> <Wrapper ref={monacoRef} /> </SpinnerWithBg> ); }; const Wrapper = styled.div` width: 100%; height: 100%; /** Inlay hints */ & span[class^="dyn-rule"], span[class*=" dyn-rule"] { font-size: 12px; } `; export default Monaco;
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/index.ts
export { default } from "./Monaco";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/init.ts
import * as monaco from "monaco-editor"; import { loadWASM, createOnigScanner, createOnigString, } from "vscode-oniguruma"; import { INITIAL, Registry, parseRawGrammar, StateStack, IRawTheme, } from "vscode-textmate"; import { RequiredKey, PgExplorer, PgCommon } from "../../../../utils/pg"; // Remove defaults https://github.com/Microsoft/monaco-editor/issues/252#issuecomment-482786867 monaco.languages.getLanguages().forEach((lang) => { // @ts-ignore lang.loader = () => ({ then: () => {} }); }); // FIXME: Builtin languages e.g. JSON override existing TextMate tokens. // https://github.com/Microsoft/monaco-editor/issues/884 /** Language grammar and configuration cache based on theme name */ const cache: { themeName: string | null; languageIds: string[]; } = { themeName: null, languageIds: [], }; /** * Initialize language grammars and configurations. * * Initialization must happen before creating the editor. * * @param theme TextMate theme */ export const initLanguages = async (theme: RequiredKey<IRawTheme, "name">) => { // Load oniguruma const resp = await fetch( require("vscode-oniguruma/release/onig.wasm?resource") ); await loadWASM(resp); const registry = new Registry({ onigLib: Promise.resolve({ createOnigScanner, createOnigString, }), loadGrammar: async (scopeName: string) => { const grammar = await PgCommon.fetchJSON( `/grammars/${scopeName}.tmLanguage.json` ); // `registry.loadGrammarWithConfiguration` expects `scopeName` as the // first argument but we provide language id instead because grammars // exist in `/grammars/<LANGUAGE_ID>.tmLanguage.json`. This format allows // sharing grammars in `monaco` and `shiki`. grammar.scopeName = scopeName; return parseRawGrammar(JSON.stringify(grammar), "grammar.json"); }, theme, }); const loadGrammarAndConfiguration = async (languageId: string) => { if (cache.themeName !== theme.name) { cache.themeName = theme.name; cache.languageIds = []; // Set color map monaco.languages.setColorMap(registry.getColorMap()); } if (cache.languageIds.includes(languageId)) return; // Using `loadGrammar` cause `onEnterRules` to not be respected. Using // `loadGrammarWithConfiguration` solves the problem. const grammar = await registry.loadGrammarWithConfiguration( languageId, monaco.languages.getEncodedLanguageId(languageId), { // Otherwise bracket colorization doesn't work balancedBracketSelectors: ["*"], } ); if (!grammar) return; // Set tokens monaco.languages.setTokensProvider(languageId, { getInitialState: () => INITIAL, tokenizeEncoded: (line: string, state: monaco.languages.IState) => { const { tokens, ruleStack: endState } = grammar.tokenizeLine2( line, state as StateStack ); return { tokens, endState }; }, }); // Set configuration const configuration = await import(`./${languageId}/configuration.json`); monaco.languages.setLanguageConfiguration( languageId, parseConfiguration(configuration) ); // Cache cache.languageIds.push(languageId); }; return PgExplorer.onDidOpenFile(async (file) => { if (!file) return; const extension = file.path.split(".").at(-1)!; const lang = monaco.languages.getLanguages().find((lang) => { return lang.extensions?.map((ext) => ext.slice(1)).includes(extension); }); if (lang) await loadGrammarAndConfiguration(lang.id); }); }; /** * Parse VSCode language configuration file to Monaco editor. * * @param configuration language configuration file * @returns the configuration in format that Monaco expects */ const parseConfiguration = ( configuration: any ): monaco.languages.LanguageConfiguration => { // Clone because properties are read-only configuration = { ...configuration }; /** Recursively parse object values to `RegExp` when necessary */ const recursivelyParseRegex = (obj: Record<string, any>) => { for (const key in obj) { const value = obj[key]; // Check whether the key is a string if (typeof value === "string") { if ( !( value.startsWith("^") || value.endsWith("$") || value.includes("\\\\") ) ) { continue; } obj[key] = new RegExp(value); } if (typeof value === "object" && value !== null) { // Check for "pattern" property const pattern = value.pattern; if (pattern) obj[key] = new RegExp(pattern); else recursivelyParseRegex(obj[key]); } } }; recursivelyParseRegex(configuration); // `onEnterRules` is not mapped properly configuration.onEnterRules &&= configuration.onEnterRules.map((rule: any) => { switch (rule.action.indent) { case "none": rule.action.indentAction = monaco.languages.IndentAction.None; break; case "indent": rule.action.indentAction = monaco.languages.IndentAction.Indent; break; case "indentOutdent": rule.action.indentAction = monaco.languages.IndentAction.IndentOutdent; break; case "outdent": rule.action.indentAction = monaco.languages.IndentAction.Outdent; } rule.beforeText = convertToRegex(rule.beforeText); rule.afterText &&= convertToRegex(rule.afterText); rule.previousLineText &&= convertToRegex(rule.previousLineText); return rule; }); return configuration; }; /** * Convert the given field to Regex if needed. * * @param field field to convert * @returns converted `RegExp` */ const convertToRegex = (field: string | RegExp) => { return typeof field === "string" ? new RegExp(field) : field; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/common.ts
import * as monaco from "monaco-editor"; import { Arrayable, Disposable, PgCommon, SyncOrAsync, } from "../../../../utils/pg"; /** * Common import implementation based on model and model's content change. * * @param update update method * @param language language(s) to support * @returns a disposable to dispose all events */ export const importTypes = async ( update: (model: monaco.editor.IModel) => SyncOrAsync<void>, language: Arrayable<string> ): Promise<Disposable> => { language = PgCommon.toArray(language); const changeModels: monaco.IDisposable[] = []; const updateDisposables = new Map<monaco.Uri, monaco.IDisposable>(); // Don't dispose `onDidCreateEditor` because it only gets initialized once await PgCommon.executeInitial( monaco.editor.onDidCreateEditor, async (editor) => { changeModels.push( await PgCommon.executeInitial(editor.onDidChangeModel, async () => { const model = editor.getModel(); if (!model) return; // Check language const isValidLanguage = language.includes(model.getLanguageId()); if (!isValidLanguage) return; const updateModel = () => update(model); await updateModel(); // Check cache if (!updateDisposables.has(model.uri)) { updateDisposables.set( model.uri, model.onDidChangeContent(updateModel) ); } }) ); }, monaco.editor.getEditors()[0] ); return { dispose: () => { changeModels.forEach(({ dispose }) => dispose()); updateDisposables.forEach(({ dispose }) => dispose()); }, }; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/index.ts
export { initLanguages } from "./init";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/python/configuration.json
{ "comments": { "lineComment": "#", "blockComment": ["\"\"\"", "\"\"\""] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}" }, { "open": "[", "close": "]" }, { "open": "(", "close": ")" }, { "open": "\"", "close": "\"", "notIn": ["string"] }, { "open": "r\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "R\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "u\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "U\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "f\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "F\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "b\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "B\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "'", "close": "'", "notIn": ["string", "comment"] }, { "open": "r'", "close": "'", "notIn": ["string", "comment"] }, { "open": "R'", "close": "'", "notIn": ["string", "comment"] }, { "open": "u'", "close": "'", "notIn": ["string", "comment"] }, { "open": "U'", "close": "'", "notIn": ["string", "comment"] }, { "open": "f'", "close": "'", "notIn": ["string", "comment"] }, { "open": "F'", "close": "'", "notIn": ["string", "comment"] }, { "open": "b'", "close": "'", "notIn": ["string", "comment"] }, { "open": "B'", "close": "'", "notIn": ["string", "comment"] }, { "open": "`", "close": "`", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"], ["`", "`"] ], "folding": { "offSide": true, "markers": { "start": "^\\s*#\\s*region\\b", "end": "^\\s*#\\s*endregion\\b" } }, "onEnterRules": [ { "beforeText": "^\\s*(?:def|class|for|if|elif|else|while|try|with|finally|except|async).*?:\\s*$", "action": { "indent": "indent" } } ] }
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/init.ts
export const init = async () => { const { initDeclarations } = await import("./declarations"); return await initDeclarations(); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/configuration.json
{ "comments": { "lineComment": "//", "blockComment": ["/*", "*/"] }, "brackets": [ ["${", "}"], ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}" }, { "open": "[", "close": "]" }, { "open": "(", "close": ")" }, { "open": "'", "close": "'", "notIn": ["string", "comment"] }, { "open": "\"", "close": "\"", "notIn": ["string"] }, { "open": "`", "close": "`", "notIn": ["string", "comment"] }, { "open": "/**", "close": " */", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["'", "'"], ["\"", "\""], ["`", "`"], ["<", ">"] ], "colorizedBracketPairs": [ ["(", ")"], ["[", "]"], ["{", "}"] ], "autoCloseBefore": ";:.,=}])>` \n\t", "folding": { "markers": { "start": "^\\s*//\\s*#?region\\b", "end": "^\\s*//\\s*#?endregion\\b" } }, "wordPattern": { "pattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\@\\~\\!\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>/\\?\\s]+)" }, "indentationRules": { "decreaseIndentPattern": { "pattern": "^((?!.*?/\\*).*\\*/)?\\s*[\\}\\]].*$" }, "increaseIndentPattern": { "pattern": "^((?!//).)*(\\{([^}\"'`/]*|(\\t|[ ])*//.*)|\\([^)\"'`/]*|\\[[^\\]\"'`/]*)$" }, "unIndentedLinePattern": { "pattern": "^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$|^(\\t|[ ])*[ ]\\*/\\s*$|^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$" } }, "onEnterRules": [ { "beforeText": { "pattern": "^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$" }, "afterText": { "pattern": "^\\s*\\*/$" }, "action": { "indent": "indentOutdent", "appendText": " * " } }, { "beforeText": { "pattern": "^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$" }, "action": { "indent": "none", "appendText": " * " } }, { "beforeText": { "pattern": "^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$" }, "previousLineText": { "pattern": "(?=^(\\s*(/\\*\\*|\\*)).*)(?=(?!(\\s*\\*/)))" }, "action": { "indent": "none", "appendText": "* " } }, { "beforeText": { "pattern": "^(\\t|[ ])*[ ]\\*/\\s*$" }, "action": { "indent": "none", "removeText": 1 } }, { "beforeText": { "pattern": "^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$" }, "action": { "indent": "none", "removeText": 1 } }, { "beforeText": { "pattern": "^\\s*(\\bcase\\s.+:|\\bdefault:)$" }, "afterText": { "pattern": "^(?!\\s*(\\bcase\\b|\\bdefault\\b))" }, "action": { "indent": "indent" } }, { "previousLineText": "^\\s*(((else ?)?if|for|while)\\s*\\(.*\\)\\s*|else\\s*)$", "beforeText": "^\\s+([^{i\\s]|i(?!f\\b))", "action": { "indent": "outdent" } } ] }
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/declarations.ts
import { declareDisposableTypes } from "./disposable"; import { declareGlobalTypes } from "./global"; import { declareImportableTypes } from "./importable"; import type { Disposable } from "../../../../../../utils/pg"; /** * Initialize type declarations. * * Steps: * 1. Declare global and importable types * 2. Declare disposable types * * @returns a disposable to dispose all events */ export const initDeclarations = async (): Promise<Disposable> => { const [global, importable] = await Promise.all([ declareGlobalTypes(), declareImportableTypes(), ]); const disposable = declareDisposableTypes(); return { dispose: () => { global.dispose(); importable.dispose(); disposable.dispose(); }, }; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/disposable.ts
import * as monaco from "monaco-editor"; import type { Idl } from "@coral-xyz/anchor"; import { declareModule } from "./helper"; import { ClientPackageName, Disposable, PgCommon, PgExplorer, PgProgramInfo, PgWallet, } from "../../../../../../utils/pg"; /** * Declare types that can change based on outside events. * * For example, `pg.wallet` will be `never` when the wallet is not connected. * * @returns a disposable to dispose all events */ export const declareDisposableTypes = (): Disposable => { addLib("default", require("./raw/pg.raw.d.ts")); // Program id const programIdChange = PgProgramInfo.onDidChangePk((programId) => { addLib( "program-id", `/** Your program public key from playground */\nconst PROGRAM_ID: ${ programId ? "web3.PublicKey" : "never" };` ); }); // Playground wallet const PG_WALLET_TYPE = "PgWallet"; const walletChange = PgWallet.onDidChangeCurrent((wallet) => { const walletType = wallet ? wallet.isPg ? PG_WALLET_TYPE : getWalletTypeName(wallet.name) : "never"; addLib( "wallet", ` ${ wallet ? `/** * Current connected wallet. * * NOTE: You can toggle connection with \`connect\` command. */` : `/** You are not connected. Use \`connect\` command to connect. */` } const wallet: ${walletType}; ` ); }); // Wallets const accountsChange = PgCommon.batchChanges(() => { // Get Playground Wallet const pgWalletsType = PgWallet.accounts .map((acc) => PgCommon.toCamelCase(acc.name)) .reduce((acc, cur, i) => { if (i === 0) return `"${cur}"`; return acc + ` | "${cur}"`; }, ""); // Get Standard Wallets const standarWalletNames = PgWallet.getConnectedStandardWallets().map( (wallet) => wallet.name ); const standardWalletsTypeDeclarations = standarWalletNames.reduce( (acc, cur) => acc + `interface ${getWalletTypeName(cur)} extends DefaultWallet {}`, "" ); const standardWalletsType = standarWalletNames.reduce( (acc, cur) => acc + `& { ${PgCommon.toCamelCase(cur)}: ${getWalletTypeName(cur)} }`, "" ); const walletsType = `{ [K in ${pgWalletsType}]: ${PG_WALLET_TYPE} } ${standardWalletsType}`; addLib( "wallets", ` ${standardWalletsTypeDeclarations} type Wallets = ${walletsType}; /** All available wallets by their camelCase names */ const wallets: ${PgWallet.current ? "Wallets" : "never"}; ` ); }, [PgWallet.onDidChangeAccounts, PgWallet.onDidChangeCurrent]); // Anchor program let programDisposables: monaco.IDisposable[] = []; const idlChange = PgProgramInfo.onDidChangeIdl((idl) => { if (!idl) { // Dispose the program types if there is no IDL otherwise the types will // leak between workspaces if the previous workspace has an IDL but the // current doesn't. programDisposables.forEach((disposable) => disposable.dispose()); programDisposables = []; return; } const convertedIdl = JSON.stringify(convertIdl(idl)); // Program const programType = `Program<${convertedIdl}>`; programDisposables.push( addLib( "program", `/** Your Anchor program */ const program: anchor.${programType};` ) ); // target/types const idlTypeName = PgCommon.toPascalFromSnake(idl.name); programDisposables.push( addModel( "target/types", `export type ${idlTypeName} = ${convertedIdl}; export const IDL: ${idlTypeName} = ${convertedIdl};`, PgExplorer.convertToFullPath(`target/types/${idl.name}.ts`) ) ); // Workspace const getWorkspace = (packageName: ClientPackageName) => { return `import { Program } from "${packageName}"; const workspace: { ${PgCommon.toPascalFromSnake( idl.name )}: ${programType} };`; }; programDisposables.push( addLib( "@coral-xyz/anchor.workspace", declareModule("@coral-xyz/anchor", getWorkspace("@coral-xyz/anchor")) ), addLib( "@project-serum/anchor.workspace", declareModule( "@project-serum/anchor", getWorkspace("@project-serum/anchor") ) ) ); }); return { dispose: () => { programIdChange.dispose(); walletChange.dispose(); accountsChange.dispose(); idlChange.dispose(); }, }; }; /** Disposable types */ type DisposableType = | "default" | "program-id" | "wallet" | "wallets" | "program" | "@coral-xyz/anchor.workspace" | "@project-serum/anchor.workspace" | "target/types"; /** Caching the disposables in order to get rid of the old declarations */ const disposableCache: { [K in DisposableType]?: monaco.IDisposable } = {}; /** * Add declaration file and remove the old one if it exists. * * @param disposableType name to keep track of the disposable in `disposableCache` * @param lib content * @returns a disposable to dispose the library */ const addLib = (disposableType: DisposableType, lib: string) => { disposableCache[disposableType]?.dispose(); disposableCache[disposableType] = monaco.languages.typescript.typescriptDefaults.addExtraLib( lib.includes("declare module") ? lib : declareModule("solana-playground", lib), // `anchor.workspace` is not getting disposed without file path `/disposables/${disposableType}.d.ts` ); return disposableCache[disposableType]!; }; /** * Add model and remove the old one if it exists. * * @param disposableType name to keep track of the disposable in `disposableCache` * @param content code * @param filePath model URI * @returns a disposable to dispose the model */ const addModel = ( disposableType: DisposableType, content: string, filePath: string ) => { disposableCache[disposableType]?.dispose(); disposableCache[disposableType] = monaco.editor.createModel( content, undefined, monaco.Uri.parse(filePath) ); return disposableCache[disposableType]!; }; /** * Convert Anchor IDL's account names into camelCase to be used accuretely for types. * * @param idl Anchor IDL * @returns converted Anchor IDL */ const convertIdl = (idl: Idl) => { if (!idl.accounts) return idl; let newIdl: Idl = { ...idl, accounts: [] }; for (const account of idl.accounts) { newIdl.accounts!.push({ ...account, name: account.name[0].toLowerCase() + account.name.substring(1), }); } return newIdl; }; /** * Get the wallet's type name. * * @param walletName wallet name * @returns wallet's type name */ const getWalletTypeName = (walletName: string) => walletName + "Wallet";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/helper.ts
import * as monaco from "monaco-editor"; import { ClientPackageName, Disposable, PgCommon, TupleFiles, } from "../../../../../../utils/pg"; /** * Some declaration files need to be declared for them to be referenced by other * declaration files. * * @param packageName package name to be referenced in declaration files * @param module contents of the module * @returns module declaration for the given package */ export const declareModule = ( packageName: ClientPackageName, module: string = "" ) => { return `declare module "${packageName}" { ${module} }`; }; /** * Declare a full package(cached). * * @param packageName package name to be referenced in declaration files * @param opts declare options * - `transitive`: Whether the package is a transitive package * @returns a dispose method to dispose all events or `undefined` if the * package has already been declared */ export const declarePackage = async ( packageName: ClientPackageName, opts?: { empty?: boolean; transitive?: boolean } ): Promise<Disposable | undefined> => { if (cache.has(packageName)) return; if (opts?.empty) { return monaco.languages.typescript.typescriptDefaults.addExtraLib( declareModule(packageName) ); } cache.add(packageName); const files: TupleFiles = await PgCommon.fetchJSON( `/packages/${packageName}/types.json` ); const disposables = files.map(([path, content]) => { // Declare module on `index.d.ts` if it's not declared if (files.length === 1 && !content.includes("declare module")) { content = declareModule(packageName, content); } return monaco.languages.typescript.typescriptDefaults.addExtraLib( content, "file:///" + path ); }); if (files.length > 1) { const [oldIndexPath] = files.find(([path]) => { return path.endsWith("old-index.d.ts"); })!; disposables.push( // Renaming exports allows us to export everything monaco.languages.typescript.typescriptDefaults.addExtraLib( declareModule( packageName, `export * from "${oldIndexPath .replace("node_modules/", "") .replace(".d.ts", "")}"` ), "file:///" + oldIndexPath.replace("old-index", "index") ) ); } // Get the transitive dependencies of global and importable packages but do // not continue the recursion to get the transitive dependencies of the // transitive dependencies because that results in excessive amount of // requests without adding much benefit. if (!opts?.transitive) { const deps: ClientPackageName[] = await PgCommon.fetchJSON( `/packages/${packageName}/deps.json` ); const transitiveDisposables = await Promise.all( deps.map((dep) => declarePackage(dep, { transitive: true })) ); disposables.push(...transitiveDisposables.filter(PgCommon.isNonNullish)); } return { dispose: () => { disposables.forEach(({ dispose }) => dispose()); cache.delete(packageName); }, }; }; /** Declared package names cache */ const cache = new Set<ClientPackageName>();
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/importable.ts
import { declarePackage } from "./helper"; import { importTypes } from "../../common"; import type { ClientPackageName, Disposable } from "../../../../../../utils/pg"; /** * Declare importable types in the editor and update them based on file switch * or the current editor model's content change. */ export const declareImportableTypes = () => { return importTypes( (model) => update(model.getValue()), ["javascript", "typescript"] ); }; /** Mapping of package name -> imported */ const cachedTypes: { [K in ClientPackageName]?: true | Disposable; } = {}; /** * Update declared types in the editor(with cache). * * This function declares modules as empty when the package is not used in * the code. This allows autocompletion when importing packages and the type * declarations will only get loaded when the code contains the package name. * * @param code current editor content */ const update = async (code: string) => { await Promise.all( PACKAGES.importable.map(async (packageName) => { const pkg = cachedTypes[packageName]; if (pkg === true) return; if (new RegExp(`("|')${packageName}("|')`, "gm").test(code)) { await declarePackage(packageName); // Dispose the old filler declaration if it exists pkg?.dispose(); // Declaration is final, this package will not get declared again cachedTypes[packageName] = true; } else if (!pkg) { // Declare empty package to give the completion hint that the package // can be imported cachedTypes[packageName] = await declarePackage(packageName, { empty: true, }); } }) ); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/global.ts
import * as monaco from "monaco-editor"; import { declarePackage } from "./helper"; import { Disposable, MergeUnion, PgCommon } from "../../../../../../utils/pg"; /** Global packages */ type GlobalPackages = typeof PACKAGES["global"]; /** Global package name */ type GlobalPackageName = keyof GlobalPackages; /** ESM import style */ type PackageImportStyle = GlobalPackages[GlobalPackageName]; /** * Load typescript declarations in the editor. * * Only the packages specified in this function are loaded by default for * performance reasons. * * This function will only declare the default types once. */ export const declareGlobalTypes = async (): Promise<Disposable> => { const disposables = [ monaco.languages.typescript.typescriptDefaults.addExtraLib( require("./raw/globals.raw.d.ts") ), monaco.languages.typescript.typescriptDefaults.addExtraLib( require("./raw/console.raw.d.ts") ), monaco.languages.typescript.typescriptDefaults.addExtraLib( require("./raw/light-dom.raw.d.ts") ), declareNamespace("solana-playground", { as: "pg" }), ]; await Promise.all( PgCommon.entries(PACKAGES.global).map( async ([packageName, importStyle]) => { const pkg = await declarePackage(packageName); if (pkg) { disposables.push(pkg, declareNamespace(packageName, importStyle)); } } ) ); return { dispose: () => disposables.forEach(({ dispose }) => dispose()) }; }; /** * Declare global namespace. * * @param packageName package name to be referenced in declaration files * @param importStyle import style of the package * @returns a dispose method to dispose all events */ const declareNamespace = ( packageName: GlobalPackageName, importStyle: PackageImportStyle ) => { const style = importStyle as Partial<MergeUnion<PackageImportStyle>>; const name = style.as ?? style.named ?? style.default; const importStyleText = style.as ? `* as ${style.as}` : style.named ? `{ ${style.named} }` : style.default; return monaco.languages.typescript.typescriptDefaults.addExtraLib( `import ${importStyleText} from "${packageName}"; export = ${name}; export as namespace ${name};`, `${name}-ns.d.ts` ); };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/index.ts
export { initDeclarations } from "./declarations";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/raw/light-dom.raw.d.ts
/* eslint-disable @typescript-eslint/no-redeclare */ /** A controller object that allows you to abort one or more DOM requests as and when desired. */ interface AbortController { /** Returns the AbortSignal object associated with this object. */ readonly signal: AbortSignal; /** Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ abort(reason?: any): void; } declare var AbortController: { prototype: AbortController; new(): AbortController; }; interface AbortSignalEventMap { "abort": Event; } /** An event which takes place in the DOM. */ interface Event { /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ readonly bubbles: boolean; /** @deprecated */ cancelBubble: boolean; /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ readonly cancelable: boolean; /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ readonly composed: boolean; /** Returns the object whose event listener's callback is currently being invoked. */ readonly currentTarget: EventTarget | null; /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ readonly defaultPrevented: boolean; /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ readonly eventPhase: number; /** Returns true if event was dispatched by the user agent, and false otherwise. */ readonly isTrusted: boolean; /** @deprecated */ returnValue: boolean; /** @deprecated */ readonly srcElement: EventTarget | null; /** Returns the object to which event is dispatched (its target). */ readonly target: EventTarget | null; /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ readonly timeStamp: DOMHighResTimeStamp; /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ readonly type: string; /** Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. */ composedPath(): EventTarget[]; /** @deprecated */ initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; /** If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. */ preventDefault(): void; /** Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. */ stopImmediatePropagation(): void; /** When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. */ stopPropagation(): void; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; readonly NONE: number; } declare var Event: { prototype: Event; new(type: string, eventInitDict?: EventInit): Event; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; readonly NONE: number; }; /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ interface AbortSignal extends EventTarget { /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ readonly aborted: boolean; onabort: ((this: AbortSignal, ev: Event) => any) | null; readonly reason: any; throwIfAborted(): void; addEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; abort(reason?: any): AbortSignal; timeout(milliseconds: number): AbortSignal; }; /** EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. */ interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. * * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void; /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ dispatchEvent(event: Event): boolean; /** Removes the event listener in target's event listener list with the same type, callback, and options. */ removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; } declare var EventTarget: { prototype: EventTarget; new(): EventTarget; }; interface EventListener { (evt: Event): void; } interface EventListenerObject { handleEvent(object: Event): void; } /** Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */ interface Crypto { /** Available only in secure contexts. */ readonly subtle: SubtleCrypto; getRandomValues<T extends ArrayBufferView | null>(array: T): T; /** Available only in secure contexts. */ randomUUID(): string; } declare var Crypto: { prototype: Crypto; new(): Crypto; }; /** * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. * Available only in secure contexts. */ interface CryptoKey { readonly algorithm: KeyAlgorithm; readonly extractable: boolean; readonly type: KeyType; readonly usages: KeyUsage[]; } declare var CryptoKey: { prototype: CryptoKey; new(): CryptoKey; }; interface CryptoKeyPair { privateKey: CryptoKey; publicKey: CryptoKey; } /** * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). * Available only in secure contexts. */ interface SubtleCrypto { decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>; deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>; deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>; digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>; encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>; exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>; exportKey(format: Exclude<KeyFormat, "jwk">, key: CryptoKey): Promise<ArrayBuffer>; generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKeyPair>; generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>; generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair | CryptoKey>; importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>; importKey(format: Exclude<KeyFormat, "jwk">, keyData: BufferSource, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>; sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>; unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>; verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>; wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise<ArrayBuffer>; } declare var SubtleCrypto: { prototype: SubtleCrypto; new(): SubtleCrypto; }; interface AesCbcParams extends Algorithm { iv: BufferSource; } interface AesCtrParams extends Algorithm { counter: BufferSource; length: number; } interface AesDerivedKeyParams extends Algorithm { length: number; } interface AesGcmParams extends Algorithm { additionalData?: BufferSource; iv: BufferSource; tagLength?: number; } interface AesKeyAlgorithm extends KeyAlgorithm { length: number; } interface AesKeyGenParams extends Algorithm { length: number; } interface Algorithm { name: string; } interface EcKeyAlgorithm extends KeyAlgorithm { namedCurve: NamedCurve; } interface EcKeyGenParams extends Algorithm { namedCurve: NamedCurve; } interface EcKeyImportParams extends Algorithm { namedCurve: NamedCurve; } interface EcdhKeyDeriveParams extends Algorithm { public: CryptoKey; } interface EcdsaParams extends Algorithm { hash: HashAlgorithmIdentifier; } interface HkdfParams extends Algorithm { hash: HashAlgorithmIdentifier; info: BufferSource; salt: BufferSource; } interface HmacImportParams extends Algorithm { hash: HashAlgorithmIdentifier; length?: number; } interface HmacKeyAlgorithm extends KeyAlgorithm { hash: KeyAlgorithm; length: number; } interface HmacKeyGenParams extends Algorithm { hash: HashAlgorithmIdentifier; length?: number; } interface RsaHashedImportParams extends Algorithm { hash: HashAlgorithmIdentifier; } interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { hash: KeyAlgorithm; } interface RsaHashedKeyGenParams extends RsaKeyGenParams { hash: HashAlgorithmIdentifier; } interface RsaKeyAlgorithm extends KeyAlgorithm { modulusLength: number; publicExponent: BigInteger; } interface RsaKeyGenParams extends Algorithm { modulusLength: number; publicExponent: BigInteger; } interface RsaOaepParams extends Algorithm { label?: BufferSource; } interface RsaOtherPrimesInfo { d?: string; r?: string; t?: string; } interface RsaPssParams extends Algorithm { saltLength: number; } interface Pbkdf2Params extends Algorithm { hash: HashAlgorithmIdentifier; iterations: number; salt: BufferSource; } interface JsonWebKey { alg?: string; crv?: string; d?: string; dp?: string; dq?: string; e?: string; ext?: boolean; k?: string; key_ops?: string[]; kty?: string; n?: string; oth?: RsaOtherPrimesInfo[]; p?: string; q?: string; qi?: string; use?: string; x?: string; y?: string; } interface KeyAlgorithm { name: string; } type AlgorithmIdentifier = Algorithm | string; type BigInteger = Uint8Array; type BufferSource = ArrayBufferView | ArrayBuffer; type EventListenerOrEventListenerObject = EventListener | EventListenerObject; type HashAlgorithmIdentifier = AlgorithmIdentifier; type NamedCurve = string; type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; type KeyType = "private" | "public" | "secret"; type KeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/raw/pg.raw.d.ts
declare module "solana-playground" { import * as web3 from "@solana/web3.js"; interface DefaultWallet { /** Public key of the wallet */ publicKey: web3.PublicKey; /** Sign the transaction with the wallet */ signTransaction<T extends web3.Transaction | web3.VersionedTransaction>( tx: T ): Promise<T>; /** Sign all transactions with the wallet */ signAllTransactions<T extends web3.Transaction | web3.VersionedTransaction>( txs: T[] ): Promise<T[]>; /** Sign a message with the wallet */ signMessage(message: Uint8Array): Promise<Uint8Array>; } interface PgWallet extends DefaultWallet { /** Keypair of the Playground Wallet */ keypair: web3.Keypair; } /** Ready to be used connection object */ const connection: web3.Connection; }
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/raw/console.raw.d.ts
declare global { interface Console { /** * Prints to `stderr` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). * * ```js * const code = 5; * console.error('error #%d', code); * // Prints: error #5, to stderr * console.error('error', code); * // Prints: error 5, to stderr * ``` * * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string * values are concatenated. See `util.format()` for more information. * @since v0.1.100 */ error(message?: any, ...optionalParams: any[]): void; /** * Prints to `stdout` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). * * ```js * const count = 5; * console.info('count: %d', count); * // Prints: count: 5, to stdout * console.info('count:', count); * // Prints: count: 5, to stdout * ``` * * See `util.format()` for more information. * @since v0.1.100 */ info(message?: any, ...optionalParams: any[]): void; /** * Prints to `stdout` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). * * ```js * const count = 5; * console.log('count: %d', count); * // Prints: count: 5, to stdout * console.log('count:', count); * // Prints: count: 5, to stdout * ``` * * See `util.format()` for more information. * @since v0.1.100 */ log(message?: any, ...optionalParams: any[]): void; /** * Prints to `stderr` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). * * ```js * const code = 5; * console.warn('warn #%d', code); * // Prints: warn #5, to stderr * console.warn('warn', code); * // Prints: warn 5, to stderr * ``` * * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string * values are concatenated. See `util.format()` for more information. * @since v0.1.100 */ warn(message?: any, ...optionalParams: any[]): void; } /** * The `console` module provides a simple debugging console that is similar to the * JavaScript console mechanism provided by web browsers. * * The module exports two specific components: * * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently * asynchronous like all other Node.js streams. See the `note on process I/O` for * more information. * * Example using the global `console`: * * ```js * console.log('hello world'); * // Prints: hello world, to stdout * console.log('hello %s', 'world'); * // Prints: hello world, to stdout * console.error(new Error('Whoops, something bad happened')); * // Prints error message and stack trace to stderr: * // Error: Whoops, something bad happened * // at [eval]:5:15 * // at Script.runInThisContext (node:vm:132:18) * // at Object.runInThisContext (node:vm:309:38) * // at node:internal/process/execution:77:19 * // at [eval]-wrapper:6:22 * // at evalScript (node:internal/process/execution:76:60) * // at node:internal/main/eval_string:23:3 * * const name = 'Will Robinson'; * console.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to stderr * ``` * * Example using the `Console` class: * * ```js * const out = getStreamSomehow(); * const err = getStreamSomehow(); * const myConsole = new console.Console(out, err); * * myConsole.log('hello world'); * // Prints: hello world, to out * myConsole.log('hello %s', 'world'); * // Prints: hello world, to out * myConsole.error(new Error('Whoops, something bad happened')); * // Prints: [Error: Whoops, something bad happened], to err * * const name = 'Will Robinson'; * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) */ namespace console {} var console: Console; } export {};
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/typescript/declarations/raw/globals.raw.d.ts
declare global { /** * @param ms amount of time to sleep in miliseconds * @returns a promise that will resolve after specified ms */ function sleep(ms?: number): Promise<void>; } export {};
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust/init.ts
import { initRustAnalyzer } from "./rust-analyzer"; export const init = () => initRustAnalyzer();
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust/configuration.json
{ "comments": { "lineComment": "//", "blockComment": ["/*", "*/"] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "colorizedBracketPairs": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}" }, { "open": "[", "close": "]" }, { "open": "(", "close": ")" }, { "open": "\"", "close": "\"", "notIn": ["string"] }, { "open": "/*", "close": " */" } ], "autoCloseBefore": ";:.,=}])> \n\t", "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["<", ">"], ["\"", "\""], ["'", "'"] ], "indentationRules": { "increaseIndentPattern": "^.*\\{[^}\"']*$|^.*\\([^\\)\"']*$", "decreaseIndentPattern": "^\\s*(\\s*\\/[*].*[*]\\/\\s*)*[})]" }, "folding": { "markers": { "start": "^\\s*// region:\\b", "end": "^\\s*// endregion\\b" } } }
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust/rust-analyzer/index.ts
export { initRustAnalyzer } from "./rust-analyzer";
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust/rust-analyzer/rust-analyzer.ts
// @ts-nocheck import * as monaco from "monaco-editor"; import type { WorldState } from "@solana-playground/rust-analyzer"; import { importTypes } from "../../common"; import { AsyncMethods, Disposable, PgCommon, PgExplorer, } from "../../../../../../utils/pg"; /** Monaco language id for Rust */ const LANGUAGE_ID = "rust"; /** * Cached crate names for Rust Analyzer. * * - `full`: Crate has been fully loaded. * - `empty`: Crate has been loaded with no content to give intellisense for the crate name. * Full crate will be loaded when `crate_name::*` is used in the model content. */ const cachedNames: Map<string, "full" | "empty"> = new Map(); /** Rust Analyzer world state */ let state: AsyncMethods<WorldState>; /** * Initialize Rust Analyzer WASM. * * Steps: * 1. Create a worker thread * 2. Initialize Rust Analyzer with default crates * 3. Load the current workspace in Rust Analyzer * 4. Load the necessary crates and set diagnostics * * @returns a disposable to dispose all events */ export const initRustAnalyzer = async (): Promise<Disposable> => { // Creating thread pool with `wasm-bindgen-rayon` sometimes hangs forever for // unknown reasons. Retry until success in order to mitigate this problem. // The try interval should take into account the initial download time of the // Rust Analyzer WASM files(~9MB) on slower connections. state = await PgCommon.tryUntilSuccess(createWorker, 10000); // Initialize and load the default crates await state.loadDefaultCrates( ...(await Promise.all([ PgCommon.fetchText("/crates/core.rs"), PgCommon.fetchText("/crates/alloc.rs"), PgCommon.fetchText("/crates/std.rs"), ])) ); const { dispose: disposeUpdateCurrentCrate } = await PgCommon.executeInitial( (cb) => { // Both `onDidInit` and `onDidSwitchWorkspace` is required to catch all // cases in which the current crate needs to be updated return PgCommon.batchChanges(cb, [ PgExplorer.onDidInit, PgExplorer.onDidSwitchWorkspace, ]); }, async () => { // Return early if `lib.rs` file doesn't exist const file = PgExplorer.getFile("src/lib.rs"); if (!file) return; // Load crate await state.setLocalCrateName( PgCommon.toSnakeCase(PgExplorer.currentWorkspaceName ?? "solpg") ); // Load files await loadLocalFiles(); // Update model const model = monaco.editor.getEditors()[0]?.getModel(); if (model) await update(model); } ); // Update local files when necessary const { dispose: disposeLoadLocalFiles } = PgCommon.batchChanges( loadLocalFiles, [ PgExplorer.onDidCreateItem, PgExplorer.onDidDeleteItem, PgExplorer.onDidRenameItem, ] ); // Import crates when necessary const { dispose: disposeImportTypes } = await importTypes( update, LANGUAGE_ID ); // Register providers at the end in order to avoid out of bound errors due to // a possible mismatch between the LSP and the client files before initialization const { dispose: disposeProviders } = registerProviders(); return { dispose: () => { disposeUpdateCurrentCrate(); disposeLoadLocalFiles(); disposeImportTypes(); disposeProviders(); }, }; }; /** Create Rust Analyzer web worker. */ const createWorker = () => { const worker = new Worker(new URL("./worker.ts", import.meta.url)); const pendingResolve = {}; let id = 1; const callWorker = async (method, ...args) => { return new Promise((res) => { pendingResolve[id] = res; worker.postMessage({ method, args, id }); id += 1; }); }; const proxyHandler = { get: (target, prop, receiver) => { if (prop === "then") return Reflect.get(target, prop, receiver); return async (...args) => callWorker(prop, ...args); }, }; let resolve; worker.onmessage = (ev) => { if (ev.data.id === "ra-worker-ready") { resolve(new Proxy({}, proxyHandler)); return; } const pending = pendingResolve[ev.data.id]; if (pending) { pending(ev.data.result); delete pendingResolve[ev.data.id]; } }; return new Promise((res) => { resolve = res; }); }; /** Load all local Rust files in the workspace. */ const loadLocalFiles = async () => { const files = Object.keys(PgExplorer.files) .filter((path) => path.endsWith(".rs")) .map((path) => [path, PgExplorer.getFileContent(path)]); await state.loadLocalFiles(files); }; /** * Jobs: * - Load crates when necessary based on the model content * - Set model markers for diagnostics * * @param model monaco editor model */ const update = async (model: monaco.editor.IModel) => { const crateImportPromises = CRATES.importable .map((crate) => { const status = cachedNames.get(crate); if (status === "full") return null; if (new RegExp(`${crate}::`, "gm").test(model.getValue())) { return loadDependency(crate); } else if (status !== "empty") { return loadDependency(crate, { empty: true }); } else { return null; } }) .filter(PgCommon.isNonNullish); if (crateImportPromises.length) { await Promise.all(crateImportPromises); } const { diagnostics } = await state.update(model.uri.path, model.getValue()); monaco.editor.setModelMarkers(model, LANGUAGE_ID, diagnostics); }; /** * Load crate and its dependencies(if any) recursively. * * @param name crate name(snake_case) * @param opts load options * - `empty`: Load the dependency with no content * - `transitive`: Load the dependency as transitive */ const loadDependency = async ( name: string, opts?: { empty?: boolean; transitive?: boolean } ) => { // Check if the crate is already loaded if (cachedNames.get(name) === "full") return; // Load empty crate if (opts?.empty) { await state.loadDependency(name); cachedNames.set(name, "empty"); return; } // Load full crate const [code, manifest] = await Promise.all([ PgCommon.fetchText(`/crates/${name}.rs`), PgCommon.fetchText(`/crates/${name}.toml`), ]); const neededCrates: string[] = await state.loadDependency( name, code, manifest, !!opts?.transitive ); cachedNames.set(name, "full"); const crateImportPromises = neededCrates .map((crate) => { if (CRATES.importable.includes(crate)) { return loadDependency(crate); } else if (CRATES.transitive.includes(crate)) { return loadDependency(crate, { transitive: true }); } else { return null; } }) .filter(PgCommon.isNonNullish); if (crateImportPromises.length) { await Promise.all(crateImportPromises); } }; /** * Register editor providers. * * @returns a disposable to remove all registered providers */ const registerProviders = (): Disposable => { const disposables = [ monaco.languages.registerHoverProvider(LANGUAGE_ID, { provideHover: async (_, pos) => { return await state.hover(pos.lineNumber, pos.column); }, }), monaco.languages.registerCodeLensProvider(LANGUAGE_ID, { provideCodeLenses: async (model) => { const codeLenses = await state.codeLenses(); return { lenses: codeLenses.map(({ range, command }) => { const position = { column: range.startColumn, lineNumber: range.startLineNumber, }; const references = command.positions.map((pos) => ({ range: pos, uri: model.uri, })); return { range, command: { id: command.id, title: command.title, arguments: [model.uri, position, references], }, }; }), dispose: () => {}, }; }, }), monaco.languages.registerReferenceProvider(LANGUAGE_ID, { provideReferences: async (model, pos, { includeDeclaration }) => { const references = await state.references( pos.lineNumber, pos.column, includeDeclaration ); if (references) { return references.map(({ range }) => ({ uri: model.uri, range })); } }, }), monaco.languages.registerInlayHintsProvider(LANGUAGE_ID, { provideInlayHints: async () => { const hints = await state.inlayHints(); return { hints: hints.map((hint) => { switch (hint.hintType) { case 1: return { kind: monaco.languages.InlayHintKind.Type, position: { column: hint.range.endColumn, lineNumber: hint.range.endLineNumber, }, label: `: ${hint.label}`, }; case 2: return { kind: monaco.languages.InlayHintKind.Parameter, position: { column: hint.range.startColumn, lineNumber: hint.range.startLineNumber, }, label: `${hint.label}: `, paddingRight: true, }; default: throw new Error("Unknown hint type:", hint.hintType); } }), dispose: () => {}, }; }, }), monaco.languages.registerDocumentHighlightProvider(LANGUAGE_ID, { provideDocumentHighlights: async (_, pos) => { return await state.references(pos.lineNumber, pos.column, true); }, }), monaco.languages.registerRenameProvider(LANGUAGE_ID, { provideRenameEdits: async (model, pos, newName) => { const edits = await state.rename(pos.lineNumber, pos.column, newName); if (edits) { return { edits: edits.map((edit) => ({ resource: model.uri, textEdit: edit, })), }; } }, resolveRenameLocation: async (_, pos) => { return state.prepareRename(pos.lineNumber, pos.column); }, }), monaco.languages.registerCompletionItemProvider(LANGUAGE_ID, { triggerCharacters: [".", ":", "="], provideCompletionItems: async (_, pos) => { const suggestions = await state.completions(pos.lineNumber, pos.column); if (suggestions) return { suggestions }; }, }), monaco.languages.registerSignatureHelpProvider(LANGUAGE_ID, { signatureHelpTriggerCharacters: ["(", ","], provideSignatureHelp: async (_, pos) => { const value = await state.signatureHelp(pos.lineNumber, pos.column); if (value) return { value, dispose: () => {} }; }, }), monaco.languages.registerDefinitionProvider(LANGUAGE_ID, { provideDefinition: async (model, pos) => { const list = await state.definition(pos.lineNumber, pos.column); if (list) return list.map((def) => ({ ...def, uri: model.uri })); }, }), monaco.languages.registerTypeDefinitionProvider(LANGUAGE_ID, { provideTypeDefinition: async (model, pos) => { const list = await state.typeDefinition(pos.lineNumber, pos.column); if (list) return list.map((def) => ({ ...def, uri: model.uri })); }, }), monaco.languages.registerImplementationProvider(LANGUAGE_ID, { provideImplementation: async (model, pos) => { const list = await state.goToImplementation(pos.lineNumber, pos.column); if (list) return list.map((def) => ({ ...def, uri: model.uri })); }, }), monaco.languages.registerDocumentSymbolProvider(LANGUAGE_ID, { provideDocumentSymbols: async () => { return await state.documentSymbols(); }, }), monaco.languages.registerOnTypeFormattingEditProvider(LANGUAGE_ID, { autoFormatTriggerCharacters: [".", "="], provideOnTypeFormattingEdits: async (_, pos, ch) => { return await state.typeFormatting(pos.lineNumber, pos.column, ch); }, }), monaco.languages.registerFoldingRangeProvider(LANGUAGE_ID, { provideFoldingRanges: async () => { return await state.foldingRanges(); }, }), ]; return { dispose: () => disposables.forEach(({ dispose }) => dispose()) }; };
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/rust/rust-analyzer/worker.ts
import init, { initThreadPool, WorldState, } from "@solana-playground/rust-analyzer"; (async () => { await init(); // Thread pool initialization with the given number of threads // (pass `navigator.hardwareConcurrency` if you want to use all cores) // https://github.com/GoogleChromeLabs/wasm-bindgen-rayon await initThreadPool(navigator.hardwareConcurrency); const state = new WorldState(); onmessage = (ev) => { const { method, args, id } = ev.data; const result = (state as any)[method](...args); postMessage({ id, result }); }; postMessage({ id: "ra-worker-ready" }); })();
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/json/configuration.json
{ "comments": { "lineComment": "//", "blockComment": ["/*", "*/"] }, "brackets": [ ["{", "}"], ["[", "]"] ], "autoClosingPairs": [ { "open": "{", "close": "}", "notIn": ["string"] }, { "open": "[", "close": "]", "notIn": ["string"] }, { "open": "(", "close": ")", "notIn": ["string"] }, { "open": "'", "close": "'", "notIn": ["string"] }, { "open": "\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "`", "close": "`", "notIn": ["string", "comment"] } ], "indentationRules": { "increaseIndentPattern": "({+(?=((\\\\.|[^\"\\\\])*\"(\\\\.|[^\"\\\\])*\")*[^\"}]*)$)|(\\[+(?=((\\\\.|[^\"\\\\])*\"(\\\\.|[^\"\\\\])*\")*[^\"\\]]*)$)", "decreaseIndentPattern": "^\\s*[}\\]],?\\s*$" } }
0
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages
solana_public_repos/solana-playground/solana-playground/client/src/components/Editor/Monaco/languages/javascript/configuration.json
{ "comments": { "lineComment": "//", "blockComment": ["/*", "*/"] }, "brackets": [ ["${", "}"], ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ { "open": "{", "close": "}" }, { "open": "[", "close": "]" }, { "open": "(", "close": ")" }, { "open": "'", "close": "'", "notIn": ["string", "comment"] }, { "open": "\"", "close": "\"", "notIn": ["string"] }, { "open": "`", "close": "`", "notIn": ["string", "comment"] }, { "open": "/**", "close": " */", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["'", "'"], ["\"", "\""], ["`", "`"], ["<", ">"] ], "autoCloseBefore": ";:.,=}])>` \n\t", "folding": { "markers": { "start": "^\\s*//\\s*#?region\\b", "end": "^\\s*//\\s*#?endregion\\b" } }, "wordPattern": { "pattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\@\\!\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>/\\?\\s]+)" }, "indentationRules": { "decreaseIndentPattern": { "pattern": "^((?!.*?/\\*).*\\*/)?\\s*[\\}\\]].*$" }, "increaseIndentPattern": { "pattern": "^((?!//).)*(\\{([^}\"'`/]*|(\\t|[ ])*//.*)|\\([^)\"'`/]*|\\[[^\\]\"'`/]*)$" }, "unIndentedLinePattern": { "pattern": "^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$|^(\\t|[ ])*[ ]\\*/\\s*$|^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$" } }, "onEnterRules": [ { "beforeText": { "pattern": "^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$" }, "afterText": { "pattern": "^\\s*\\*/$" }, "action": { "indent": "indentOutdent", "appendText": " * " } }, { "beforeText": { "pattern": "^\\s*/\\*\\*(?!/)([^\\*]|\\*(?!/))*$" }, "action": { "indent": "none", "appendText": " * " } }, { "beforeText": { "pattern": "^(\\t|[ ])*[ ]\\*([ ]([^\\*]|\\*(?!/))*)?$" }, "previousLineText": { "pattern": "(?=^(\\s*(/\\*\\*|\\*)).*)(?=(?!(\\s*\\*/)))" }, "action": { "indent": "none", "appendText": "* " } }, { "beforeText": { "pattern": "^(\\t|[ ])*[ ]\\*/\\s*$" }, "action": { "indent": "none", "removeText": 1 } }, { "beforeText": { "pattern": "^(\\t|[ ])*[ ]\\*[^/]*\\*/\\s*$" }, "action": { "indent": "none", "removeText": 1 } }, { "beforeText": { "pattern": "^\\s*(\\bcase\\s.+:|\\bdefault:)$" }, "afterText": { "pattern": "^(?!\\s*(\\bcase\\b|\\bdefault\\b))" }, "action": { "indent": "indent" } }, { "previousLineText": "^\\s*(((else ?)?if|for|while)\\s*\\(.*\\)\\s*|else\\s*)$", "beforeText": "^\\s+([^{i\\s]|i(?!f\\b))", "action": { "indent": "outdent" } } ] }
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/UploadArea/index.ts
export { default } from "./UploadArea";
0
solana_public_repos/solana-playground/solana-playground/client/src/components
solana_public_repos/solana-playground/solana-playground/client/src/components/UploadArea/UploadArea.tsx
import { FC } from "react"; import styled, { css, DefaultTheme } from "styled-components"; import { DropzoneOptions, DropzoneState, useDropzone } from "react-dropzone"; import Input from "../Input"; import { Checkmark, Upload } from "../Icons"; import { PgCommon, PgTheme } from "../../utils/pg"; interface UploadAreaProps extends DropzoneOptions { /** Callback to run on drop or import */ onDrop: (files: any) => Promise<void>; /** Error message to show */ error: string; /** Default message to show */ text?: string; /** The amount of files that are uploaded */ filesLength?: number; className?: string; } const UploadArea: FC<UploadAreaProps> = ({ className, ...props }) => { const { getRootProps, getInputProps, isDragActive } = useDropzone(props); return ( <Wrapper className={className} {...getRootProps()} isDragActive={isDragActive} > <Input {...getInputProps()} /> <Upload /> <ImportResult isDragActive={isDragActive} {...props} /> </Wrapper> ); }; const Wrapper = styled.div<{ isDragActive: boolean }>` ${({ theme, isDragActive }) => css` display: flex; flex-direction: column; justify-content: center; align-items: center; opacity: ${isDragActive ? 0.55 : 1}; & > svg { ${PgTheme.convertToCSS(theme.components.uploadArea.icon)}; } &:hover > div { color: ${theme.colors.default.textPrimary}; } ${PgTheme.convertToCSS(theme.components.uploadArea.default)}; `} `; type ImportResultProps = Pick< UploadAreaProps, "error" | "filesLength" | "text" > & Pick<DropzoneState, "isDragActive"> & Pick<DropzoneOptions, "noClick">; const ImportResult: FC<ImportResultProps> = ({ error, text, filesLength, isDragActive, noClick, }) => { if (error) { return ( <ImportResultWrapper> <ImportResultText result="error">{error}</ImportResultText> </ImportResultWrapper> ); } if (filesLength) { return ( <ImportResultWrapper> <ImportResultText result="success"> <Checkmark /> Imported {filesLength} {PgCommon.makePlural("file", filesLength)}. </ImportResultText> </ImportResultWrapper> ); } if (isDragActive) return <ImportResultText>Drop here</ImportResultText>; return ( <ImportResultText> {text ?? (noClick ? "Drop files" : "Select or drop files")} </ImportResultText> ); }; /** Adding this div in order to only change the color when result is not defined */ const ImportResultWrapper = styled.div``; const ImportResultText = styled.div<{ result?: keyof DefaultTheme["components"]["uploadArea"]["text"]; }>` ${({ theme, result }) => css` display: flex; align-items: center; & > svg { margin-right: 0.5rem; } ${PgTheme.convertToCSS(theme.components.uploadArea.text.default)} ${result === "error" && PgTheme.convertToCSS(theme.components.uploadArea.text.error)}; ${result === "success" && PgTheme.convertToCSS(theme.components.uploadArea.text.success)}; `} `; export default UploadArea;
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/theme/fonts.ts
import type { Font } from "../utils/pg"; /** All available fonts */ export const FONTS: Font[] = [ { family: "JetBrains Mono", size: { xsmall: "0.7rem", small: "0.75rem", medium: "0.8125rem", large: "0.875rem", xlarge: "1rem", }, }, { family: "Hack", size: { xsmall: "0.7rem", small: "0.75rem", medium: "0.8125rem", large: "0.875rem", xlarge: "1rem", }, }, ];
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/theme/index.ts
export { FONTS } from "./fonts"; export { THEMES } from "./themes";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/theme/create.ts
import { PgCommon } from "../utils/pg/common"; import type { ImportableTheme } from "../utils/pg"; /** * Create themes from the given names. * * Theme names are expected to be Title Case and the theme files are expected * to be kebab-case, e.g. if name is "My Theme", file name should be "my-theme.ts" * * @param names theme names * @returns the importable themes */ export const createThemes = (...names: string[]): ImportableTheme[] => { return names.map((name) => ({ name, importTheme: () => import(`./themes/${PgCommon.toKebabFromTitle(name)}`), })); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/theme/themes.ts
import { createThemes } from "./create"; /** All available themes */ export const THEMES = createThemes("Dracula", "Solana", "Playground", "Light");
0
solana_public_repos/solana-playground/solana-playground/client/src/theme
solana_public_repos/solana-playground/solana-playground/client/src/theme/themes/dracula.ts
import type { Theme } from "../../utils/pg"; // BG const BG_DEFAULT = "#282A36", BG_DARK = "#21222C", BG_DARKER = "#191A21", // FG CYAN = "#8BE9FD", GREEN = "#50FA7B", ORANGE = "#FFB86C", PINK = "#FF79C6", PURPLE = "#BD93F9", RED = "#FF5555", YELLOW = "#F1FA8C", // TEXT TEXT_PRIMARY = "#F8F8F2", TEXT_SECONDARY = "#BCC2CD", // State COMMENT = "#6272A4", SELECTION = "#44475A", HOVER = "#343746"; const DRACULA: Theme = { isDark: true, colors: { default: { bgPrimary: BG_DEFAULT, bgSecondary: BG_DARK, primary: PURPLE, secondary: PINK, textPrimary: TEXT_PRIMARY, textSecondary: TEXT_SECONDARY, border: SELECTION, }, state: { hover: { bg: HOVER, color: "#888a9d", }, disabled: { bg: BG_DARKER, color: TEXT_SECONDARY, }, error: { color: RED, }, success: { color: GREEN, }, warning: { color: YELLOW, }, info: { color: CYAN, }, }, }, components: { bottom: { default: { bg: BG_DARKER, }, connect: { hover: { bg: PURPLE + "16", }, }, }, editor: { gutter: { color: COMMENT, }, }, modal: { default: { bg: BG_DARK, }, }, sidebar: { left: { button: { selected: { bg: SELECTION, }, }, }, }, skeleton: { bg: SELECTION, highlightColor: HOVER, }, toast: { default: { bg: BG_DARKER, }, }, tooltip: { bg: BG_DARKER, }, }, highlight: { typeName: { color: CYAN, fontStyle: "italic" }, variableName: { color: TEXT_PRIMARY }, namespace: { color: CYAN }, macroName: { color: GREEN }, functionCall: { color: GREEN }, functionDef: { color: GREEN }, functionArg: { color: ORANGE }, definitionKeyword: { color: PINK }, moduleKeyword: { color: PINK }, modifier: { color: PINK }, controlKeyword: { color: PINK }, operatorKeyword: { color: PINK }, keyword: { color: PINK }, self: { color: PINK }, bool: { color: PURPLE }, integer: { color: PURPLE }, literal: { color: PURPLE }, string: { color: YELLOW }, character: { color: YELLOW }, operator: { color: PINK }, derefOperator: { color: PINK }, specialVariable: { color: PURPLE }, lineComment: { color: COMMENT }, blockComment: { color: COMMENT }, meta: { color: PURPLE }, invalid: { color: RED }, constant: { color: TEXT_PRIMARY }, regexp: { color: ORANGE }, tagName: { color: YELLOW }, attributeName: { color: YELLOW }, attributeValue: { color: YELLOW }, annotion: { color: ORANGE }, }, }; export default DRACULA;
0
solana_public_repos/solana-playground/solana-playground/client/src/theme
solana_public_repos/solana-playground/solana-playground/client/src/theme/themes/solana.ts
import type { Theme } from "../../utils/pg"; // BG const BG_BLACK = "#000000", // BG_WHITE = "#F9F9FB", BG_GRAY = "#18191E", // FG GREEN = "#14F195", PURPLE = "#9945FF", BLUE = "#80ECFF", PINK = "#EB54BC", ORANGE = "#F85228", RED = "#DC3545", YELLOW = "#FFC107", // TEXT TEXT_PRIMARY = "#FFFFFF", TEXT_SECONDARY = "#AAAAAA", // State DISABLED = "#111114", HOVER_BG = "#2B2D39", SELECTION = "#232323", // Highlight COMMENT = "#859188"; const NO_TRANSFORM = { "&:not(:disabled):hover": { transform: "none", }, }; const SOLANA: Theme = { isDark: true, colors: { default: { bgPrimary: BG_BLACK, bgSecondary: BG_GRAY, primary: GREEN, secondary: PURPLE, textPrimary: TEXT_PRIMARY, textSecondary: TEXT_SECONDARY, border: SELECTION, }, state: { disabled: { bg: DISABLED, color: TEXT_SECONDARY, }, error: { color: RED, }, hover: { bg: HOVER_BG, color: "#91939e", }, info: { color: BLUE, }, success: { color: GREEN, }, warning: { color: YELLOW }, }, }, default: { borderRadius: "12px", }, components: { bottom: { default: { color: BG_BLACK, }, }, button: { default: { "&:not(:disabled):hover": { transform: "translateY(-3px)", }, }, overrides: { icon: NO_TRANSFORM, "no-border": NO_TRANSFORM, transparent: NO_TRANSFORM, primary: { color: BG_BLACK, hover: { color: TEXT_PRIMARY, }, }, outline: { border: `1px solid ${TEXT_PRIMARY}`, hover: { bg: TEXT_PRIMARY, borderColor: BG_BLACK, boxShadow: "0 1rem 2.5rem rgba(35, 35, 35, 0.1), 0 .5rem 1rem -0.75rem rgba(35, 35, 35, 0.1)", color: BG_BLACK, }, }, }, }, editor: { default: { bg: BG_GRAY, }, gutter: { color: TEXT_SECONDARY, activeColor: TEXT_PRIMARY, }, peekView: { title: { bg: BG_BLACK, }, editor: { bg: BG_BLACK, }, }, tooltip: { bg: BG_BLACK, }, }, input: { padding: "0.375rem 0.625rem", }, main: { default: { bg: BG_BLACK, }, primary: { home: { resources: { card: { default: { bg: BG_GRAY, }, }, }, tutorials: { card: { bg: BG_GRAY, }, }, }, tutorials: { main: { default: { bg: BG_BLACK, border: `1px solid ${SELECTION}`, }, content: { card: { default: { bg: BG_GRAY, }, }, }, }, }, }, }, menu: { default: { bg: BG_GRAY, }, }, sidebar: { right: { default: { bg: BG_BLACK, otherBg: BG_GRAY, }, }, }, skeleton: { bg: SELECTION, highlightColor: HOVER_BG, }, tabs: { tab: { current: { bg: BG_GRAY, }, }, }, terminal: { default: { bg: BG_GRAY, }, }, toast: { default: { bg: BG_GRAY, }, }, tooltip: { bg: BG_GRAY, bgSecondary: BG_BLACK, }, wallet: { default: { bg: BG_BLACK, }, main: { transactions: { table: { default: { bg: BG_GRAY, }, header: { bg: BG_BLACK, }, }, }, }, }, }, highlight: { typeName: { color: BLUE, fontStyle: "italic" }, variableName: { color: TEXT_PRIMARY }, namespace: { color: BLUE }, macroName: { color: GREEN }, functionCall: { color: GREEN }, functionDef: { color: GREEN }, functionArg: { color: TEXT_PRIMARY }, definitionKeyword: { color: PINK }, moduleKeyword: { color: PINK }, modifier: { color: PINK }, controlKeyword: { color: PINK }, operatorKeyword: { color: PINK }, keyword: { color: PINK }, self: { color: PINK }, bool: { color: PURPLE }, integer: { color: PURPLE }, literal: { color: PURPLE }, string: { color: YELLOW }, character: { color: YELLOW }, operator: { color: PINK }, derefOperator: { color: PINK }, specialVariable: { color: PURPLE }, lineComment: { color: COMMENT }, blockComment: { color: COMMENT }, meta: { color: PURPLE }, invalid: { color: RED }, constant: { color: TEXT_PRIMARY }, regexp: { color: ORANGE }, tagName: { color: YELLOW }, attributeName: { color: YELLOW }, attributeValue: { color: YELLOW }, annotion: { color: ORANGE }, }, }; export default SOLANA;
0
solana_public_repos/solana-playground/solana-playground/client/src/theme
solana_public_repos/solana-playground/solana-playground/client/src/theme/themes/light.ts
import type { Theme } from "../../utils/pg"; // BG const BG_DARK = "#2c2c2c"; const BG_LIGHT = "#f3f3f3"; const BG_WHITE = "#ffffff"; // FG const BLUE = "#2979cc"; const PURPLE = "#af22db"; const GUTTER_BLUE = "#257893"; const TYPE_BLUE = "#41b3e8"; const FN_YELLOW = "#e19f41"; const KEYWORDS_BLUE = "#285fff"; const CONDITIONAL_PURPLE = "#b14ff1"; const NUMBER_GREEN = "#298c67"; const STRING_RED = "#b41c32"; const AMPERSAND_DARK_BLUE = "#020737"; const ERROR_RED = "#ff5555"; //TEXT const TEXT_PRIMARY = "#333333"; const TEXT_SECONDARY = "#555555"; // State const COMMENT = "#238000"; const SELECTION = "#e5ebf1"; const HOVER = "#ecedee"; const DISABLED = "#cccccc"; const LIGHT: Theme = { isDark: false, colors: { default: { bgPrimary: BG_WHITE, bgSecondary: BG_LIGHT, primary: BLUE, secondary: PURPLE, textPrimary: TEXT_PRIMARY, textSecondary: TEXT_SECONDARY, border: SELECTION, }, state: { hover: { bg: HOVER, color: "#71717110", }, disabled: { bg: DISABLED, color: TEXT_SECONDARY, }, error: { color: ERROR_RED, }, success: { color: NUMBER_GREEN, }, warning: { color: FN_YELLOW, }, info: { color: BLUE, }, }, }, components: { bottom: { default: { color: BG_WHITE, }, }, button: { overrides: { primary: { color: BG_LIGHT, hover: { color: BG_WHITE, }, }, secondary: { color: BG_LIGHT, hover: { color: BG_WHITE, }, }, "primary-outline": { hover: { color: BG_LIGHT, }, }, "primary-transparent": { bg: BLUE + "dd", color: BG_LIGHT, hover: { bg: BLUE + "bb", color: BG_WHITE, }, }, "secondary-outline": { hover: { color: BG_LIGHT, }, }, "secondary-transparent": { bg: PURPLE + "dd", color: BG_LIGHT, hover: { bg: PURPLE + "bb", color: BG_WHITE, }, }, error: { color: BG_LIGHT, hover: { color: BG_WHITE, }, }, outline: { borderColor: TEXT_SECONDARY + "36", }, }, }, editor: { default: { color: "#0f1780", }, gutter: { color: GUTTER_BLUE, activeColor: TEXT_PRIMARY, }, }, main: { primary: { programs: { main: { content: { card: { bg: BG_WHITE, }, }, }, }, }, }, sidebar: { left: { default: { bg: BG_DARK, }, button: { selected: { bg: "#00000020", borderLeft: `2px solid ${BG_LIGHT}`, }, }, }, }, skeleton: { bg: "#e5e4e6", highlightColor: BG_LIGHT, }, wallet: { default: { bg: BG_WHITE, }, }, }, highlight: { typeName: { color: TYPE_BLUE, fontStyle: "italic" }, variableName: { color: TEXT_PRIMARY }, namespace: { color: TYPE_BLUE }, macroName: { color: KEYWORDS_BLUE }, functionCall: { color: FN_YELLOW }, functionDef: { color: FN_YELLOW }, functionArg: { color: TEXT_PRIMARY }, definitionKeyword: { color: KEYWORDS_BLUE }, moduleKeyword: { color: KEYWORDS_BLUE }, modifier: { color: KEYWORDS_BLUE }, controlKeyword: { color: CONDITIONAL_PURPLE }, operatorKeyword: { color: KEYWORDS_BLUE }, keyword: { color: KEYWORDS_BLUE }, self: { color: KEYWORDS_BLUE }, bool: { color: KEYWORDS_BLUE }, integer: { color: NUMBER_GREEN }, literal: { color: NUMBER_GREEN }, string: { color: STRING_RED }, character: { color: STRING_RED }, operator: { color: AMPERSAND_DARK_BLUE }, derefOperator: { color: AMPERSAND_DARK_BLUE }, specialVariable: { color: AMPERSAND_DARK_BLUE }, lineComment: { color: COMMENT }, blockComment: { color: COMMENT }, meta: { color: GUTTER_BLUE }, invalid: { color: ERROR_RED }, constant: { color: TEXT_SECONDARY }, regexp: { color: STRING_RED }, tagName: { color: STRING_RED }, attributeName: { color: STRING_RED }, attributeValue: { color: STRING_RED }, annotion: { color: STRING_RED }, }, }; export default LIGHT;
0
solana_public_repos/solana-playground/solana-playground/client/src/theme
solana_public_repos/solana-playground/solana-playground/client/src/theme/themes/playground.ts
import type { Theme } from "../../utils/pg"; // BG const BG_DEFAULT = "#151721", BG_DARK = "#0e1019", BG_LIGHT = "#212431", // FG BLUE = "#5288f2", DARK_BLUE = "#1a2c4f", CYAN = "#46c9d7", RED = "#c63453", GREEN = "#29cd7d", YELLOW = "#e7d354", // TEXT TEXT_PRIMARY = "#f2f2f7", TEXT_SECONDARY = "#c0c1ce", // Border BORDER_COLOR = "#293244", // State DISABLED = "#0c0c11", COMMENT = "#9BA8C8"; // Highlighting const H_YELLOW = "#ffd174", H_LIGHT_BLUE = "#38ccff", H_PURPLE = "#d57bee", H_PINK = "#e1a6da", H_GREEN = "#2ef0b1"; const BOX_SHADOW_LIGHT = `0px 0px 12px 0px ${TEXT_PRIMARY}30`; const PROGRESS_BG = `linear-gradient(to right, ${BLUE}, ${CYAN})`; const PLAYGROUND: Theme = { isDark: true, colors: { default: { bgPrimary: BG_DEFAULT, bgSecondary: BG_DARK, primary: BLUE, secondary: CYAN, textPrimary: TEXT_PRIMARY, textSecondary: TEXT_SECONDARY, border: BORDER_COLOR, }, state: { disabled: { bg: DISABLED, color: TEXT_SECONDARY, }, error: { color: RED, }, hover: { bg: BG_LIGHT, color: "#838799", }, info: { color: BLUE, }, success: { color: GREEN, }, warning: { color: YELLOW, }, }, }, default: { backdrop: { backdropFilter: "blur(8px)", }, borderRadius: "8px", boxShadow: "#0d081680 -1px 4px 8px", }, components: { bottom: { default: { bg: DARK_BLUE, }, }, button: { default: { borderRadius: "12px", }, }, editor: { default: { bg: "transparent", }, gutter: { bg: "transparent", color: COMMENT, }, wrapper: { bg: `linear-gradient(315deg, ${BG_DEFAULT}, ${BG_LIGHT})`, }, }, main: { default: { bg: `linear-gradient(45deg, ${BG_DARK}, ${BG_DEFAULT})`, }, primary: { home: { resources: { card: { default: { boxShadow: BOX_SHADOW_LIGHT, border: "none", }, }, }, }, programs: { top: { bg: `linear-gradient(180deg, ${BG_DEFAULT}, ${BG_LIGHT})`, boxShadow: BOX_SHADOW_LIGHT, }, }, tutorial: { aboutPage: { bg: "transparent", boxShadow: BOX_SHADOW_LIGHT, }, }, tutorials: { top: { bg: `linear-gradient(180deg, ${BG_DEFAULT}, ${BG_LIGHT})`, boxShadow: BOX_SHADOW_LIGHT, }, main: { content: { card: { default: { boxShadow: BOX_SHADOW_LIGHT, }, }, featured: { boxShadow: BOX_SHADOW_LIGHT, }, }, }, }, }, secondary: { default: { bg: `linear-gradient(210deg, ${BG_DEFAULT} 75%, ${BG_LIGHT})`, borderTop: `1px solid ${BLUE}80`, transition: `all 250ms ease-in-out`, focusWithin: { borderTopColor: BLUE, }, }, }, }, modal: { default: { bg: BG_DARK + "19", boxShadow: BOX_SHADOW_LIGHT, border: "none", }, }, sidebar: { left: { default: { bg: `linear-gradient(to right, ${BG_DEFAULT}, ${BG_LIGHT})`, }, }, right: { default: { bg: `linear-gradient(45deg, ${BG_DARK}, ${BG_LIGHT})`, otherBg: `linear-gradient(315deg, ${BG_DEFAULT}, ${BG_LIGHT})`, }, }, }, skeleton: { bg: BG_LIGHT, highlightColor: BG_DEFAULT, }, progressbar: { indicator: { bg: PROGRESS_BG, }, }, toast: { progress: { bg: PROGRESS_BG, }, }, }, highlight: { typeName: { color: CYAN, fontStyle: "italic" }, variableName: { color: TEXT_PRIMARY }, namespace: { color: CYAN }, macroName: { color: H_GREEN }, functionCall: { color: H_GREEN }, functionDef: { color: H_GREEN }, functionArg: { color: TEXT_PRIMARY }, definitionKeyword: { color: BLUE }, moduleKeyword: { color: BLUE }, modifier: { color: BLUE }, controlKeyword: { color: H_PURPLE }, operatorKeyword: { color: H_PURPLE }, keyword: { color: BLUE }, self: { color: BLUE }, bool: { color: H_PINK, fontStyle: "italic" }, integer: { color: H_PINK }, literal: { color: H_PINK }, string: { color: H_YELLOW }, character: { color: H_YELLOW }, operator: { color: H_PURPLE }, derefOperator: { color: H_PURPLE }, specialVariable: { color: H_PURPLE }, lineComment: { color: COMMENT, fontStyle: "italic" }, blockComment: { color: COMMENT, fontStyle: "italic" }, meta: { color: H_LIGHT_BLUE }, invalid: { color: RED }, constant: { color: TEXT_PRIMARY }, regexp: { color: YELLOW }, tagName: { color: YELLOW }, attributeName: { color: YELLOW }, attributeValue: { color: YELLOW }, annotion: { color: YELLOW }, }, }; export default PLAYGROUND;
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useProgramInfo.tsx
import { PgProgramInfo } from "../utils/pg"; import { useRenderOnChange } from "./useRenderOnChange"; /** Get the current program info. */ export const useProgramInfo = () => { useRenderOnChange(PgProgramInfo.onDidChange); return { programInfo: PgProgramInfo, error: !PgProgramInfo.onChain, deployed: PgProgramInfo.onChain?.deployed, }; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useSetStatic.tsx
import { Dispatch, SetStateAction, useEffect } from "react"; export const useSetStatic = ( set: Dispatch<SetStateAction<any>>, eventName: string ) => { useEffect(() => { const handle = (e: UIEvent & { detail: any }) => { set(e.detail); }; document.addEventListener(eventName, handle as EventListener); return () => document.removeEventListener(eventName, handle as EventListener); }, [eventName, set]); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useWallet.tsx
import { PgWallet } from "../utils/pg"; import { useRenderOnChange } from "./useRenderOnChange"; export const useWallet = () => { useRenderOnChange(PgWallet.onDidChangeCurrent); return { wallet: PgWallet.current }; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useBalance.tsx
import { PgWallet } from "../utils/pg"; import { useRenderOnChange } from "./useRenderOnChange"; /** Get globally synced current wallet's balance. */ export const useBalance = () => { useRenderOnChange(PgWallet.onDidChangeBalance); return { balance: PgWallet.balance }; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useOnClickOutside.tsx
import { RefObject, useEffect } from "react"; /** * Run the given callback when the user clicks outside of the given element. * * @param ref element reference * @param cb callback function to run on outside click * @param listenCondition only listen for click events if this condition is truthy */ export const useOnClickOutside = ( ref: RefObject<HTMLElement>, cb: () => void, listenCondition: boolean = true ) => { useEffect(() => { if (!listenCondition) return; const handleOutsideClick = (ev: MouseEvent) => { if (ev.target && !ref.current?.contains(ev.target as Node)) { cb(); } }; document.addEventListener("mousedown", handleOutsideClick); return () => document.removeEventListener("mousedown", handleOutsideClick); }, [ref, cb, listenCondition]); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useMounted.tsx
import { useEffect, useRef } from "react"; /** * Get whether the component is mounted. * * @returns whether the component is mounted */ export const useMounted = () => { const mounted = useRef(false); useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }); return mounted; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useGetAndSetStatic.tsx
import { Dispatch, SetStateAction, useMemo } from "react"; import { PgCommon } from "../utils/pg/common"; import { useGetStatic } from "./useGetStatic"; import { useSetStatic } from "./useSetStatic"; export const useGetAndSetStatic = <T,>( get: T, set: Dispatch<SetStateAction<T>>, eventName: string ) => { const eventNames = useMemo( () => PgCommon.getStaticStateEventNames(eventName), [eventName] ); useGetStatic(get, eventNames.get); useSetStatic(set, eventNames.set); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useExposeStatic.tsx
import { useCallback, useMemo } from "react"; import { useSendAndReceiveCustomEvent } from "./useSendAndReceiveCustomEvent"; import { PgCommon } from "../utils/pg/common"; import type { Methods } from "../utils/pg"; /** * Expose the given class object inside a component to outside, allowing it to * be used anywhere. * * This hook should be used with {@link PgCommon.sendAndReceiveCustomEvent}. * For example, to get the object statically: * * ```ts * const classObject = await PgCommon.sendAndReceiveCustomEvent<Type>( * PgCommon.getStaticEventNames(eventName).get * ); * ``` * * @param classObject object to expose * @param eventName event name to derive from */ export const useExposeStatic = ( classObject: { [key: string]: any } | null, eventName: string ) => { const eventNames = useMemo( () => PgCommon.getStaticEventNames(eventName), [eventName] ); useExposeGetClassAsStatic(classObject, eventNames.get); useExposeMethodsAsStatic(classObject, eventNames.run); }; const useExposeGetClassAsStatic = <T,>(classObject: T, eventName: string) => { const cb = useCallback(async () => classObject, [classObject]); useSendAndReceiveCustomEvent<T>(eventName, cb); }; const useExposeMethodsAsStatic = <T,>( classObject: { [key: string]: any } | null, eventName: string ) => { const cb = useCallback( async (data) => { if (!classObject) return; const methodName = Object.keys(data)[0]; if (!classObject[methodName]?.call) return classObject[methodName]; return await classObject[methodName](...data[methodName]); }, [classObject] ); useSendAndReceiveCustomEvent< Methods<T> extends { [key: string]: any } ? Methods<T> : never >(eventName, cb); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useBlockExplorer.tsx
import { useRenderOnChange } from "./useRenderOnChange"; import { PgBlockExplorer } from "../utils/pg"; /** Get the current block explorer */ export const useBlockExplorer = () => { useRenderOnChange(PgBlockExplorer.onDidChange); return PgBlockExplorer.current; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useCopy.tsx
import useCopyClipboard from "react-use-clipboard"; export const useCopy = (str: string): [boolean, () => void] => { const [copied, setCopied] = useCopyClipboard(str, { successDuration: 5000, }); return [copied, setCopied]; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useDifferentBackground.tsx
import { useEffect, useRef } from "react"; import { useTheme } from "styled-components"; import { PgTheme } from "../utils/pg"; /** * Use a different background than the parent node's background. * * @param delay the amount of miliseconds to delay the background check * * @returns the element ref object to attach */ export const useDifferentBackground = <T extends HTMLElement = HTMLDivElement>( delay?: number ) => { const ref = useRef<T>(null); const theme = useTheme(); useEffect(() => { const id = setTimeout(() => { if (!ref.current) return; let parent: HTMLElement | null | undefined = ref.current; let inheritedBg = ""; while (1) { parent = parent?.parentElement; if (!parent) continue; const style = getComputedStyle(parent); if (style.backgroundImage !== "none") { inheritedBg = style.backgroundImage; break; } if (style.backgroundColor !== "rgba(0, 0, 0, 0)") { inheritedBg = style.backgroundColor; break; } } ref.current.style.background = PgTheme.getDifferentBackground(inheritedBg); }, delay); return () => clearTimeout(id); // eslint-disable-next-line react-hooks/exhaustive-deps }, [delay, theme.name]); return { ref }; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useConnection.tsx
import { PgConnection } from "../utils/pg"; import { useRenderOnChange } from "./useRenderOnChange"; /** Get access to Playnet compatible globally synced `Connection` object. */ export const useConnection = () => { useRenderOnChange(PgConnection.onDidChangeCurrent); useRenderOnChange(PgConnection.onDidChangeIsConnected); return { connection: PgConnection.current, isConnected: PgConnection.isConnected, }; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useSendAndReceiveCustomEvent.tsx
import { DependencyList, useEffect } from "react"; import { PgCommon } from "../utils/pg/common"; export const useSendAndReceiveCustomEvent = <T,>( eventName: string, cb: (data: T) => Promise<any>, deps?: DependencyList ) => { useEffect(() => { const eventNames = PgCommon.getSendAndReceiveEventNames(eventName); const handleSend = async (e: UIEvent & { detail: T }) => { try { const data = await cb(e.detail); PgCommon.createAndDispatchCustomEvent(eventNames.receive, { data }); } catch (e: any) { PgCommon.createAndDispatchCustomEvent(eventNames.receive, { error: e.message, }); } }; document.addEventListener(eventNames.send, handleSend as any); return () => { document.removeEventListener(eventNames.send, handleSend as any); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps ?? [eventName, cb]); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useGetStatic.tsx
import { useSendAndReceiveCustomEvent } from "./useSendAndReceiveCustomEvent"; export const useGetStatic = (get: any, eventName: string) => { useSendAndReceiveCustomEvent(eventName, () => get); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/index.ts
export { useAsyncEffect } from "./useAsyncEffect"; export { useBalance } from "./useBalance"; export { useBlockExplorer } from "./useBlockExplorer"; export { useConnection } from "./useConnection"; export { useCopy } from "./useCopy"; export { useDifferentBackground } from "./useDifferentBackground"; export { useDisposable } from "./useDisposable"; export { useExplorer } from "./useExplorer"; export { useExposeStatic } from "./useExposeStatic"; export { useFilteredSearch } from "./useFilteredSearch"; export { useGetAndSetStatic } from "./useGetAndSetStatic"; export { useGetStatic } from "./useGetStatic"; export { useKeybind } from "./useKeybind"; export { useMounted } from "./useMounted"; export { useOnClickOutside } from "./useOnClickOutside"; export { useProgramInfo } from "./useProgramInfo"; export { useRenderOnChange } from "./useRenderOnChange"; export { useSendAndReceiveCustomEvent } from "./useSendAndReceiveCustomEvent"; export { useSetStatic } from "./useSetStatic"; export { useWallet } from "./useWallet";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useRenderOnChange.tsx
import { useEffect, useReducer, useState } from "react"; import type { Disposable } from "../utils/pg"; export const useRenderOnChange = <T,>( onChange: (cb: (v?: T) => any) => Disposable, defaultValue?: T ) => { const [value, setValue] = useState(defaultValue); const [, render] = useReducer((r) => r + 1, 0); const [effect, runEffect] = useReducer((r) => r + 1, 0); useEffect(() => { // If `onChange` doesn't exist, re-run the effect after a timeout if (!onChange) { setTimeout(() => runEffect(), 20); return; } const { dispose } = onChange((newValue) => { if (newValue === undefined) { render(); return; } const valueType = typeof newValue; // Static class is type `function`. Intentionally passing a function because // `useState` does not accept static classes as a value. if (valueType === "function") { setValue(() => newValue); render(); } else if (valueType === "object") { setValue(newValue); render(); } else { setValue(newValue); } }); return dispose; }, [effect, onChange]); return value; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useFilteredSearch.tsx
import { ChangeEvent } from "react"; import { useLocation, useSearchParams } from "react-router-dom"; import { Arrayable, PgCommon, PgRouter } from "../utils/pg"; type Filterable = { name: string; featured?: boolean } & Record<string, any>; interface FilterSearchProps<T extends Filterable> { /** Global route path */ route: RoutePath; /** All filterable items */ items: T[]; /** All filters */ filters: Readonly<Array<{ param: string }>>; /** Sort function for the items */ sort: (a: T, b: T) => number; } export const useFilteredSearch = <T extends Filterable>({ route, items, filters, sort, }: FilterSearchProps<T>) => { const [searchParams, setSearchParams] = useSearchParams(); // If the user clicks an item, the `pathname` will be the item's path. // This causes flickering when filters are applied before the click because // filters will get reset before the component unmounts which makes the // unfiltered items show up just before the component unmounts. // TODO: Make sure routes don't leak const { pathname } = useLocation(); if (!PgRouter.isPathsEqual(pathname, route)) return null; const search = searchParams.get(SEARCH_PARAM) ?? ""; const queries = filters.map((f) => ({ key: f.param, value: searchParams.getAll(f.param), })); const [featuredItems, regularItems] = PgCommon.filterWithRemaining( items .filter((item) => { return ( item.name.toLowerCase().includes(search.toLowerCase()) && queries.every((f) => filterQuery(f.value, item[f.key])) ); }) .sort(sort), (t) => t.featured ); return { featuredItems, regularItems, searchBarProps: { value: search, onChange: (ev: ChangeEvent<HTMLInputElement>) => { const value = ev.target.value; if (!value) searchParams.delete(SEARCH_PARAM); else searchParams.set(SEARCH_PARAM, value); setSearchParams(searchParams, { replace: true }); }, }, }; }; const SEARCH_PARAM = "search"; /** * Filter the query based on the search values and the item values. * * @param searchValues values in the URL * @param itemValues values declared for the item * @returns whether the item passes the checks */ const filterQuery = ( searchValues: Arrayable<string>, itemValues: Arrayable<string> = [] ) => { searchValues = PgCommon.toArray(searchValues); itemValues = PgCommon.toArray(itemValues); return ( !searchValues.length || (!!itemValues.length && searchValues.some((v) => itemValues.includes(v))) ); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useDisposable.tsx
import { useAsyncEffect } from "./useAsyncEffect"; import type { Disposable, SyncOrAsync } from "../utils/pg"; /** Run the given callback on mount and dispose it on unmount. */ export const useDisposable = (disposable: () => SyncOrAsync<Disposable>) => { useAsyncEffect(async () => { const { dispose } = await disposable(); return dispose; }, [disposable]); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useAsyncEffect.tsx
import { DependencyList, useEffect } from "react"; import type { Fn } from "../utils/pg"; /** * Async version of the `useEffect` hook. * * NOTE: Be careful when using this hook with a callback that subscribes to changes * (especially nested subscribes) because it could potentially not get cleaned up. * * @param cb callback function to run * @param deps `useEffect` dependency array */ export const useAsyncEffect = ( cb: () => Promise<Fn | void>, deps?: DependencyList ) => { useEffect( () => { let returned = false; let ret: Fn | void; (async () => { ret = await cb(); if (returned) ret?.(); })(); return () => { returned = true; ret?.(); }; }, // eslint-disable-next-line react-hooks/exhaustive-deps deps ); };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/hooks/useExplorer.tsx
import { PgExplorer } from "../utils/pg"; import { useRenderOnChange } from "./useRenderOnChange"; /** * Globally synced explorer. * * @param checkInitialization whether to check whether the explorer is initialized * @returns the global explorer object */ export const useExplorer = <C,>(opts?: { checkInitialization?: C }) => { useRenderOnChange(PgExplorer.onNeedRender); return { explorer: opts?.checkInitialization ? PgExplorer.isInitialized ? PgExplorer : null : PgExplorer, } as { explorer: C extends true ? typeof PgExplorer | null : typeof PgExplorer; }; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/block-explorers/solana-explorer.ts
import { Endpoint } from "../constants"; import { PgBlockExplorer, PgConnection } from "../utils/pg"; export const solanaExplorer = PgBlockExplorer.create({ name: "Solana Explorer", url: "https://explorer.solana.com", getClusterParam: () => { switch (PgConnection.cluster) { case "mainnet-beta": return ""; case "testnet": return "?cluster=testnet"; case "devnet": return "?cluster=devnet"; case "localnet": return "?cluster=custom&customUrl=" + Endpoint.LOCALHOST; } }, });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/block-explorers/solana-fm.ts
import { Endpoint } from "../constants"; import { PgBlockExplorer, PgConnection } from "../utils/pg"; export const solanaFM = PgBlockExplorer.create({ name: "Solana FM", url: "https://solana.fm", getClusterParam: () => { switch (PgConnection.cluster) { case "mainnet-beta": return ""; case "testnet": return "?cluster=testnet-solana"; case "devnet": return "?cluster=devnet-solana"; case "localnet": // Doesn't work with protocol ("http") prefix return "?cluster=custom-" + new URL(Endpoint.LOCALHOST).host; } }, });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/block-explorers/solscan.ts
import { PgBlockExplorer, PgConnection } from "../utils/pg"; export const solscan = PgBlockExplorer.create({ name: "Solscan", url: "https://solscan.io", getClusterParam: () => { switch (PgConnection.cluster) { case "mainnet-beta": return ""; case "testnet": return "?cluster=testnet"; case "devnet": return "?cluster=devnet"; case "localnet": // No support https://solana.stackexchange.com/a/2330 return ""; } }, });
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/block-explorers/index.ts
import * as _BLOCK_EXPLORERS from "./block-explorers"; export const BLOCK_EXPLORERS = Object.values(_BLOCK_EXPLORERS);
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/block-explorers/block-explorers.ts
export * from "./solana-explorer"; export * from "./solana-fm"; export * from "./solscan";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/index.ts
export { TUTORIALS } from "./tutorials";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/create.ts
import { PgCommon, TutorialData, TutorialDataInit } from "../utils/pg"; /** Create tutorials with defaults. */ export const createTutorials = (...tutorials: TutorialDataInit[]) => { return tutorials.map((tutorial) => { if (tutorial.categories && tutorial.categories.length > 3) { throw new Error( [ `Tutorial "${tutorial.name}" has ${tutorial.categories.length}`, "categories but the maximum allowed category amount is 3", ].join(" ") ); } if (!tutorial.thumbnail) { const kebabCaseName = PgCommon.toKebabFromTitle(tutorial.name); tutorial.thumbnail = kebabCaseName + "/" + TUTORIAL_THUMBNAIL_MAP[kebabCaseName]; } tutorial.thumbnail = "/tutorials/" + tutorial.thumbnail; tutorial.elementImport ??= () => { return import(`./${PgCommon.toPascalFromTitle(tutorial.name)}`); }; return tutorial; }) as TutorialData[]; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/tutorials.ts
import { createTutorials } from "./create"; /** All visible tutorials at `/tutorials`(in order) */ export const TUTORIALS = createTutorials( { name: "Hello Solana", description: "Hello world program with Native Solana/Rust.", authors: [ { name: "acheron", link: "https://twitter.com/acheroncrypto", }, ], level: "Beginner", framework: "Native", languages: ["Rust", "TypeScript"], }, { name: "Hello Anchor", description: "Hello world program with Anchor framework.", authors: [ { name: "acheron", link: "https://twitter.com/acheroncrypto", }, ], level: "Beginner", framework: "Anchor", languages: ["Rust", "TypeScript"], }, { name: "Hello Seahorse", description: "Hello world program with Seahorse framework in Python.", authors: [ { name: "acheron", link: "https://twitter.com/acheroncrypto", }, ], level: "Beginner", framework: "Seahorse", languages: ["Python", "TypeScript"], }, { name: "Counter PDA Tutorial", description: "Create a simple counter that will store the number of times is called.", authors: [ { name: "cleon", link: "https://twitter.com/0xCleon", }, ], level: "Beginner", framework: "Anchor", languages: ["Rust", "TypeScript"], thumbnail: "counter-easy/thumbnail.jpg", elementImport: () => import("./CounterEasy"), }, { name: "Tiny Adventure", description: "Create a very simple on chain game. Moving a character left and right. Will be connected to Unity Game Engine later on.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, ], level: "Beginner", framework: "Anchor", languages: ["Rust", "TypeScript"], categories: ["Gaming"], }, { name: "Tiny Adventure Two", description: "Giving out SOL rewards to players.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, ], level: "Beginner", framework: "Anchor", languages: ["Rust", "TypeScript"], categories: ["Gaming"], }, { name: "Zero Copy", description: "How to handle memory and big accounts.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, ], level: "Advanced", framework: "Anchor", languages: ["Rust", "TypeScript"], }, { name: "Lumberjack", description: "How to build an energy system on chain.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, ], level: "Intermediate", framework: "Anchor", languages: ["Rust", "TypeScript"], categories: ["Gaming"], }, { name: "Battle Coins", description: "Learn to create a token mint with metadata, mint tokens, and burn tokens. Defeat enemies to earn tokens and restore your health by burning tokens.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, { name: "John", link: "https://twitter.com/ZYJLiu", }, ], level: "Intermediate", framework: "Anchor", languages: ["Rust", "TypeScript"], categories: ["Gaming"], }, { name: "Boss Battle", description: "How to use XORShift random number generator in an onchain game. Spawn and attack an enemy boss, dealing pseudo-random damage utilizing the current slot as a source of randomness.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, { name: "John", link: "https://twitter.com/ZYJLiu", }, ], level: "Intermediate", framework: "Anchor", languages: ["Rust", "TypeScript"], categories: ["Gaming"], }, { name: "Spl Token Vault", description: "Learn how to create and SPL token with meta data and icon using metaplex sdk and saving it in an anchor program.", authors: [ { name: "Jonas Hahn", link: "https://twitter.com/solplay_jonas", }, ], framework: "Anchor", level: "Intermediate", languages: ["Rust", "TypeScript"], categories: ["SPL", "Token"], }, { name: "Expense Tracker", description: "Learn how to create an expense tracker app and understand PDAs", authors: [ { name: "Bolt / Syed Aabis Akhtar", link: "https://twitter.com/0xBolt", }, ], level: "Beginner", framework: "Anchor", languages: ["Rust", "TypeScript"], }, { name: "Bank Simulator", description: "Learn on-chain automation by creating bank program with interest returns.", authors: [ { name: "Bolt / Syed Aabis Akhtar", link: "https://twitter.com/0xBolt", }, ], level: "Intermediate", framework: "Anchor", languages: ["Rust", "TypeScript"], }, { name: "Tictactoe Seahorse", description: "Create your own 2 player on-chain classic game of tic-tac-toe.", authors: [ { name: "lostin", link: "https://twitter.com/__lostin__", }, ], level: "Beginner", framework: "Seahorse", languages: ["Python", "TypeScript"], categories: ["Gaming"], }, { name: "Todo App Seahorse", description: "Build a todo app to keep track of tasks.", authors: [ { name: "lostin", link: "https://twitter.com/__lostin__", }, ], level: "Beginner", framework: "Seahorse", languages: ["Python", "TypeScript"], }, { name: "Faucet Seahorse", description: "Build a token faucet with a price oracle.", authors: [ { name: "lostin", link: "https://twitter.com/__lostin__", }, ], level: "Intermediate", framework: "Seahorse", languages: ["Python", "TypeScript"], categories: ["SPL", "Token"], } );
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/CounterEasy/CounterEasy.tsx
import { Tutorial } from "../../components/Tutorial"; const CounterEasy = () => ( <Tutorial // About section that will be shown under the description of the tutorial page about={require("./about.md")} // Actual tutorial pages to show next to the editor pages={[ { content: require("./pages/1.md") }, { content: require("./pages/2.md") }, { content: require("./pages/3.md") }, { content: require("./pages/4.md") }, { content: require("./pages/5.md") }, { content: require("./pages/6.md") }, { content: require("./pages/7.md") }, { content: require("./pages/8.md") }, { content: require("./pages/9.md") }, { content: require("./pages/10.md") }, ]} // Initial files to have at the beginning of the tutorial files={[ ["src/lib.rs", require("./files/lib.rs")], ["tests/index.test.ts", require("./files/anchor.test.ts.raw")], ]} /> ); export default CounterEasy;
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/CounterEasy/index.ts
export { default } from "./CounterEasy";
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/CounterEasy
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/CounterEasy/files/lib.rs
use anchor_lang::prelude::*; declare_id!(""); #[program] // Smart contract functions pub mod counter { use super::*; pub fn create_counter(ctx: Context<CreateCounter>) -> Result<()> { msg!("Creating a Counter!!"); // The creation of the counter must be here msg!("Current count is {}", counter.count); msg!("The Admin PubKey is: {} ", counter.authority); Ok(()) } pub fn update_counter(ctx: Context<UpdateCounter>) -> Result<()> { msg!("Adding 1 to the counter!!"); // Updating the counter must be here msg!("Current count is {}", counter.count); msg!("{} remaining to reach 1000 ", 1000 - counter.count); Ok(()) } } // Data validators #[derive(Accounts)] pub struct CreateCounter<'info> { #[account(mut)] authority: Signer<'info>, #[account( init, seeds = [authority.key().as_ref()], bump, payer = authority, space = 100 )] counter: Account<'info, Counter>, system_program: Program<'info, System>, } #[derive(Accounts)] pub struct UpdateCounter<'info> { authority: Signer<'info>, #[account(mut, has_one = authority)] counter: Account<'info, Counter>, } // Data structures #[account] pub struct Counter { authority: Pubkey, count: u64, }
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/CounterEasy
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/CounterEasy/files/anchor.test.ts.raw
describe("counter", () => { // Configure the client to use the local cluster. const systemProgram = anchor.web3.SystemProgram; it("Create Counter!", async () => { // Keypair = account const [counter, _counterBump] = await anchor.web3.PublicKey.findProgramAddress( [pg.wallet.publicKey.toBytes()], pg.program.programId ); console.log("Your counter address", counter.toString()); const tx = await pg.program.methods .createCounter() .accounts({ authority: pg.wallet.publicKey, counter: counter, systemProgram: systemProgram.programId, }) .rpc(); console.log("Your transaction signature", tx); }); it("Fetch a counter!", async () => { // Keypair = account const [counterPubkey, _] = await anchor.web3.PublicKey.findProgramAddress( [pg.wallet.publicKey.toBytes()], pg.program.programId ); console.log("Your counter address", counterPubkey.toString()); const counter = await pg.program.account.counter.fetch(counterPubkey); console.log("Your counter", counter); }); it("Update a counter!", async () => { // Keypair = account const [counterPubkey, _] = await anchor.web3.PublicKey.findProgramAddress( [pg.wallet.publicKey.toBytes()], pg.program.programId ); console.log("Your counter address", counterPubkey.toString()); const counter = await pg.program.account.counter.fetch(counterPubkey); console.log("Your counter", counter); const tx = await pg.program.methods .updateCounter() .accounts({ counter: counterPubkey, }) .rpc(); console.log("Your transaction signature", tx); const counterUpdated = await pg.program.account.counter.fetch(counterPubkey); console.log("Your counter count is: ", counterUpdated.count.toNumber()); }); });
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BattleCoins/BattleCoins.tsx
import { Tutorial } from "../../components/Tutorial"; const BattleCoins = () => ( <Tutorial // About section that will be shown under the description of the tutorial page about={require("./about.md")} // Actual tutorial pages to show next to the editor pages={[ { content: require("./pages/1.md") }, { content: require("./pages/2.md") }, { content: require("./pages/3.md") }, { content: require("./pages/4.md") }, { content: require("./pages/5.md") }, { content: require("./pages/6.md") }, { content: require("./pages/7.md") }, ]} // Initial files to have at the beginning of the tutorial files={[ ["src/lib.rs", require("./files/lib.rs")], ["client/client.ts", require("./files/client.ts.raw")], ]} /> ); export default BattleCoins;
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BattleCoins/index.ts
export { default } from "./BattleCoins";
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BattleCoins
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BattleCoins/files/client.ts.raw
import { Metaplex } from "@metaplex-foundation/js"; import { getMint, getAssociatedTokenAddressSync } from "@solana/spl-token"; // metaplex token metadata program ID const TOKEN_METADATA_PROGRAM_ID = new web3.PublicKey( "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s" ); // metaplex setup const metaplex = Metaplex.make(pg.connection); // token metadata const metadata = { uri: "https://raw.githubusercontent.com/solana-developers/program-examples/new-examples/tokens/tokens/.assets/spl-token.json", name: "Solana Gold", symbol: "GOLDSOL", }; // reward token mint PDA const [rewardTokenMintPDA] = anchor.web3.PublicKey.findProgramAddressSync( [Buffer.from("reward")], pg.PROGRAM_ID ); // player data account PDA const [playerPDA] = anchor.web3.PublicKey.findProgramAddressSync( [Buffer.from("player"), pg.wallet.publicKey.toBuffer()], pg.PROGRAM_ID ); // reward token mint metadata account address const rewardTokenMintMetadataPDA = await metaplex .nfts() .pdas() .metadata({ mint: rewardTokenMintPDA }); // player token account address const playerTokenAccount = getAssociatedTokenAddressSync( rewardTokenMintPDA, pg.wallet.publicKey ); async function logTransaction(txHash) { const { blockhash, lastValidBlockHeight } = await pg.connection.getLatestBlockhash(); await pg.connection.confirmTransaction({ blockhash, lastValidBlockHeight, signature: txHash, }); console.log(`Use 'solana confirm -v ${txHash}' to see the logs`); } async function fetchAccountData() { const [playerBalance, playerData] = await Promise.all([ pg.connection.getTokenAccountBalance(playerTokenAccount), pg.program.account.playerData.fetch(playerPDA), ]); console.log("Player Token Balance: ", playerBalance.value.uiAmount); console.log("Player Health: ", playerData.health); } let txHash; try { const mintData = await getMint(pg.connection, rewardTokenMintPDA); console.log("Mint Already Exists"); } catch { txHash = await pg.program.methods .createMint(metadata.uri, metadata.name, metadata.symbol) .accounts({ rewardTokenMint: rewardTokenMintPDA, metadataAccount: rewardTokenMintMetadataPDA, tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID, }) .rpc(); await logTransaction(txHash); } console.log("Token Mint: ", rewardTokenMintPDA.toString()); try { const playerData = await pg.program.account.playerData.fetch(playerPDA); console.log("Player Already Exists"); console.log("Player Health: ", playerData.health); } catch { txHash = await pg.program.methods .initPlayer() .accounts({ playerData: playerPDA, player: pg.wallet.publicKey, }) .rpc(); await logTransaction(txHash); console.log("Player Account Created"); } txHash = await pg.program.methods .killEnemy() .accounts({ playerData: playerPDA, playerTokenAccount: playerTokenAccount, rewardTokenMint: rewardTokenMintPDA, }) .rpc(); await logTransaction(txHash); console.log("Enemy Defeated"); await fetchAccountData(); txHash = await pg.program.methods .heal() .accounts({ playerData: playerPDA, playerTokenAccount: playerTokenAccount, rewardTokenMint: rewardTokenMintPDA, }) .rpc(); await logTransaction(txHash); console.log("Player Healed"); await fetchAccountData();
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BattleCoins
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BattleCoins/files/lib.rs
use anchor_lang::prelude::*; use anchor_spl::{ associated_token::AssociatedToken, metadata::{ create_metadata_accounts_v3, mpl_token_metadata::{accounts::Metadata as MetadataAccount, types::DataV2}, CreateMetadataAccountsV3, Metadata, }, token::{burn, mint_to, Burn, Mint, MintTo, Token, TokenAccount}, }; use solana_program::{pubkey, pubkey::Pubkey}; declare_id!("CCLnXJAJYFjCHLCugpBCEQKrpiSApiRM4UxkBUHJRrv4"); const ADMIN_PUBKEY: Pubkey = pubkey!("REPLACE_WITH_YOUR_WALLET_PUBKEY"); const MAX_HEALTH: u8 = 100; #[program] pub mod anchor_token { use super::*; // Create new token mint with PDA as mint authority pub fn create_mint( ctx: Context<CreateMint>, uri: String, name: String, symbol: String, ) -> Result<()> { // PDA seeds and bump to "sign" for CPI let seeds = b"reward"; let bump = ctx.bumps.reward_token_mint; let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]]; // On-chain token metadata for the mint let data_v2 = DataV2 { name: name, symbol: symbol, uri: uri, seller_fee_basis_points: 0, creators: None, collection: None, uses: None, }; // CPI Context let cpi_ctx = CpiContext::new_with_signer( ctx.accounts.token_metadata_program.to_account_info(), CreateMetadataAccountsV3 { // the metadata account being created metadata: ctx.accounts.metadata_account.to_account_info(), // the mint account of the metadata account mint: ctx.accounts.reward_token_mint.to_account_info(), // the mint authority of the mint account mint_authority: ctx.accounts.reward_token_mint.to_account_info(), // the update authority of the metadata account update_authority: ctx.accounts.reward_token_mint.to_account_info(), // the payer for creating the metadata account payer: ctx.accounts.admin.to_account_info(), // the system program account system_program: ctx.accounts.system_program.to_account_info(), // the rent sysvar account rent: ctx.accounts.rent.to_account_info(), }, signer, ); create_metadata_accounts_v3( cpi_ctx, // cpi context data_v2, // token metadata true, // is_mutable true, // update_authority_is_signer None, // collection details )?; Ok(()) } // Create new player account pub fn init_player(ctx: Context<InitPlayer>) -> Result<()> { ctx.accounts.player_data.health = MAX_HEALTH; Ok(()) } // Mint tokens to player token account pub fn kill_enemy(ctx: Context<KillEnemy>) -> Result<()> { // Check if player has enough health if ctx.accounts.player_data.health == 0 { return err!(ErrorCode::NotEnoughHealth); } // Subtract 10 health from player ctx.accounts.player_data.health = ctx.accounts.player_data.health.checked_sub(10).unwrap(); // PDA seeds and bump to "sign" for CPI let seeds = b"reward"; let bump = ctx.bumps.reward_token_mint; let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]]; // CPI Context let cpi_ctx = CpiContext::new_with_signer( ctx.accounts.token_program.to_account_info(), MintTo { mint: ctx.accounts.reward_token_mint.to_account_info(), to: ctx.accounts.player_token_account.to_account_info(), authority: ctx.accounts.reward_token_mint.to_account_info(), }, signer, ); // Mint 1 token, accounting for decimals of mint let amount = (1u64) .checked_mul(10u64.pow(ctx.accounts.reward_token_mint.decimals as u32)) .unwrap(); mint_to(cpi_ctx, amount)?; Ok(()) } // Burn token to heal player pub fn heal(ctx: Context<Heal>) -> Result<()> { ctx.accounts.player_data.health = MAX_HEALTH; // CPI Context let cpi_ctx = CpiContext::new( ctx.accounts.token_program.to_account_info(), Burn { mint: ctx.accounts.reward_token_mint.to_account_info(), from: ctx.accounts.player_token_account.to_account_info(), authority: ctx.accounts.player.to_account_info(), }, ); // Burn 1 token, accounting for decimals of mint let amount = (1u64) .checked_mul(10u64.pow(ctx.accounts.reward_token_mint.decimals as u32)) .unwrap(); burn(cpi_ctx, amount)?; Ok(()) } } #[derive(Accounts)] pub struct CreateMint<'info> { #[account( mut, address = ADMIN_PUBKEY )] pub admin: Signer<'info>, // The PDA is both the address of the mint account and the mint authority #[account( init, seeds = [b"reward"], bump, payer = admin, mint::decimals = 9, mint::authority = reward_token_mint, )] pub reward_token_mint: Account<'info, Mint>, ///CHECK: Using "address" constraint to validate metadata account address #[account( mut, address = MetadataAccount::find_pda(&reward_token_mint.key()).0, )] pub metadata_account: UncheckedAccount<'info>, pub token_program: Program<'info, Token>, pub token_metadata_program: Program<'info, Metadata>, pub system_program: Program<'info, System>, pub rent: Sysvar<'info, Rent>, } #[derive(Accounts)] pub struct InitPlayer<'info> { #[account( init, payer = player, space = 8 + 8, seeds = [b"player", player.key().as_ref()], bump, )] pub player_data: Account<'info, PlayerData>, #[account(mut)] pub player: Signer<'info>, pub system_program: Program<'info, System>, } #[derive(Accounts)] pub struct KillEnemy<'info> { #[account(mut)] pub player: Signer<'info>, #[account( mut, seeds = [b"player", player.key().as_ref()], bump, )] pub player_data: Account<'info, PlayerData>, // Initialize player token account if it doesn't exist #[account( init_if_needed, payer = player, associated_token::mint = reward_token_mint, associated_token::authority = player )] pub player_token_account: Account<'info, TokenAccount>, #[account( mut, seeds = [b"reward"], bump, )] pub reward_token_mint: Account<'info, Mint>, pub token_program: Program<'info, Token>, pub associated_token_program: Program<'info, AssociatedToken>, pub system_program: Program<'info, System>, } #[derive(Accounts)] pub struct Heal<'info> { #[account(mut)] pub player: Signer<'info>, #[account( mut, seeds = [b"player", player.key().as_ref()], bump, )] pub player_data: Account<'info, PlayerData>, #[account( mut, associated_token::mint = reward_token_mint, associated_token::authority = player )] pub player_token_account: Account<'info, TokenAccount>, #[account( mut, seeds = [b"reward"], bump, )] pub reward_token_mint: Account<'info, Mint>, pub token_program: Program<'info, Token>, pub associated_token_program: Program<'info, AssociatedToken>, } #[account] pub struct PlayerData { pub health: u8, } #[error_code] pub enum ErrorCode { #[msg("Not enough health")] NotEnoughHealth, }
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BankSimulator/BankSimulator.tsx
import { Tutorial } from "../../components/Tutorial"; const ExpenseTracker = () => ( <Tutorial // About section that will be shown under the description of the tutorial page about={require("./about.md")} // Actual tutorial pages to show next to the editor pages={[ { content: require("./pages/1.md") }, { content: require("./pages/2.md") }, { content: require("./pages/3.md") }, { content: require("./pages/4.md") }, { content: require("./pages/5.md") }, ]} // Initial files to have at the beginning of the tutorial files={[ ["src/lib.rs", require("./files/lib.rs")], ["tests/index.test.ts", require("./files/index.test.ts.raw")], ]} /> ); export default ExpenseTracker;
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BankSimulator/index.ts
export { default } from "./BankSimulator";
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BankSimulator
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BankSimulator/files/lib.rs
use anchor_lang::prelude::*; use anchor_lang::solana_program::{instruction::Instruction}; use anchor_lang::InstructionData; use clockwork_sdk::state::{Thread, ThreadAccount}; // Your program Id will be added here when you enter "build" command declare_id!(""); // Calculating interest per minute instead of anually for faster results const MINUTE_INTEREST: f64 = 0.05; // 5% interest return const CRON_SCHEDULE: &str = "*/10 * * * * * *"; // 10s https://crontab.guru/ const AUTOMATION_FEE: u64 = 5000000; // https://docs.clockwork.xyz/developers/threads/fees pub const BANK_ACCOUNT_SEED: &[u8] = b"bank_account"; pub const THREAD_AUTHORITY_SEED: &[u8] = b"authority"; #[program] pub mod bank_simulator { use super::*; pub fn initialize_account( ctx: Context<Initialize>, thread_id: Vec<u8>, holder_name: String, balance: f64, ) -> Result<()> { let system_program = &ctx.accounts.system_program; let clockwork_program = &ctx.accounts.clockwork_program; let holder = &ctx.accounts.holder; let bank_account = &mut ctx.accounts.bank_account; let thread = &ctx.accounts.thread; let thread_authority = &ctx.accounts.thread_authority; bank_account.thread_id = thread_id.clone(); bank_account.holder = *holder.key; bank_account.balance = balance; bank_account.holder_name = holder_name; bank_account.created_at = Clock::get().unwrap().unix_timestamp; // Clockwork Target Instruction let target_ix = Instruction { program_id: ID, accounts: crate::accounts::AddInterest { bank_account: bank_account.key(), thread: thread.key(), thread_authority: thread_authority.key(), } .to_account_metas(Some(true)), data: crate::instruction::AddInterest { _thread_id: thread_id.clone(), } .data(), }; // Clockwork Trigger let trigger = clockwork_sdk::state::Trigger::Cron { schedule: CRON_SCHEDULE.to_string(), skippable: true, }; // Clockwork thread CPI let bump = ctx.bumps.thread_authority; clockwork_sdk::cpi::thread_create( CpiContext::new_with_signer( clockwork_program.to_account_info(), clockwork_sdk::cpi::ThreadCreate { payer: holder.to_account_info(), system_program: system_program.to_account_info(), thread: thread.to_account_info(), authority: thread_authority.to_account_info(), }, &[&[THREAD_AUTHORITY_SEED, &[bump]]], ), AUTOMATION_FEE, thread_id, vec![target_ix.into()], trigger, )?; Ok(()) } pub fn deposit(ctx: Context<UpdateBalance>, _thread_id: Vec<u8>, amount: f64) -> Result<()> { if amount < 0.0 { return Err(error!(ErrorCode::AmountTooSmall)); }; let bank_account = &mut ctx.accounts.bank_account; bank_account.balance += amount; Ok(()) } pub fn withdraw(ctx: Context<UpdateBalance>, _thread_id: Vec<u8>, amount: f64) -> Result<()> { let bank_account = &mut ctx.accounts.bank_account; if amount > bank_account.balance { return Err(error!(ErrorCode::AmountTooBig)); }; bank_account.balance -= amount; Ok(()) } pub fn add_interest(ctx: Context<AddInterest>, _thread_id: Vec<u8>) -> Result<()> { let now = Clock::get().unwrap().unix_timestamp; let bank_account = &mut ctx.accounts.bank_account; bank_account.updated_at = now; let elapsed_time = (now - bank_account.created_at) as f64; let minutes = elapsed_time / 60.0; let accumulated_value = bank_account.balance * (1.0 + (MINUTE_INTEREST)).powf(minutes); bank_account.balance = accumulated_value; msg!( "New Balance: {}, Minutes Elasped when Called: {}", accumulated_value, minutes, ); Ok(()) } pub fn remove_account(ctx: Context<RemoveAccount>, _thread_id: Vec<u8>) -> Result<()> { let clockwork_program = &ctx.accounts.clockwork_program; let holder = &ctx.accounts.holder; let thread = &ctx.accounts.thread; let thread_authority = &ctx.accounts.thread_authority; // Delete thread via CPI let bump = ctx.bumps.thread_authority; clockwork_sdk::cpi::thread_delete(CpiContext::new_with_signer( clockwork_program.to_account_info(), clockwork_sdk::cpi::ThreadDelete { authority: thread_authority.to_account_info(), close_to: holder.to_account_info(), thread: thread.to_account_info(), }, &[&[THREAD_AUTHORITY_SEED, &[bump]]], ))?; Ok(()) } } #[derive(Accounts)] #[instruction(thread_id: Vec<u8>)] pub struct Initialize<'info> { #[account(mut)] pub holder: Signer<'info>, #[account( init, payer = holder, seeds = [BANK_ACCOUNT_SEED, thread_id.as_ref()], bump, space = 8 + std::mem::size_of::<BankAccount>(), )] pub bank_account: Account<'info, BankAccount>, #[account(mut, address = Thread::pubkey(thread_authority.key(), thread_id))] pub thread: SystemAccount<'info>, #[account(seeds = [THREAD_AUTHORITY_SEED], bump)] pub thread_authority: SystemAccount<'info>, #[account(address = clockwork_sdk::ID)] pub clockwork_program: Program<'info, clockwork_sdk::ThreadProgram>, pub system_program: Program<'info, System>, } #[derive(Accounts)] #[instruction(thread_id: Vec<u8>)] pub struct UpdateBalance<'info> { #[account(mut)] pub holder: Signer<'info>, #[account(mut, seeds = [BANK_ACCOUNT_SEED, thread_id.as_ref()], bump)] pub bank_account: Account<'info, BankAccount>, pub system_program: Program<'info, System>, } #[derive(Accounts)] #[instruction(thread_id: Vec<u8>)] pub struct AddInterest<'info> { #[account(mut, seeds = [BANK_ACCOUNT_SEED, thread_id.as_ref()], bump)] pub bank_account: Account<'info, BankAccount>, #[account(signer, constraint = thread.authority.eq(&thread_authority.key()))] pub thread: Account<'info, Thread>, #[account(seeds = [THREAD_AUTHORITY_SEED], bump)] pub thread_authority: SystemAccount<'info>, } #[derive(Accounts)] #[instruction(thread_id : Vec<u8>)] pub struct RemoveAccount<'info> { #[account(mut)] pub holder: Signer<'info>, #[account( mut, seeds = [BANK_ACCOUNT_SEED, thread_id.as_ref()], bump, close = holder )] pub bank_account: Account<'info, BankAccount>, #[account(mut, address = thread.pubkey(), constraint = thread.authority.eq(&thread_authority.key()))] pub thread: Account<'info, Thread>, #[account(seeds = [THREAD_AUTHORITY_SEED], bump)] pub thread_authority: SystemAccount<'info>, #[account(address = clockwork_sdk::ID)] pub clockwork_program: Program<'info, clockwork_sdk::ThreadProgram>, } #[account] #[derive(Default)] pub struct BankAccount { pub holder: Pubkey, pub holder_name: String, pub balance: f64, pub thread_id: Vec<u8>, pub created_at: i64, pub updated_at: i64, } #[error_code] pub enum ErrorCode { #[msg("Amount must be greater than zero")] AmountTooSmall, #[msg("Withdraw amount cannot be less than deposit")] AmountTooBig, }
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BankSimulator
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/BankSimulator/files/index.test.ts.raw
import { ClockworkProvider } from "@clockwork-xyz/sdk"; describe("Bank Simulator", async () => { const threadId = "bank_account-1"; const holderName = "test"; const balance = 10.0; const clockworkProvider = ClockworkProvider.fromAnchorProvider( pg.program.provider ); const [bankAccount] = anchor.web3.PublicKey.findProgramAddressSync( [Buffer.from("bank_account"), Buffer.from(threadId)], pg.program.programId ); const [threadAuthority] = anchor.web3.PublicKey.findProgramAddressSync( [anchor.utils.bytes.utf8.encode("authority")], pg.program.programId ); const [threadAddress] = clockworkProvider.getThreadPDA( threadAuthority, threadId ); console.log("Thread ID: ", threadId); console.log("Bank Account: ", bankAccount.toBase58()); console.log("Thread Authority: ", threadAuthority.toBase58()); console.log("Thread Address: ", threadAddress.toBase58()); console.log( "Clockwork Program: ", clockworkProvider.threadProgram.programId.toBase58() ); it("Create Account", async () => { await pg.program.methods .initializeAccount( Buffer.from(threadId), holderName, Number(balance.toFixed(2)) ) .accounts({ holder: pg.wallet.publicKey, bankAccount: bankAccount, clockworkProgram: clockworkProvider.threadProgram.programId, thread: threadAddress, threadAuthority: threadAuthority, }) .rpc(); }); it("Deposit Amount", async () => { await pg.program.methods .deposit(Buffer.from(threadId), balance) .accounts({ bankAccount: bankAccount, holder: pg.wallet.publicKey, }) .rpc(); }); it("Withdraw Amount", async () => { await pg.program.methods .withdraw(Buffer.from(threadId), balance) .accounts({ bankAccount: bankAccount, holder: pg.wallet.publicKey, }) .rpc(); }); it("Delete Account", async () => { await pg.program.methods .removeAccount(Buffer.from(threadId)) .accounts({ holder: pg.wallet.publicKey, bankAccount: bankAccount, thread: threadAddress, threadAuthority: threadAuthority, clockworkProgram: clockworkProvider.threadProgram.programId, }) .rpc(); }); });
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/SplTokenVault/SplTokenVault.tsx
import { Tutorial } from "../../components/Tutorial"; const SplTokenVault = () => ( <Tutorial // About section that will be shown under the description of the tutorial page about={require("./about.md")} // Actual tutorial pages to show next to the editor pages={[ { content: require("./pages/1.md") }, { content: require("./pages/2.md") }, { content: require("./pages/3.md") }, { content: require("./pages/4.md") }, { content: require("./pages/5.md") }, { content: require("./pages/6.md") }, { content: require("./pages/7.md") }, ]} // Initial files to have at the beginning of the tutorial files={[ ["src/lib.rs", require("./files/lib.rs")], ["client/client.ts", require("./files/client.ts.raw")], ]} /> ); export default SplTokenVault;
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/SplTokenVault/index.ts
export { default } from "./SplTokenVault";
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/SplTokenVault
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/SplTokenVault/files/client.ts.raw
import { getAccount, getOrCreateAssociatedTokenAccount, } from "@solana/spl-token"; import { PublicKey } from "@solana/web3.js"; import { keypairIdentity, token, Metaplex } from "@metaplex-foundation/js"; const mintAuthority = pg.wallet.keypair; const decimals = 9; let [tokenAccountOwnerPda] = PublicKey.findProgramAddressSync( [Buffer.from("token_account_owner_pda")], pg.PROGRAM_ID ); const metaplex = new Metaplex(pg.connection).use( keypairIdentity(pg.wallet.keypair) ); const createdSFT = await metaplex.nfts().createSft({ uri: "https://shdw-drive.genesysgo.net/AzjHvXgqUJortnr5fXDG2aPkp2PfFMvu4Egr57fdiite/PirateCoinMeta", name: "Gold", symbol: "GOLD", sellerFeeBasisPoints: 100, updateAuthority: mintAuthority, mintAuthority: mintAuthority, decimals: decimals, tokenStandard: "Fungible", isMutable: true, }); console.log( "Creating semi fungible spl token with address: " + createdSFT.sft.address ); const mintDecimals = Math.pow(10, decimals); let mintResult = await metaplex.nfts().mint({ nftOrSft: createdSFT.sft, authority: pg.wallet.keypair, toOwner: pg.wallet.keypair.publicKey, amount: token(100 * mintDecimals), }); console.log("Mint to result: " + mintResult.response.signature); const tokenAccount = await getOrCreateAssociatedTokenAccount( pg.connection, pg.wallet.keypair, createdSFT.mintAddress, pg.wallet.keypair.publicKey ); console.log("tokenAccount: " + tokenAccount.address); console.log("TokenAccountOwnerPda: " + tokenAccountOwnerPda); let tokenAccountInfo = await getAccount(pg.connection, tokenAccount.address); console.log( "Owned token amount: " + tokenAccountInfo.amount / BigInt(mintDecimals) ); let [tokenVault] = PublicKey.findProgramAddressSync( [Buffer.from("token_vault"), createdSFT.mintAddress.toBuffer()], pg.PROGRAM_ID ); console.log("VaultAccount: " + tokenVault); let confirmOptions = { skipPreflight: true, }; let txHash = await pg.program.methods .initialize() .accounts({ tokenAccountOwnerPda: tokenAccountOwnerPda, vaultTokenAccount: tokenVault, senderTokenAccount: tokenAccount.address, mintOfTokenBeingSent: createdSFT.mintAddress, signer: pg.wallet.publicKey, }) .rpc(confirmOptions); console.log(`Initialize`); await logTransaction(txHash); console.log(`Vault initialized.`); tokenAccountInfo = await getAccount(pg.connection, tokenAccount.address); console.log( "Owned token amount: " + tokenAccountInfo.amount / BigInt(mintDecimals) ); tokenAccountInfo = await getAccount(pg.connection, tokenVault); console.log( "Vault token amount: " + tokenAccountInfo.amount / BigInt(mintDecimals) ); async function logTransaction(txHash) { const { blockhash, lastValidBlockHeight } = await pg.connection.getLatestBlockhash(); await pg.connection.confirmTransaction({ blockhash, lastValidBlockHeight, signature: txHash, }); console.log( `Solana Explorer: https://explorer.solana.com/tx/${txHash}?cluster=devnet` ); }
0
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/SplTokenVault
solana_public_repos/solana-playground/solana-playground/client/src/tutorials/SplTokenVault/files/lib.rs
use anchor_lang::prelude::*; use anchor_spl::token::{Mint, Token, TokenAccount}; // This is your program's public key and it will update // automatically when you build the project. declare_id!("HCLBrPG3A9agLsVE3j1BCBRUfv9jc1juk5Wt888ZDDsV"); #[program] mod token_vault { use super::*; pub fn initialize(_ctx: Context<Initialize>) -> Result<()> { Ok(()) } pub fn transfer_in(_ctx: Context<TransferAccounts>, amount: u64) -> Result<()> { msg!("Token amount transfer in: {}!", amount); // See Tutorial page 6 Ok(()) } pub fn transfer_out(_ctx: Context<TransferAccounts>, amount: u64) -> Result<()> { msg!("Token amount transfer out: {}!", amount); // See Tutorial page 7 Ok(()) } } #[derive(Accounts)] pub struct Initialize<'info> { // Derived PDAs #[account( init_if_needed, payer = signer, seeds=[b"token_account_owner_pda"], bump, space = 8 )] token_account_owner_pda: AccountInfo<'info>, #[account( init_if_needed, payer = signer, seeds=[b"token_vault", mint_of_token_being_sent.key().as_ref()], token::mint=mint_of_token_being_sent, token::authority=token_account_owner_pda, bump )] vault_token_account: Account<'info, TokenAccount>, mint_of_token_being_sent: Account<'info, Mint>, #[account(mut)] signer: Signer<'info>, system_program: Program<'info, System>, token_program: Program<'info, Token>, rent: Sysvar<'info, Rent>, } #[derive(Accounts)] pub struct TransferAccounts<'info> { // Derived PDAs #[account(mut, seeds=[b"token_account_owner_pda"], bump )] token_account_owner_pda: AccountInfo<'info>, #[account(mut, seeds=[b"token_vault", mint_of_token_being_sent.key().as_ref()], bump, token::mint=mint_of_token_being_sent, token::authority=token_account_owner_pda, )] vault_token_account: Account<'info, TokenAccount>, #[account(mut)] sender_token_account: Account<'info, TokenAccount>, mint_of_token_being_sent: Account<'info, Mint>, #[account(mut)] signer: Signer<'info>, system_program: Program<'info, System>, token_program: Program<'info, Token>, rent: Sysvar<'info, Rent>, }
0