├── .env.example
├── .eslintrc.json
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── components
├── account
│ └── tokens.tsx
├── layout.tsx
├── nav.tsx
├── notifications
│ └── success.tsx
├── program-mini-card.tsx
├── program
│ ├── accounts-data
│ │ ├── account-selector.tsx
│ │ ├── filter.tsx
│ │ └── index.tsx
│ ├── builds.tsx
│ ├── idl-viewer.tsx
│ ├── idl
│ │ ├── accounts.tsx
│ │ ├── constants.tsx
│ │ ├── errors.tsx
│ │ ├── events.tsx
│ │ ├── instructions.tsx
│ │ └── types.tsx
│ ├── index.tsx
│ ├── metadata.tsx
│ ├── program-banner.tsx
│ ├── readme.tsx
│ ├── source-files.tsx
│ ├── source.tsx
│ └── tabs.tsx
├── search.tsx
└── status.tsx
├── context
├── AutoConnectProvider.tsx
└── ContextProvider.tsx
├── hooks
└── useAuth.ts
├── next-env.d.ts
├── next.config.js
├── package.json
├── pages
├── 404.tsx
├── _app.tsx
├── _document.tsx
├── _error.js
├── account.tsx
├── api
│ ├── auth
│ │ └── [...nextauth].js
│ ├── idl.ts
│ ├── keys.ts
│ └── user.ts
├── idl
│ └── [address].tsx
├── index.tsx
└── program
│ └── [address]
│ ├── build
│ └── [id].tsx
│ └── index.tsx
├── postcss.config.js
├── public
├── banner-text copy.png
├── banner-text.png
├── boxes.png
├── favicon.ico
├── logo.png
├── missing.png
└── social.png
├── sentry.client.config.js
├── sentry.properties
├── sentry.server.config.js
├── src
├── Copyright.tsx
├── ProTip.tsx
├── createEmotionCache.ts
└── theme.ts
├── style.css
├── tailwind.config.js
├── tsconfig.json
├── types
├── index.d.ts
└── next-auth.d.ts
├── utils
├── apps-data.json
├── build-status.ts
├── fetcher-md.js
├── fetcher-multi.js
├── fetcher.js
├── files-tree.ts
├── format-date.ts
├── from-now.js
├── loadMoreApps.js
├── markdown.js
├── network-status.ts
└── renderArguments.tsx
└── yarn.lock
/.env.example:
--------------------------------------------------------------------------------
1 | NEXT_PUBLIC_API_ENDPOINT=urlgoeshere
2 | NEXT_PUBLIC_NETWORK_ENV=devnet
3 | NEXTAUTH_URL=http://localhost:3000
4 | NEXT_PUBLIC_SENTRY_DSN=
5 | SENTRY_AUTH_TOKEN=
6 | SENTRY_ORG=
7 | SENTRY_PROJECT=
8 | NEXT_PUBLIC_NODE_URL=https://ssc-dao.genesysgo.net/
9 | SKIP_BUILD_STATIC_GENERATION=true
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": [
3 | "next/core-web-vitals",
4 | "prettier"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # next.js
12 | /.next/
13 | /out/
14 |
15 | # production
16 | /build
17 |
18 | # misc
19 | .DS_Store
20 | *.pem
21 |
22 | # debug
23 | npm-debug.log*
24 | yarn-debug.log*
25 | yarn-error.log*
26 |
27 | # local env files
28 | .env.local
29 | .env.development.local
30 | .env.test.local
31 | .env.production.local
32 |
33 | # vercel
34 | .vercel
35 |
36 | .idea
37 | # Sentry
38 | .sentryclirc
39 |
40 | # Sentry
41 | .sentryclirc
42 |
43 | # Sentry
44 | .sentryclirc
45 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Anchor
2 |
3 | Thank you for your interest in contributing to apr! All contributions are welcome no
4 | matter how big or small. This includes (but is not limited to) filing issues,
5 | adding documentation, fixing bugs, creating examples, and implementing features.
6 |
7 | ## Finding issues to work on
8 |
9 | If you're looking to get started,
10 | check out [good first issues](https://github.com/coral-xyz/apr-ui/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
11 | or issues where [help is wanted](https://github.com/coral-xyz/apr-ui/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22).
12 | For simple documentation changes or typos, feel free to just open a pull request.
13 |
14 | If you're considering larger changes or self motivated features, please file an issue
15 | and engage with the maintainers in [Discord](https://discord.gg/sxy4zxBckh).
16 |
17 | ## Choosing an issue
18 |
19 | If you'd like to contribute, please claim an issue by commenting, forking, and
20 | opening a pull request, even if empty. This allows the maintainers to track who
21 | is working on what issue as to not overlap work.
22 |
23 | ## Issue Guidelines
24 |
25 | Please follow these guidelines:
26 |
27 | Before coding:
28 |
29 | - choose a branch name that describes the issue you're working on
30 | - enable [commit signing](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits)
31 |
32 | While coding:
33 |
34 | - Submit a draft PR asap
35 | - Only change code directly relevant to your PR. Sometimes you might find some code that could really need some refactoring. However, if it's not relevant to your PR, do not touch it. File an issue instead. This allows the reviewer to focus on a single problem at a time.
36 | - If you write comments, do not exceed 80 chars per line. This allows contributors who work with multiple open windows to still read the comments without horizontally scrolling.
37 | - Write adversarial tests. For example, if you're adding a new account type, do not only write tests where the instruction succeeds. Also write tests that test whether the instruction fails, if a check inside the new type is violated.
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2020 Serum Foundation
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
Anchor Program Registry "apr"
5 |
6 |
7 | Solana's program registry
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | ## Public Roadmap
17 |
18 | - https://github.com/orgs/coral-xyz/projects/1
19 |
20 | ## Getting Started
21 |
22 | 1. Install dependencies
23 | 2. `cp .env.example .env.local`
24 | 3. Change `NEXT_PUBLIC_API_ENDPOINT` value (ex. `https://api.apr.dev`)
25 | 4. yarn dev
26 | 5. open browser `http://localhost:3000`
27 |
28 | ### `NEXT_PUBLIC_API_ENDPOINT` env var
29 |
30 | Ask @italoacasas or @armaniferrante in Discord or Twitter.
31 |
32 | ## TailwindCSS & Material UI
33 |
34 | All new components should use TailwindCSS and not Material UI. The goal is to remove Material UI from the project.
35 |
36 | ## APR API
37 |
38 | apr codebase possesses two projects, the UI (Next.js) and the API (Rust). The API will be open source at a later date.
39 |
--------------------------------------------------------------------------------
/components/account/tokens.tsx:
--------------------------------------------------------------------------------
1 | import { memo, useState } from "react";
2 | import { styled } from "@mui/material/styles";
3 | import Table from "@mui/material/Table";
4 | import TableBody from "@mui/material/TableBody";
5 | import TableCell, { tableCellClasses } from "@mui/material/TableCell";
6 | import TableContainer from "@mui/material/TableContainer";
7 | import TableHead from "@mui/material/TableHead";
8 | import TableRow from "@mui/material/TableRow";
9 | import Paper from "@mui/material/Paper";
10 | import { Box, Button, InputAdornment, TextField } from "@mui/material";
11 | import useSWR from "swr";
12 | import fetcher from "../../utils/fetcher";
13 | import formatDate from "../../utils/format-date";
14 | import { Key } from "@mui/icons-material";
15 |
16 | const StyledTableCell = styled(TableCell)(({ theme }) => ({
17 | [`&.${tableCellClasses.head}`]: {
18 | backgroundColor: theme.palette.grey["700"],
19 | color: theme.palette.common.white,
20 | },
21 | [`&.${tableCellClasses.body}`]: {
22 | fontSize: 14,
23 | },
24 | }));
25 |
26 | const StyledTableRow = styled(TableRow)(({ theme }) => ({
27 | "&:nth-of-type(odd)": {
28 | backgroundColor: theme.palette.action.hover,
29 | },
30 | // hide last border
31 | "&:last-child td, &:last-child th": {
32 | border: 0,
33 | },
34 | }));
35 |
36 | /**
37 | * Delete specific access token
38 | * @param id access token key id
39 | */
40 | async function deleteTokenOnClick(id: string) {
41 | await fetch(`/api/keys/`, {
42 | method: "DELETE",
43 | body: JSON.stringify({ id }),
44 | });
45 | }
46 |
47 | function Tokens() {
48 | const [accessTokenName, setAccessTokenName] = useState("");
49 | const [accessTokenError, setAccessTokenError] = useState(false);
50 | const [newAccessToken, setNewAccessToken] = useState("");
51 | const { data: keys = [] } = useSWR("/api/keys", fetcher, {
52 | refreshInterval: 5000,
53 | });
54 |
55 | async function generateNewTokenOnClick() {
56 | if (accessTokenName.length === 0) {
57 | setAccessTokenError(true);
58 | return;
59 | }
60 |
61 | setAccessTokenError(false);
62 |
63 | const response = await fetch("/api/keys/", {
64 | method: "POST",
65 | body: JSON.stringify({ name: accessTokenName }),
66 | });
67 |
68 | const data = await response.json();
69 |
70 | setNewAccessToken(data.plaintext);
71 | }
72 | return (
73 | <>
74 |
75 |
76 | {newAccessToken && (
77 |
87 |
88 |
89 | ),
90 | }}
91 | />
92 | )}
93 |
94 |
95 |
102 | setAccessTokenName(e.target.value)}
111 | />
112 | generateNewTokenOnClick()}
114 | className="rounded-md bg-gray-900 py-3 px-5 text-sm uppercase text-gray-100"
115 | >
116 | Generate new Access Token
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 | Token
126 | Name
127 | Created
128 | Delete
129 |
130 |
131 |
132 | {keys.map((row) => (
133 |
134 | {row.token_name}
135 | {row.name}
136 |
137 | {formatDate(row.created_at)}
138 |
139 |
140 | deleteTokenOnClick(row.id)}
146 | >
147 | Delete
148 |
149 |
150 |
151 | ))}
152 |
153 |
154 |
155 | >
156 | );
157 | }
158 |
159 | interface TokensProps {
160 | keys: Token[];
161 | }
162 |
163 | interface Token {
164 | token_name: string;
165 | id: string;
166 | name: string;
167 | created_at: string;
168 | }
169 |
170 | export default memo(Tokens);
171 |
--------------------------------------------------------------------------------
/components/layout.tsx:
--------------------------------------------------------------------------------
1 | import Head from "next/head";
2 |
3 | export default function Layout({ children, metaTags }) {
4 | return (
5 | <>
6 |
7 | {metaTags.title}
8 |
9 |
10 |
11 | {/* Google */}
12 | {metaTags.shouldIndex ? (
13 | <>
14 | {" "}
15 |
16 |
17 | >
18 | ) : (
19 | <>
20 |
21 |
22 | >
23 | )}
24 |
25 | {/* Open Graph */}
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | {/* Twitter */}
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | {children}
45 | >
46 | );
47 | }
48 |
--------------------------------------------------------------------------------
/components/nav.tsx:
--------------------------------------------------------------------------------
1 | import { Fragment, memo, useEffect, useState } from "react";
2 | import { Disclosure, Menu, Transition } from "@headlessui/react";
3 | import { UserCircleIcon } from "@heroicons/react/solid";
4 | import {
5 | DuplicateIcon,
6 | ExternalLinkIcon,
7 | IdentificationIcon,
8 | LinkIcon,
9 | LogoutIcon,
10 | MenuIcon,
11 | SearchIcon,
12 | XIcon,
13 | } from "@heroicons/react/outline";
14 | import { GlobalHotKeys } from "react-hotkeys";
15 | import Image from "next/image";
16 | import { useWallet } from "@solana/wallet-adapter-react";
17 | import { useWalletModal } from "@solana/wallet-adapter-react-ui";
18 | import Link from "next/link";
19 | import dynamic from "next/dynamic";
20 | import { useRouter } from "next/router";
21 | import useSWR from "swr";
22 | import { signIn, signOut, useSession } from "next-auth/react";
23 | import bs58 from "bs58";
24 | import fetcher from "../utils/fetcher";
25 |
26 | const Search = dynamic(() => import("./search"));
27 |
28 | function classNames(...classes: any) {
29 | return classes.filter(Boolean).join(" ");
30 | }
31 |
32 | function Nav() {
33 | const [showSearch, setShowSearch] = useState(false);
34 | const { data = [], error } = useSWR(
35 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/programs/latest`,
36 | fetcher
37 | );
38 | const [anchorEl, setAnchorEl] = useState(null);
39 | const { pathname } = useRouter();
40 | const { data: session, status } = useSession();
41 | const { wallet, publicKey, signMessage, connected } = useWallet();
42 | const { setVisible } = useWalletModal();
43 |
44 | const keyMap = {
45 | SEARCH: "command+k",
46 | };
47 |
48 | const handlers = {
49 | SEARCH: () => setShowSearch(true),
50 | };
51 |
52 | useEffect(() => {
53 | async function login() {
54 | const message = `Sign this message for authenticating with your wallet`;
55 | const encodedMessage = new TextEncoder().encode(message);
56 | try {
57 | const signedMessage = await signMessage(encodedMessage);
58 |
59 | signIn("credentials", {
60 | publicKey: publicKey,
61 | signature: bs58.encode(signedMessage),
62 | callbackUrl: `${window.location.origin}/`,
63 | });
64 | } catch (error) {
65 | console.error(error);
66 | }
67 | }
68 |
69 | if (connected && status === "unauthenticated") login();
70 | }, [wallet, status, publicKey, connected, signMessage]);
71 |
72 | const open = Boolean(anchorEl);
73 | const handleClick = (event: React.MouseEvent) => {
74 | setAnchorEl(event.currentTarget);
75 | };
76 | const handleClose = () => {
77 | setAnchorEl(null);
78 | };
79 |
80 | return (
81 | <>
82 |
83 | {({ open }) => (
84 | <>
85 |
86 |
87 |
88 | {/* Logo */}
89 |
90 |
91 |
97 |
98 |
99 |
100 |
101 | {/* Search */}
102 | {pathname !== "/" && (
103 |
104 |
105 |
106 |
setShowSearch(true)}
108 | className="shadow-xs flex h-12 w-full cursor-text items-center
109 | justify-between rounded-md border border-gray-700 bg-gray-700 px-5 shadow focus:outline-none"
110 | >
111 |
112 |
116 |
117 | Search by name or address
118 |
119 |
120 |
121 |
122 | ⌘K
123 |
124 |
125 |
126 |
127 |
128 |
129 | )}
130 |
131 | {/* Actions */}
132 |
133 |
139 | Docs
140 |
141 |
142 |
143 | {/* Wallet not connected */}
144 | {status === "unauthenticated" && (
145 |
setVisible(true)}
149 | >
150 |
151 | Login with Wallet
152 |
153 | )}
154 |
155 | {/* Wallet Connected desktop */}
156 | {status === "authenticated" && (
157 |
158 |
159 | {/* Auth or Profile */}
160 |
161 |
162 |
163 | Open user menu
164 |
165 |
166 |
167 |
176 |
181 |
182 | {({ active }) => (
183 |
184 | Connected as
185 |
186 | {publicKey && (
187 | <>
188 | {publicKey.toBase58().slice(0, 6)}...
189 | {publicKey.toBase58().slice(-4)}
190 | >
191 | )}
192 |
193 |
194 | )}
195 |
196 |
197 | {({ active }) => (
198 |
199 |
205 |
206 | My Account
207 |
208 |
209 | )}
210 |
211 |
212 | {({ active }) => (
213 | {
219 | navigator.clipboard.writeText(
220 | publicKey.toBase58()
221 | );
222 | }}
223 | >
224 |
225 | Copy Address
226 |
227 | )}
228 |
229 |
230 | {({ active }) => (
231 | signOut()}
233 | className={classNames(
234 | active ? "bg-gray-100" : "",
235 | "block flex w-full flex-row gap-2 border-t px-4 py-2 text-sm text-gray-900"
236 | )}
237 | >
238 |
239 | Disconnect
240 |
241 | )}
242 |
243 |
244 |
245 |
246 |
247 |
248 | )}
249 |
250 | {/* Mobile menu button */}
251 | {status === "authenticated" && (
252 |
253 |
258 | Open main menu
259 | {open ? (
260 |
261 | ) : (
262 |
266 | )}
267 |
268 |
269 | )}
270 |
271 |
272 |
273 |
274 |
275 | {/* Connected menu, mobile version */}
276 | {status === "authenticated" && (
277 |
278 |
279 |
280 |
281 | Connected as
282 |
283 |
284 | {publicKey && (
285 | <>
286 | {publicKey.toBase58().slice(0, 6)}...
287 | {publicKey.toBase58().slice(-4)}
288 | >
289 | )}
290 |
291 |
292 |
293 |
294 |
299 |
300 |
301 |
302 | My Account
303 |
304 |
305 |
306 |
307 |
{
312 | navigator.clipboard.writeText(publicKey.toBase58());
313 | }}
314 | >
315 |
316 | Copy Address
317 |
318 |
signOut()}
323 | >
324 |
325 | Disconnect
326 |
327 |
328 | )}
329 |
330 | >
331 | )}
332 |
333 | {showSearch && (
334 |
335 | )}
336 | >
337 | );
338 | }
339 |
340 | export default memo(Nav);
341 |
--------------------------------------------------------------------------------
/components/notifications/success.tsx:
--------------------------------------------------------------------------------
1 | import { Dispatch, Fragment, memo, SetStateAction } from "react";
2 | import { Transition } from "@headlessui/react";
3 | import { CheckCircleIcon } from "@heroicons/react/outline";
4 | import { XIcon } from "@heroicons/react/solid";
5 |
6 | function Notification({
7 | show,
8 | setShow,
9 | message,
10 | subText,
11 | }: {
12 | show: boolean;
13 | setShow: Dispatch>;
14 | message: string;
15 | subText: string;
16 | }) {
17 | return (
18 |
22 |
23 |
33 |
34 |
35 |
36 |
37 |
41 |
42 |
43 |
{message}
44 |
{subText}
45 |
46 |
47 | {
51 | setShow(false);
52 | }}
53 | >
54 | Close
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | );
65 | }
66 |
67 | export default memo(Notification);
68 |
--------------------------------------------------------------------------------
/components/program-mini-card.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import Link from "next/link";
3 |
4 | function ProgramMiniCard({ name, address, id }: ProgramMiniCardProps) {
5 | const programUrl: string = id
6 | ? `/program/${address}/build/${id}`
7 | : `/program/${address}`;
8 |
9 | return (
10 |
11 |
12 |
13 | {/* Program Name */}
14 |
{name}
15 |
16 |
17 | {/* Program Address */}
18 |
{address}
19 |
20 |
21 | );
22 | }
23 |
24 | interface ProgramMiniCardProps {
25 | name: string;
26 | address: string;
27 | id: string | boolean;
28 | }
29 |
30 | export default memo(ProgramMiniCard);
31 |
--------------------------------------------------------------------------------
/components/program/accounts-data/account-selector.tsx:
--------------------------------------------------------------------------------
1 | import { memo, useState } from "react";
2 | import { CheckIcon, SelectorIcon } from "@heroicons/react/solid";
3 | import { Combobox } from "@headlessui/react";
4 |
5 | function classNames(...classes) {
6 | return classes.filter(Boolean).join(" ");
7 | }
8 |
9 | function AccountSelector({
10 | accounts,
11 | selectedAccount,
12 | setSelectedAccount,
13 | setCurrentPage,
14 | }: AccountSelectorProps) {
15 | const [query, setQuery] = useState("");
16 |
17 | const filteredAccounts =
18 | query === ""
19 | ? accounts
20 | : accounts.filter((account) => {
21 | return account.toLowerCase().includes(query.toLowerCase());
22 | });
23 |
24 | return (
25 | {
30 | setSelectedAccount(account);
31 | setCurrentPage(0);
32 | }}
33 | >
34 |
35 | Account
36 |
37 |
38 |
setQuery(event.target.value)}
42 | displayValue={(account) => account}
43 | />
44 |
45 |
46 |
47 |
48 | {filteredAccounts.length > 0 && (
49 |
50 | {filteredAccounts.map((account) => (
51 |
55 | classNames(
56 | "relative cursor-default select-none py-2 pl-3 pr-9",
57 | active ? "bg-amber-500 text-white" : "text-gray-900"
58 | )
59 | }
60 | >
61 | {({ active, selected }) => (
62 | <>
63 |
64 | {/* TODO: icon */}
65 |
71 | {account}
72 |
73 |
74 |
75 | {selected && (
76 |
82 |
83 |
84 | )}
85 | >
86 | )}
87 |
88 | ))}
89 |
90 | )}
91 |
92 |
93 | );
94 | }
95 |
96 | interface AccountSelectorProps {
97 | accounts: string[];
98 | selectedAccount: string;
99 | setSelectedAccount: (account: string) => void;
100 | setCurrentPage: (page: number) => void;
101 | }
102 |
103 | export default memo(AccountSelector);
104 |
--------------------------------------------------------------------------------
/components/program/accounts-data/filter.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import { RadioGroup } from "@headlessui/react";
3 |
4 | const filterOptions = ["address", "memcmp"];
5 |
6 | function classNames(...classes) {
7 | return classes.filter(Boolean).join(" ");
8 | }
9 |
10 | function AccountsDataFilter({
11 | filter,
12 | setFilter,
13 | option,
14 | setOption,
15 | }: AccountsDataFilterProps) {
16 | return (
17 |
18 |
19 |
Filter using:
20 |
21 |
22 |
23 |
24 | {filterOptions.map((option) => (
25 | setFilter({})}
29 | className={({ active, checked }) =>
30 | classNames(
31 | "cursor-pointer focus:outline-none",
32 | active ? "ring-2 ring-amber-500 ring-offset-2" : "",
33 | checked
34 | ? "border-transparent bg-amber-600 text-white hover:bg-amber-700"
35 | : "border-gray-200 bg-white text-gray-900 hover:bg-gray-50",
36 | "flex items-center justify-center rounded-md border py-3 px-3 text-sm font-medium sm:flex-1"
37 | )
38 | }
39 | >
40 | {option}
41 |
42 | ))}
43 |
44 |
45 |
46 | {option === "address" && (
47 |
48 |
49 | account
50 |
51 |
56 | setFilter({ ...filter, address: event.target.value })
57 | }
58 | className="block w-28 flex-1 rounded-none rounded-r-md border-gray-300 px-3 py-2 focus:border-amber-500 focus:ring-amber-500 sm:text-sm"
59 | placeholder="HWx6Bcau9SJGcdX5PYTeFGzrhwVcFRrj2D1jadicLVkj"
60 | />
61 |
62 | )}
63 |
64 | {option === "memcmp" && (
65 | <>
66 |
67 |
68 | offset
69 |
70 |
75 | setFilter({ ...filter, offset: event.target.value })
76 | }
77 | className="block w-28 flex-1 rounded-none rounded-r-md border-gray-300 px-3 py-2 focus:border-amber-500 focus:ring-amber-500 sm:text-sm"
78 | placeholder="1"
79 | />
80 |
81 |
82 |
83 |
84 | bytes
85 |
86 |
90 | setFilter({ ...filter, bytes: event.target.value })
91 | }
92 | id="bytes"
93 | className="block w-96 flex-1 rounded-none rounded-r-md border-gray-300 px-3 py-2 focus:border-amber-500 focus:ring-amber-500 sm:text-sm"
94 | placeholder="AYtuQqncT1C7rY1M5sgupBNj8tqemkN3PJ9smGVdRgMJ"
95 | />
96 |
97 | >
98 | )}
99 |
100 | );
101 | }
102 |
103 | interface AccountsDataFilterProps {
104 | filter: any;
105 | option: string;
106 | setFilter: (filter: any) => void;
107 | setOption: (option: string) => void;
108 | }
109 |
110 | export default memo(AccountsDataFilter);
111 |
--------------------------------------------------------------------------------
/components/program/accounts-data/index.tsx:
--------------------------------------------------------------------------------
1 | import { memo, useCallback, useEffect, useState } from "react";
2 | import { AnchorProvider, Program } from "@project-serum/anchor";
3 | import { Connection, PublicKey } from "@solana/web3.js";
4 | import AccountSelector from "./account-selector";
5 | import AccountsDataFilter from "./filter";
6 | import { PrismAsyncLight as SyntaxHighlighter } from "react-syntax-highlighter";
7 | import { CollectionIcon } from "@heroicons/react/solid";
8 |
9 | function AccountsData({ idl, programID }: AccountsDataProps) {
10 | const [selectedAccount, setSelectedAccount] = useState();
11 | const [data, setData] = useState([]);
12 | // Pagination
13 | const [accountsLength, setAccountsLength] = useState(0);
14 | const [pageSize, setPageSize] = useState(10);
15 | const [pages, setPages] = useState();
16 | const [currentPage, setCurrentPage] = useState(0);
17 | // Filter
18 | const [option, setOption] = useState("");
19 | const [filter, setFilter] = useState({});
20 |
21 | // Initialize Anchor program
22 | const defineProgram = useCallback(async (): Promise => {
23 | try {
24 | const connection = new Connection(
25 | process.env.NEXT_PUBLIC_NODE_URL as string
26 | );
27 |
28 | const provider = new AnchorProvider(
29 | connection,
30 | {
31 | publicKey: PublicKey.default,
32 | signAllTransactions: undefined,
33 | signTransaction: undefined,
34 | },
35 | { commitment: "processed", skipPreflight: true }
36 | );
37 | console.log(idl);
38 | console.log(programID);
39 | return new Program(idl, programID, provider);
40 | } catch (e) {
41 | console.error("Error defining program:", e);
42 | }
43 | }, [idl, programID]);
44 |
45 | // Find all accounts
46 | const getAccounts = useCallback(
47 | async (accountName: string): Promise => {
48 | try {
49 | const program = await defineProgram();
50 |
51 | // normalize account name
52 | const name = accountName.charAt(0).toLowerCase() + accountName.slice(1);
53 |
54 | let accountFilter: any | undefined = undefined;
55 | if (filter.offset && filter.bytes) {
56 | accountFilter = [
57 | {
58 | memcmp: {
59 | offset: Number(filter.offset),
60 | bytes: filter.bytes,
61 | },
62 | },
63 | ];
64 | }
65 |
66 | // Get all accounts
67 | const accounts = await program.account[name].all(accountFilter);
68 |
69 | // Pagination
70 | setAccountsLength(accounts.length);
71 | setPages(Math.ceil(accounts.length / 10));
72 |
73 | return accounts.map((account) => {
74 | return account.publicKey;
75 | });
76 | } catch (e) {
77 | console.log("Error:", e);
78 | }
79 | },
80 | [defineProgram, filter]
81 | );
82 |
83 | // Get data for selected accounts
84 | const getData = useCallback(
85 | async (accountName: string): Promise => {
86 | try {
87 | const program = await defineProgram();
88 |
89 | // normalize account name
90 | const name = accountName.charAt(0).toLowerCase() + accountName.slice(1);
91 | // Check if I need to find an specific account or all accounts
92 | if (filter.address) {
93 | const data = await program.account[name].fetch(filter.address);
94 | setAccountsLength(1);
95 | setPages(1);
96 | return data;
97 | } else {
98 | const pks = await getAccounts(accountName);
99 | return await program.account[name].fetchMultiple(
100 | pks.slice(currentPage, currentPage + pageSize)
101 | );
102 | }
103 | } catch (e) {
104 | console.log("Error:", e);
105 | }
106 | },
107 | [defineProgram, getAccounts, currentPage, pageSize, filter.address]
108 | );
109 |
110 | useEffect(() => {
111 | async function fetchData() {
112 | try {
113 | const data = await getData(selectedAccount);
114 | setData(data);
115 | } catch (e) {
116 | console.log("Error:", e);
117 | }
118 | }
119 | if (selectedAccount) fetchData();
120 | }, [getData, selectedAccount, filter]);
121 |
122 | // List of accounts names to display
123 | const listOfAccounts = idl.accounts.map((account) => account.name);
124 |
125 | return (
126 |
127 |
145 |
146 |
147 |
148 | {/* Account name */}
149 |
150 |
151 |
152 | {selectedAccount ? selectedAccount : "Select an Account"}
153 |
154 |
155 |
156 | {/* Pagination state */}
157 | {selectedAccount && (
158 |
159 | Showing {currentPage * pageSize} to{" "}
160 | {accountsLength >= pageSize
161 | ? pageSize * currentPage + pageSize
162 | : accountsLength}{" "}
163 | of {accountsLength} results
164 |
165 | )}
166 |
167 | {/* Pagination actions */}
168 |
169 | {
172 | setCurrentPage(currentPage - 1);
173 | }}
174 | className="relative inline-flex items-center rounded-md border border-gray-300
175 | bg-white px-4 py-2 text-sm font-medium text-gray-700
176 | hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
177 | >
178 | Previous
179 |
180 | setCurrentPage(currentPage + 1)}
182 | className="relative ml-3 inline-flex items-center
183 | rounded-md border border-gray-300 bg-white px-4 py-2
184 | text-sm font-medium text-gray-700 hover:bg-gray-50
185 | disabled:cursor-not-allowed disabled:opacity-50"
186 | disabled={currentPage === pages - 1 || !selectedAccount}
187 | >
188 | Next
189 |
190 |
191 |
192 |
193 |
194 |
200 | {JSON.stringify(data, null, 2)}
201 |
202 |
203 |
204 |
205 | );
206 | }
207 |
208 | interface AccountsDataProps {
209 | idl: any;
210 | programID: string;
211 | }
212 |
213 | export default memo(AccountsData);
214 |
--------------------------------------------------------------------------------
/components/program/builds.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import { CalendarIcon, KeyIcon } from "@heroicons/react/outline";
3 | import Link from "next/link";
4 | import Status from "../status";
5 | import FormatDate from "../../utils/format-date";
6 |
7 | function Builds({ builds }: BuildsProps) {
8 | return (
9 |
10 | {builds.map((build) => {
11 | return (
12 |
17 |
18 | {/* Build */}
19 |
20 |
Build #{build.id}
21 |
22 |
23 | {/* Middle section */}
24 |
25 | {/* Published date*/}
26 |
27 |
28 |
29 |
30 | Publish {FormatDate(build.updated_at)}
31 |
32 |
33 |
34 | {/* SHA */}
35 | {build.sha256 && (
36 |
37 |
38 |
39 |
40 | {build.sha256}
41 |
42 |
43 | )}
44 |
45 |
46 | {/* Build status */}
47 |
48 |
49 |
50 |
51 |
52 | );
53 | })}
54 |
55 | );
56 | }
57 |
58 | interface BuildsProps {
59 | builds: any[];
60 | }
61 |
62 | export default memo(Builds);
63 |
--------------------------------------------------------------------------------
/components/program/idl-viewer.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import dynamic from "next/dynamic";
3 | import { useRouter } from "next/router";
4 | import { DownloadIcon } from "@heroicons/react/solid";
5 |
6 | const Instructions = dynamic(() => import("./idl/instructions"));
7 | const Accounts = dynamic(() => import("./idl/accounts"));
8 | const Errors = dynamic(() => import("./idl/errors"));
9 | const Events = dynamic(() => import("./idl/events"));
10 | const Types = dynamic(() => import("./idl/types"));
11 | const Constants = dynamic(() => import("./idl/constants"));
12 |
13 | const tabs = [
14 | { name: "Instructions" },
15 | { name: "Accounts" },
16 | { name: "Types" },
17 | { name: "Errors" },
18 | { name: "Constants" },
19 | { name: "Events" },
20 | { name: "Raw" },
21 | ];
22 |
23 | function classNames(...classes) {
24 | return classes.filter(Boolean).join(" ");
25 | }
26 |
27 | function IdlViewer({ data, url }: IDLViewerProps) {
28 | const router = useRouter();
29 |
30 | const selectedTab = router.query.idl || "Instructions";
31 |
32 | return (
33 |
34 |
35 |
36 | Select a tab
37 |
38 | tab.name === selectedTab).name}
43 | >
44 | {tabs.map((tab) => (
45 | {tab.name}
46 | ))}
47 |
48 |
49 |
50 |
51 | {tabs.map((tab) => (
52 |
56 | {tab.name !== "Raw" ? (
57 |
{
59 | let section = router.pathname.includes("/idl/")
60 | ? "idl"
61 | : "program";
62 |
63 | router.push(
64 | `/${section}/${router.query.address}?tab=IDL&idl=${tab.name}`
65 | );
66 | }}
67 | disabled={!(tab.name.toLowerCase() in data)}
68 | className={classNames(
69 | tab.name === selectedTab
70 | ? "bg-orange-100 text-gray-500"
71 | : "text-gray-500 hover:text-gray-700",
72 | "rounded-md px-3 py-2 text-sm font-medium disabled:cursor-not-allowed disabled:text-gray-300"
73 | )}
74 | aria-current={tab.name === selectedTab ? "page" : undefined}
75 | >
76 | {tab.name}
77 |
78 | ) : (
79 | url && (
80 |
86 |
87 | {tab.name}
88 |
89 | )
90 | )}
91 |
92 | ))}
93 |
94 |
95 | {selectedTab === "Instructions" && (
96 |
97 | )}
98 | {selectedTab === "Accounts" &&
}
99 | {data.errors && selectedTab === "Errors" &&
}
100 | {data.types && selectedTab === "Types" &&
}
101 | {data.events && selectedTab === "Events" &&
}
102 | {data.events && selectedTab === "Constants" && (
103 |
104 | )}
105 |
106 | );
107 | }
108 |
109 | interface IDLViewerProps {
110 | data: any;
111 | url: string;
112 | }
113 |
114 | export default memo(IdlViewer);
115 |
--------------------------------------------------------------------------------
/components/program/idl/accounts.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 |
3 | import renderArguments from "../../../utils/renderArguments";
4 |
5 | function IDLAccounts({ data }: IDLAccountsProps) {
6 | return (
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
18 | Name
19 |
20 |
24 | Fields
25 |
26 |
27 |
28 |
29 | {data.map((item) => (
30 |
31 |
32 | {item.name}
33 |
34 |
35 | {renderArguments(item.type.fields)}
36 |
37 |
38 | ))}
39 |
40 |
41 |
42 |
43 |
44 |
45 | );
46 | }
47 |
48 | interface IDLAccountsProps {
49 | data: any;
50 | }
51 |
52 | export default memo(IDLAccounts);
53 |
--------------------------------------------------------------------------------
/components/program/idl/constants.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 |
3 | function IDLConstants({ data }: IDLConstantsProps) {
4 | return (
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
16 | Name
17 |
18 |
22 | Fields
23 |
24 |
28 | Value
29 |
30 |
31 |
32 |
33 | {data.map((item) => (
34 |
35 |
36 | {item.name}
37 |
38 |
39 |
40 | `{item.type.defined}`
41 |
42 |
43 |
44 | {item.value}
45 |
46 |
47 | ))}
48 |
49 |
50 |
51 |
52 |
53 |
54 | );
55 | }
56 |
57 | interface IDLConstantsProps {
58 | data: any;
59 | }
60 |
61 | export default memo(IDLConstants);
62 |
--------------------------------------------------------------------------------
/components/program/idl/errors.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 |
3 | function IDLErrors({ data }: IDLErrorsProps) {
4 | return (
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
16 | Code
17 |
18 |
22 | Name
23 |
24 |
28 | Message
29 |
30 |
31 |
32 |
33 | {data.map((item) => (
34 |
35 |
36 | {item.code}
37 |
38 |
39 | {item.name}
40 |
41 |
42 | {item.msg}
43 |
44 |
45 | ))}
46 |
47 |
48 |
49 |
50 |
51 |
52 | );
53 | }
54 |
55 | interface IDLErrorsProps {
56 | data: any;
57 | }
58 |
59 | export default memo(IDLErrors);
60 |
--------------------------------------------------------------------------------
/components/program/idl/events.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 |
3 | import renderArguments from "../../../utils/renderArguments";
4 |
5 | function IDLEvents({ data }: IDLEventsProps) {
6 | return (
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
18 | Name
19 |
20 |
24 | Fields
25 |
26 |
27 |
28 |
29 | {data.map((item) => (
30 |
31 |
32 | {item.name}
33 |
34 |
35 | {renderArguments(item.fields)}
36 |
37 |
38 | ))}
39 |
40 |
41 |
42 |
43 |
44 |
45 | );
46 | }
47 |
48 | interface IDLEventsProps {
49 | data: any;
50 | }
51 |
52 | export default memo(IDLEvents);
53 |
--------------------------------------------------------------------------------
/components/program/idl/instructions.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 |
3 | import renderArguments from "../../../utils/renderArguments";
4 |
5 | function renderAccounts(accounts) {
6 | let component = [];
7 |
8 | for (let i = 0; i < accounts.length; i++) {
9 | component.push(
10 |
11 |
{accounts[i].name}
12 |
13 | {accounts[i].isSigner && (
14 |
15 | isSigner
16 |
17 | )}
18 | {accounts[i].isMut && (
19 |
20 | isMut
21 |
22 | )}
23 |
24 |
25 | );
26 | }
27 |
28 | return component;
29 | }
30 |
31 | function Instructions({ data }: InstructionsProps) {
32 | return (
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
44 | Name
45 |
46 |
50 | Arguments
51 |
52 |
56 | Accounts
57 |
58 |
59 |
60 |
61 | {data.map((item) => (
62 |
63 |
64 | {item.name}
65 |
66 |
67 | {renderArguments(item.args)}
68 |
69 |
70 | {renderAccounts(item.accounts)}
71 |
72 |
73 | ))}
74 |
75 |
76 |
77 |
78 |
79 |
80 | );
81 | }
82 |
83 | interface InstructionsProps {
84 | data: any;
85 | }
86 |
87 | export default memo(Instructions);
88 |
--------------------------------------------------------------------------------
/components/program/idl/types.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 |
3 | function renderArguments(type) {
4 | let component = [];
5 |
6 | if (type.fields) {
7 | const args = type.fields;
8 | for (let i = 0; i < args.length; i++) {
9 | let type = "";
10 |
11 | if (args[i].type.array) {
12 | type = `[${args[i].type.array[0]}; ${args[i].type.array[1]}]`;
13 | } else if (args[i].type.vec) {
14 | if (args[i].type.vec.defined) {
15 | type = `Vec<${args[i].type.vec.defined}>`;
16 | } else {
17 | type = `Vec<[${args[i].type.vec.array[0]}; ${args[i].type.vec.array[1]}]>`;
18 | }
19 | } else if (args[i].type.defined) {
20 | type = args[i].type.defined;
21 | } else if (args[i].type.option) {
22 | type = `Option<${args[i].type.option}>`;
23 | } else if (args[i].type.variant) {
24 | } else {
25 | type = args[i].type;
26 | }
27 |
28 | component.push(
29 |
30 |
31 | {args[i].name}:
32 |
33 | `{type}`
34 |
35 | {args[i].index && (
36 |
37 | index
38 |
39 | )}
40 |
41 |
42 | );
43 | }
44 | } else if (type.variants) {
45 | const args = type.variants;
46 | for (let i = 0; i < args.length; i++) {
47 | let type = args[i].name;
48 |
49 | component.push(
50 |
51 |
52 |
53 | `{type}`
54 |
55 |
56 |
57 | );
58 | }
59 | }
60 |
61 | return component;
62 | }
63 |
64 | function IDLTypes({ data }: IDLTypesProps) {
65 | return (
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
77 | Name
78 |
79 |
83 | Fields
84 |
85 |
86 |
87 |
88 | {data.map((item) => (
89 |
90 |
91 | {item.type.kind} {item.name}
92 |
93 |
94 | {renderArguments(item.type)}
95 |
96 |
97 | ))}
98 |
99 |
100 |
101 |
102 |
103 |
104 | );
105 | }
106 |
107 | interface IDLTypesProps {
108 | data: any;
109 | }
110 |
111 | export default memo(IDLTypes);
112 |
--------------------------------------------------------------------------------
/components/program/index.tsx:
--------------------------------------------------------------------------------
1 | import dynamic from "next/dynamic";
2 | import { memo } from "react";
3 | import {
4 | ClockIcon,
5 | CodeIcon,
6 | DatabaseIcon,
7 | DocumentTextIcon,
8 | TerminalIcon,
9 | } from "@heroicons/react/solid";
10 |
11 | const ProgramBanner = dynamic(() => import("./program-banner"));
12 | const Tabs = dynamic(() => import("./tabs"));
13 |
14 | const tabs = [
15 | { name: "Readme", icon: DocumentTextIcon },
16 | { name: "Explorer", icon: CodeIcon },
17 | { name: "IDL", icon: TerminalIcon },
18 | { name: "Accounts Data", icon: DatabaseIcon },
19 | { name: "Builds", icon: ClockIcon },
20 | ];
21 |
22 | function Program({
23 | program,
24 | selectedBuild,
25 | builds,
26 | readme,
27 | files,
28 | }: ProgramProps) {
29 | const latestBuild = selectedBuild.id === builds[0].id;
30 |
31 | return (
32 |
49 | );
50 | }
51 |
52 | interface ProgramProps {
53 | program: any;
54 | builds: any[];
55 | selectedBuild: any;
56 | readme: string;
57 | files: string[];
58 | }
59 |
60 | export default memo(Program);
61 |
--------------------------------------------------------------------------------
/components/program/metadata.tsx:
--------------------------------------------------------------------------------
1 | import { Button, Divider, Typography } from "@mui/material";
2 | import Box from "@mui/material/Box";
3 | import { CloudDownloadOutlined, OpenInNew } from "@mui/icons-material";
4 | import { styled } from "@mui/material/styles";
5 | import FormatDate from "../../utils/format-date";
6 |
7 | const StyledTitle = styled(Typography)(({ theme }) => ({
8 | fontSize: 13,
9 | color: theme.palette.grey["600"],
10 | fontWeight: "bold",
11 | textTransform: "uppercase",
12 | }));
13 |
14 | export default function Metadata({ data }) {
15 | return (
16 |
17 |
18 | Last Updated
19 |
20 | {FormatDate(data.updated_at)}
21 |
22 |
23 |
24 |
25 |
26 |
27 | Artifact
28 | }
33 | color="info"
34 | >
35 |
36 | {data.name}.so
37 |
38 |
39 |
40 |
41 |
42 |
43 | {data.sha256 && (
44 |
45 | Build
46 | }
50 | color="info"
51 | sx={{
52 | width: "fit-content",
53 | }}
54 | >
55 |
56 | {data.sha256}
57 |
58 |
59 |
60 | )}
61 |
62 | {data.upgrade_authority && (
63 | <>
64 |
65 |
66 |
67 | Upgrade authority
68 | }
73 | color="info"
74 | sx={{
75 | width: "fit-content",
76 | }}
77 | >
78 |
79 | {data.upgrade_authority}
80 |
81 |
82 |
83 | >
84 | )}
85 |
86 | {data.verified_slot && (
87 | <>
88 |
89 |
90 | Slot deployed
91 | }
96 | color="info"
97 | sx={{
98 | width: "fit-content",
99 | }}
100 | >
101 |
102 | {data.verified_slot}
103 |
104 |
105 |
106 | >
107 | )}
108 |
109 | );
110 | }
111 |
--------------------------------------------------------------------------------
/components/program/program-banner.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import { ExternalLinkIcon } from "@heroicons/react/outline";
3 | import FormatDate from "../../utils/format-date";
4 | import { CloudDownloadOutlined } from "@mui/icons-material";
5 | import dynamic from "next/dynamic";
6 |
7 | const Status = dynamic(() => import("../status"));
8 |
9 | function ProgramCard({
10 | name,
11 | address,
12 | selectedBuild,
13 | latest,
14 | }: ProgramCardProps) {
15 | return (
16 | <>
17 |
18 |
19 |
20 |
21 | {/* Program Name */}
22 |
{name}
23 | {/* Program SHA */}
24 |
35 |
36 |
37 | {/* Tags */}
38 |
39 | {selectedBuild ? (
40 |
41 | build #{selectedBuild.id}
42 |
43 | ) : (
44 | <>
45 |
46 | mainnet-beta
47 |
48 | >
49 | )}
50 |
51 | {latest && (
52 |
53 | latest
54 |
55 | )}
56 |
57 |
58 |
59 |
60 | {selectedBuild && (
61 | <>
62 |
70 |
71 |
72 | {/* Verification Status */}
73 |
74 |
75 | Status
76 |
77 |
78 |
79 |
80 | {/* Last Updated */}
81 |
82 |
83 | Last Updated
84 |
85 |
86 | {FormatDate(selectedBuild.updated_at)}
87 |
88 |
89 |
90 | {/* Build */}
91 |
92 |
93 | Build
94 |
95 |
104 |
105 |
106 | {/* Artifact */}
107 |
108 |
109 | Artifact
110 |
111 |
120 |
121 |
122 | >
123 | )}
124 |
125 | >
126 | );
127 | }
128 |
129 | interface ProgramCardProps {
130 | name: string;
131 | address: string;
132 | selectedBuild: any | boolean;
133 | latest: boolean;
134 | }
135 |
136 | export default memo(ProgramCard);
137 |
--------------------------------------------------------------------------------
/components/program/readme.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import { BookOpenIcon } from "@heroicons/react/solid";
3 |
4 | function Readme({ readme }: ReadmeProps) {
5 | return (
6 |
7 |
8 |
9 |
Readme
10 |
11 |
12 |
16 |
17 | );
18 | }
19 |
20 | interface ReadmeProps {
21 | readme: string;
22 | }
23 |
24 | export default memo(Readme);
25 |
--------------------------------------------------------------------------------
/components/program/source-files.tsx:
--------------------------------------------------------------------------------
1 | import { memo, useEffect, useState } from "react";
2 | import Box from "@mui/material/Box";
3 | import filesTree from "../../utils/files-tree";
4 | import {
5 | Breadcrumbs,
6 | Button,
7 | Paper,
8 | TableCell,
9 | TableContainer,
10 | } from "@mui/material";
11 | import Table from "@mui/material/Table";
12 | import TableRow from "@mui/material/TableRow";
13 | import TableBody from "@mui/material/TableBody";
14 | import { Folder } from "@mui/icons-material";
15 | import Typography from "@mui/material/Typography";
16 | import InsertDriveFileOutlinedIcon from "@mui/icons-material/InsertDriveFileOutlined";
17 | import Source from "./source";
18 |
19 | function table(
20 | tree: any[],
21 | setTree: Function,
22 | setSource: Function,
23 | setShowSource: Function,
24 | setBreadcrumbs: Function,
25 | breadcrumbs: any[]
26 | ) {
27 | return (
28 |
33 |
34 |
35 | {tree.map((file) => (
36 |
37 | {file.type === "folder" && (
38 | {
42 | setBreadcrumbs([
43 | ...breadcrumbs,
44 | {
45 | name: file.name,
46 | children: file.children,
47 | },
48 | ]);
49 |
50 | setTree(file.children);
51 | }}
52 | sx={{ cursor: "pointer" }}
53 | >
54 |
55 | {" "}
60 |
61 | {file.name}
62 |
63 |
64 | )}
65 | {file.type === "file" && (
66 | {
70 | setBreadcrumbs([
71 | ...breadcrumbs,
72 | {
73 | name: file.name,
74 | children: file.children,
75 | },
76 | ]);
77 | setSource({ name: file.name, url: file.url });
78 | setShowSource(true);
79 | }}
80 | sx={{ cursor: "pointer" }}
81 | >
82 |
83 |
84 | {file.name}
85 |
86 |
87 | )}
88 |
89 | ))}
90 |
91 |
92 |
93 | );
94 | }
95 |
96 | function SourceFiles({ name, files, readme }: SourceFilesProps) {
97 | const [tree, setTree] = useState([]);
98 | const [source, setSource] = useState();
99 | const [showSource, setShowSource] = useState(false);
100 | const [breadcrumbs, setBreadcrumbs] = useState([]);
101 |
102 | useEffect(() => {
103 | const structure = filesTree(files);
104 | setTree(structure);
105 |
106 | setBreadcrumbs([{ name, children: structure }]);
107 | }, [files, name]);
108 |
109 | return (
110 |
113 |
114 | {breadcrumbs.map((item) => (
115 | {
120 | let files: any;
121 |
122 | for (let i = 0; i < breadcrumbs.length; i++) {
123 | if (item.name !== breadcrumbs[i].name) continue;
124 |
125 | files = item;
126 |
127 | const newBreadcrumbs = breadcrumbs.slice(0, i + 1);
128 | setBreadcrumbs(newBreadcrumbs);
129 |
130 | break;
131 | }
132 |
133 | if (showSource) setShowSource(false);
134 |
135 | setTree(files.children);
136 | }}
137 | >
138 | {item.name}
139 |
140 | ))}
141 |
142 |
143 | {showSource ? (
144 |
145 | ) : (
146 | table(
147 | tree,
148 | setTree,
149 | setSource,
150 | setShowSource,
151 | setBreadcrumbs,
152 | breadcrumbs
153 | )
154 | )}
155 |
156 | );
157 | }
158 |
159 | interface SourceFilesProps {
160 | name: string;
161 | files: string[];
162 | readme: string;
163 | }
164 |
165 | interface SourceProps {
166 | name: string;
167 | url: string;
168 | }
169 |
170 | export default memo(SourceFiles);
171 |
--------------------------------------------------------------------------------
/components/program/source.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import useSWR from "swr";
3 | import fetchMD from "../../utils/fetcher-md";
4 | import { PrismAsyncLight as SyntaxHighlighter } from "react-syntax-highlighter";
5 | import Readme from "./readme";
6 |
7 | function language(file: string): string {
8 | const extension = file.split(".")[1];
9 | switch (extension) {
10 | case "rs":
11 | return "rust";
12 | case "js":
13 | return "javascript";
14 | case "ts":
15 | return "typescript";
16 | case "yaml":
17 | return "yaml";
18 | case "md":
19 | return "markdown";
20 | case "jsx":
21 | return "jsx";
22 | case "tsx":
23 | return "tsx";
24 | case "sql":
25 | return "sql";
26 | case "toml":
27 | return "toml";
28 | case "json":
29 | return "json";
30 | case "sh":
31 | return "bash";
32 | default:
33 | return "";
34 | }
35 | }
36 |
37 | function Source({ url, name, readme }: SourceProps) {
38 | const { data } = useSWR(url as string, fetchMD);
39 |
40 | return (
41 |
42 | {name !== "README.md" ? (
43 | <>
44 |
54 |
55 |
61 | {data}
62 |
63 |
64 | >
65 | ) : (
66 |
67 | )}
68 |
69 | );
70 | }
71 |
72 | interface SourceProps {
73 | name: string;
74 | url: string;
75 | readme: string;
76 | }
77 |
78 | export default memo(Source);
79 |
--------------------------------------------------------------------------------
/components/program/tabs.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import useSWR from "swr";
3 | import dynamic from "next/dynamic";
4 | import { useRouter } from "next/router";
5 | import fetcher from "../../utils/fetcher";
6 | import { Address, Idl } from "@project-serum/anchor";
7 |
8 | const Readme = dynamic(() => import("./readme"));
9 | const Builds = dynamic(() => import("./builds"));
10 | const IdlViewer = dynamic(() => import("./idl-viewer"));
11 | const SourceFiles = dynamic(() => import("./source-files"));
12 | const AccountsData = dynamic(() => import("./accounts-data"));
13 |
14 | function classNames(...classes) {
15 | return classes.filter(Boolean).join(" ");
16 | }
17 |
18 | function Tabs({
19 | tabs,
20 | selectedBuild,
21 | builds,
22 | readme,
23 | files,
24 | networkIdl,
25 | idlAddress,
26 | }: TabsProps) {
27 | const router = useRouter();
28 | const { data: apiIdl } = useSWR(
29 | selectedBuild && (selectedBuild.artifacts.idl as string),
30 | fetcher
31 | );
32 |
33 | const idl = apiIdl || networkIdl;
34 | const address = selectedBuild?.address || idlAddress;
35 |
36 | let selectedTab = router.query.tab || "Readme";
37 |
38 | if (router.pathname.includes("/idl/")) {
39 | selectedTab = router.query.tab == "Accounts Data" ? "Accounts Data" : "IDL";
40 | }
41 |
42 | const idlHasAccount =
43 | idl && Array.isArray(idl.accounts) && idl.accounts.length > 0;
44 |
45 | return (
46 |
47 |
48 |
49 |
50 | Select a tab
51 |
52 | tab.name === selectedTab).name}
57 | >
58 | {tabs.map((tab) => (
59 | {tab.name}
60 | ))}
61 |
62 |
63 |
64 |
65 |
66 |
67 | {tabs.map((tab) => (
68 | {
71 | let section = router.pathname.includes("/idl/")
72 | ? "idl"
73 | : "program";
74 |
75 | router.push(
76 | `/${section}/${router.query.address}?tab=${tab.name}`
77 | );
78 | }}
79 | disabled={
80 | tab.disabled ||
81 | (tab.name === "IDL" && !idl) ||
82 | (tab.name === "Accounts Data" && !idlHasAccount)
83 | }
84 | className={classNames(
85 | tab.name === selectedTab
86 | ? "border-amber-500 text-amber-600"
87 | : "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700",
88 | "group inline-flex items-center border-b-2 py-4 px-1 text-sm font-medium disabled:cursor-not-allowed disabled:text-gray-300"
89 | )}
90 | aria-current={tab.name === selectedTab ? "page" : undefined}
91 | >
92 |
105 | {tab.name}
106 |
107 | ))}
108 |
109 |
110 |
111 |
112 | {selectedTab === "Readme" &&
}
113 | {selectedTab === "Builds" &&
}
114 | {selectedTab === "Explorer" && (
115 |
116 | )}
117 | {selectedTab === "IDL" && (idl || networkIdl) && (
118 |
119 | )}
120 | {selectedTab === "Accounts Data" && idl && idl.accounts && (
121 |
122 | )}
123 |
124 | );
125 | }
126 |
127 | interface TabsProps {
128 | readme: string | undefined;
129 | selectedBuild: any | undefined;
130 | builds: any[] | undefined;
131 | files: string[] | undefined;
132 | tabs: any[];
133 | networkIdl: Idl | undefined;
134 | idlAddress: Address | undefined;
135 | }
136 |
137 | export default memo(Tabs);
138 |
--------------------------------------------------------------------------------
/components/search.tsx:
--------------------------------------------------------------------------------
1 | import { Fragment, useCallback, useEffect, useMemo, useState } from "react";
2 | import { Combobox, Dialog, Transition } from "@headlessui/react";
3 | import { FilterIcon } from "@heroicons/react/solid";
4 | import { AnchorProvider, Program } from "@project-serum/anchor";
5 | import { Connection, PublicKey } from "@solana/web3.js";
6 |
7 | function classNames(...classes) {
8 | return classes.filter(Boolean).join(" ");
9 | }
10 |
11 | export default function Search({ programs, open, setOpen }: ProgramsProps) {
12 | const [query, setQuery] = useState("");
13 | const [list, setList] = useState([]);
14 | const [unpublishedProgram, setUnpublishedProgram] = useState(false);
15 |
16 | const filteredPrograms = useMemo(async () => {
17 | if (query === "") {
18 | setList([]);
19 | } else {
20 | const data = programs.filter((program) => {
21 | if (program.name.toLowerCase().includes(query.toLowerCase())) {
22 | return true;
23 | } else if (
24 | program.address.toLowerCase().includes(query.toLowerCase())
25 | ) {
26 | return true;
27 | }
28 | return false;
29 | });
30 |
31 | setList(data);
32 | setUnpublishedProgram(false);
33 | }
34 | }, [programs, query]);
35 |
36 | const fetchIdl = useCallback(async (address: PublicKey): Promise => {
37 | try {
38 | const connection = new Connection(
39 | process.env.NEXT_PUBLIC_NODE_URL as string
40 | );
41 |
42 | const provider = new AnchorProvider(
43 | connection,
44 | {
45 | publicKey: PublicKey.default,
46 | signAllTransactions: undefined,
47 | signTransaction: undefined,
48 | },
49 | { commitment: "processed", skipPreflight: true }
50 | );
51 |
52 | const idl = await Program.fetchIdl(address, provider);
53 | return idl;
54 | } catch (e) {
55 | console.error("Error:", e);
56 | }
57 | }, []);
58 |
59 | useEffect(() => {
60 | {
61 | async function run() {
62 | try {
63 | const key = new PublicKey(query);
64 |
65 | // If real key, try fetching idl
66 | if (PublicKey.isOnCurve(key.toBytes())) {
67 | const idl = await fetchIdl(key);
68 |
69 | if (idl) {
70 | setList([{ address: query, name: idl.name, idl: idl, id: 1 }]);
71 | setUnpublishedProgram(true);
72 | }
73 | }
74 | } catch (e) {
75 | console.log("Error:", e);
76 | }
77 | }
78 | if (list.length == 0 && query.length > 20) {
79 | run();
80 | }
81 | }
82 | }, [list.length, fetchIdl, query, filteredPrograms]);
83 |
84 | return (
85 | setQuery("")}
89 | appear
90 | >
91 |
92 |
101 |
102 |
103 |
104 |
105 |
114 |
115 | {
117 | if (unpublishedProgram) {
118 | return (window.location = `/idl/${program.address}`);
119 | }
120 |
121 | return (window.location = `/program/${program.address}`);
122 | }}
123 | >
124 | setQuery(event.target.value)}
128 | />
129 |
130 | {list.length > 0 && (
131 |
135 | {list.map((program) => (
136 |
140 | classNames(
141 | "cursor-default select-none border-b border-gray-200 px-4 py-2",
142 | active && "bg-sky-50 text-sky-500"
143 | )
144 | }
145 | >
146 |
147 |
148 | {program.name}
149 |
150 |
151 | {program.address}
152 |
153 |
154 |
155 | ))}
156 |
157 | )}
158 |
159 | {query !== "" && list.length === 0 && (
160 |
161 |
165 |
166 | No programs found using that search term.
167 |
168 |
169 | )}
170 |
171 |
172 |
173 |
174 |
175 |
176 | );
177 | }
178 |
179 | interface ProgramsProps {
180 | programs: any[];
181 | open: boolean;
182 | setOpen: (open: boolean) => void;
183 | }
184 |
--------------------------------------------------------------------------------
/components/status.tsx:
--------------------------------------------------------------------------------
1 | import { memo } from "react";
2 | import {
3 | CheckCircleIcon,
4 | ClockIcon,
5 | ExclamationCircleIcon,
6 | ExclamationIcon,
7 | } from "@heroicons/react/solid";
8 |
9 | function Status({ buildStatus }: StatusProps) {
10 | return (
11 |
12 | {buildStatus === "verified" && (
13 |
14 |
15 | Verified
16 |
17 | )}
18 |
19 | {buildStatus === "failed" && (
20 |
21 |
22 | Verification Failed
23 |
24 | )}
25 |
26 | {buildStatus === "aborted" && (
27 |
28 |
29 | Build Aborted
30 |
31 | )}
32 |
33 | {buildStatus === "building" && (
34 |
35 |
36 | Building
37 |
38 | )}
39 |
40 | {buildStatus === "built" && (
41 |
42 |
43 | Built
44 |
45 | )}
46 |
47 | );
48 | }
49 |
50 | interface StatusProps {
51 | buildStatus: string;
52 | }
53 |
54 | export default memo(Status);
55 |
--------------------------------------------------------------------------------
/context/AutoConnectProvider.tsx:
--------------------------------------------------------------------------------
1 | import { useLocalStorage } from "@solana/wallet-adapter-react";
2 | import { createContext, FC, ReactNode, useContext } from "react";
3 |
4 | export interface AutoConnectContextState {
5 | autoConnect: boolean;
6 | setAutoConnect(autoConnect: boolean): void;
7 | }
8 |
9 | export const AutoConnectContext = createContext(
10 | {} as AutoConnectContextState
11 | );
12 |
13 | export function useAutoConnect(): AutoConnectContextState {
14 | return useContext(AutoConnectContext);
15 | }
16 |
17 | export const AutoConnectProvider: FC<{ children: ReactNode }> = ({ children }) => {
18 | const [autoConnect, setAutoConnect] = useLocalStorage("autoConnect", true);
19 |
20 | return (
21 |
22 | {children}
23 |
24 | );
25 | };
26 |
--------------------------------------------------------------------------------
/context/ContextProvider.tsx:
--------------------------------------------------------------------------------
1 | import { WalletAdapterNetwork } from "@solana/wallet-adapter-base";
2 | import { ConnectionProvider, WalletProvider } from "@solana/wallet-adapter-react";
3 | import { WalletModalProvider } from "@solana/wallet-adapter-react-ui";
4 | import {
5 | PhantomWalletAdapter,
6 | SolflareWalletAdapter,
7 | GlowWalletAdapter,
8 | } from "@solana/wallet-adapter-wallets";
9 | import { clusterApiUrl } from "@solana/web3.js";
10 | import { FC, ReactNode, useMemo } from "react";
11 | import { AutoConnectProvider, useAutoConnect } from "./AutoConnectProvider";
12 |
13 | const WalletContextProvider: FC<{ children: ReactNode }> = ({ children }) => {
14 | const { autoConnect } = useAutoConnect();
15 |
16 | let network = null;
17 | if (process.env.NEXT_PUBLIC_NETWORK_ENV === "devnet") network = WalletAdapterNetwork.Devnet;
18 | if (process.env.NEXT_PUBLIC_NETWORK_ENV === "testnet") network = WalletAdapterNetwork.Testnet;
19 | if (process.env.NEXT_PUBLIC_NETWORK_ENV === "mainnet") network = WalletAdapterNetwork.Mainnet;
20 |
21 | const endpoint = useMemo(() => clusterApiUrl(network), [network]);
22 |
23 | const wallets = useMemo(
24 | () => [
25 | new PhantomWalletAdapter(),
26 | new GlowWalletAdapter(),
27 | new SolflareWalletAdapter({ network }),
28 | ],
29 | [network]
30 | );
31 |
32 | return (
33 |
34 |
35 | {children}
36 |
37 |
38 | );
39 | };
40 |
41 | export const ContextProvider: FC<{ children: ReactNode }> = ({ children }) => {
42 | return (
43 |
44 | {children}
45 |
46 | );
47 | };
48 |
--------------------------------------------------------------------------------
/hooks/useAuth.ts:
--------------------------------------------------------------------------------
1 | import { useSession } from "next-auth/react";
2 | import { useRouter } from "next/router";
3 |
4 | export default function useAuth(privatePage: boolean) {
5 | const router = useRouter();
6 | const { data, status } = useSession({
7 | required: privatePage,
8 | onUnauthenticated() {
9 | router.push("/");
10 | },
11 | });
12 |
13 | return {
14 | session: data,
15 | status,
16 | };
17 | }
18 |
--------------------------------------------------------------------------------
/next-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 | ///
3 |
4 | // NOTE: This file should not be edited
5 | // see https://nextjs.org/docs/basic-features/typescript for more information.
6 |
--------------------------------------------------------------------------------
/next.config.js:
--------------------------------------------------------------------------------
1 | const { withSentryConfig } = require("@sentry/nextjs");
2 | const { withPlausibleProxy } = require("next-plausible");
3 |
4 | const moduleExports = withPlausibleProxy()({
5 | experimental: {
6 | legacyBrowsers: false,
7 | images: { allowFutureImage: true },
8 | },
9 | reactStrictMode: true,
10 | swcMinify: true,
11 | typescript: {
12 | ignoreBuildErrors: true,
13 | },
14 | images: {
15 | domains: [],
16 | formats: ["image/avif", "image/webp"],
17 | },
18 | });
19 |
20 | const sentryWebpackPluginOptions = {
21 | // Additional config options for the Sentry Webpack plugin. Keep in mind that
22 | // the following options are set automatically, and overriding them is not
23 | // recommended:
24 | // release, url, org, project, authToken, configFile, stripPrefix,
25 | // urlPrefix, include, ignore
26 |
27 | silent: true, // Suppresses all logs
28 | // For all available options, see:
29 | // https://github.com/getsentry/sentry-webpack-plugin#options.
30 | };
31 |
32 | // Make sure adding Sentry options is the last code to run before exporting, to
33 | // ensure that your source maps include changes from all other Webpack plugins
34 | module.exports = withSentryConfig(moduleExports, sentryWebpackPluginOptions);
35 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "registry",
3 | "version": "5.0.0",
4 | "private": true,
5 | "scripts": {
6 | "dev": "next dev",
7 | "build": "next build",
8 | "start": "next start",
9 | "lint": "next lint"
10 | },
11 | "dependencies": {
12 | "@sentry/nextjs": "^7.11.1",
13 | "@sentry/tracing": "^7.11.1",
14 | "next": "^12.2.5",
15 | "next-auth": "4.10.3",
16 | "react": "^18.2.0",
17 | "react-dom": "^18.2.0",
18 | "react-hotkeys": "^2.0.0"
19 | },
20 | "devDependencies": {
21 | "@emotion/cache": "^11.10.3",
22 | "@emotion/react": "^11.10.0",
23 | "@emotion/server": "^11.10.0",
24 | "@emotion/styled": "^11.10.0",
25 | "@headlessui/react": "^1.6.6",
26 | "@heroicons/react": "v1",
27 | "@mapbox/rehype-prism": "^0.8.0",
28 | "@mui/icons-material": "^5.10.2",
29 | "@mui/lab": "^5.0.0-alpha.96",
30 | "@mui/material": "^5.10.2",
31 | "@mui/x-data-grid": "^5.15.3",
32 | "@project-serum/anchor": "^0.25.0",
33 | "@solana/wallet-adapter-base": "^0.9.15",
34 | "@solana/wallet-adapter-react": "^0.15.17",
35 | "@solana/wallet-adapter-react-ui": "^0.9.15",
36 | "@solana/wallet-adapter-wallets": "^0.18.4",
37 | "@solana/web3.js": "^1.53.0",
38 | "@tailwindcss/aspect-ratio": "^0.4.0",
39 | "@tailwindcss/forms": "^0.5.2",
40 | "@tailwindcss/typography": "^0.5.4",
41 | "@types/node": "^18.7.11",
42 | "@types/react": "^18.0.17",
43 | "autoprefixer": "^10.4.8",
44 | "bs58": "^5.0.0",
45 | "eslint": "^8.22.0",
46 | "eslint-config-next": "^12.2.5",
47 | "eslint-config-prettier": "^8.5.0",
48 | "isomorphic-unfetch": "^3.1.0",
49 | "next-plausible": "^3.2.0",
50 | "postcss": "^8.4.16",
51 | "prettier": "^2.7.1",
52 | "prettier-plugin-tailwindcss": "^0.1.13",
53 | "react-json-view": "^1.21.3",
54 | "react-syntax-highlighter": "^15.5.0",
55 | "remark": "^14.0.2",
56 | "remark-gfm": "^3.0.1",
57 | "remark-html": "^15.0.1",
58 | "remark-prism": "^1.3.6",
59 | "swr": "^1.3.0",
60 | "tailwindcss": "^3.1.8",
61 | "typescript": "^4.7.4"
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/pages/404.tsx:
--------------------------------------------------------------------------------
1 | export default function Custom404() {
2 | return <>>;
3 | }
4 |
--------------------------------------------------------------------------------
/pages/_app.tsx:
--------------------------------------------------------------------------------
1 | import { AppProps } from "next/app";
2 | import { ThemeProvider } from "@mui/material/styles";
3 | import { CacheProvider, EmotionCache } from "@emotion/react";
4 | import theme from "../src/theme";
5 | import createEmotionCache from "../src/createEmotionCache";
6 | import { SessionProvider } from "next-auth/react";
7 | import PlausibleProvider from "next-plausible";
8 | import { ContextProvider } from "../context/ContextProvider";
9 | import Nav from "../components/nav";
10 | import "../style.css";
11 |
12 | require("@solana/wallet-adapter-react-ui/styles.css");
13 |
14 | // Client-side cache, shared for the whole session of the user in the browser.
15 | const clientSideEmotionCache = createEmotionCache();
16 |
17 | interface MyAppProps extends AppProps {
18 | emotionCache?: EmotionCache;
19 | }
20 |
21 | export default function MyApp(props: MyAppProps) {
22 | const {
23 | Component,
24 | emotionCache = clientSideEmotionCache,
25 | pageProps: { session, ...pageProps },
26 | } = props;
27 |
28 | return (
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | );
46 | }
47 |
--------------------------------------------------------------------------------
/pages/_document.tsx:
--------------------------------------------------------------------------------
1 | import Document, { Head, Html, Main, NextScript } from "next/document";
2 | import createEmotionServer from "@emotion/server/create-instance";
3 | import theme from "../src/theme";
4 | import createEmotionCache from "../src/createEmotionCache";
5 |
6 | export default class MyDocument extends Document {
7 | render() {
8 | return (
9 |
10 |
11 | {/* PWA primary color */}
12 |
13 |
14 |
15 |
16 |
20 | {/* Inject MUI styles first to match with the prepend: true configuration. */}
21 | {(this.props as any).emotionStyleTags}
22 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | );
33 | }
34 | }
35 |
36 | // `getInitialProps` belongs to `_document` (instead of `_app`),
37 | // it's compatible with static-site generation (SSG).
38 | MyDocument.getInitialProps = async (ctx) => {
39 | // Resolution order
40 | //
41 | // On the server:
42 | // 1. app.getInitialProps
43 | // 2. page.getInitialProps
44 | // 3. document.getInitialProps
45 | // 4. app.render
46 | // 5. page.render
47 | // 6. document.render
48 | //
49 | // On the server with error:
50 | // 1. document.getInitialProps
51 | // 2. app.render
52 | // 3. page.render
53 | // 4. document.render
54 | //
55 | // On the client
56 | // 1. app.getInitialProps
57 | // 2. page.getInitialProps
58 | // 3. app.render
59 | // 4. page.render
60 |
61 | const originalRenderPage = ctx.renderPage;
62 |
63 | // You can consider sharing the same emotion cache between all the SSR requests to speed up performance.
64 | // However, be aware that it can have global side effects.
65 | const cache = createEmotionCache();
66 | const { extractCriticalToChunks } = createEmotionServer(cache);
67 |
68 | ctx.renderPage = () =>
69 | originalRenderPage({
70 | enhanceApp: (App: any) =>
71 | function EnhanceApp(props) {
72 | return ;
73 | },
74 | });
75 |
76 | const initialProps = await Document.getInitialProps(ctx);
77 | // This is important. It prevents emotion to render invalid HTML.
78 | // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
79 | const emotionStyles = extractCriticalToChunks(initialProps.html);
80 | const emotionStyleTags = emotionStyles.styles.map((style) => (
81 |
87 | ));
88 |
89 | return {
90 | ...initialProps,
91 | emotionStyleTags,
92 | };
93 | };
94 |
--------------------------------------------------------------------------------
/pages/_error.js:
--------------------------------------------------------------------------------
1 | import NextErrorComponent from 'next/error';
2 |
3 | import * as Sentry from '@sentry/nextjs';
4 |
5 | const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
6 | if (!hasGetInitialPropsRun && err) {
7 | // getInitialProps is not called in case of
8 | // https://github.com/vercel/next.js/issues/8592. As a workaround, we pass
9 | // err via _app.js so it can be captured
10 | Sentry.captureException(err);
11 | // Flushing is not required in this case as it only happens on the client
12 | }
13 |
14 | return ;
15 | };
16 |
17 | MyError.getInitialProps = async (context) => {
18 | const errorInitialProps = await NextErrorComponent.getInitialProps(context);
19 |
20 | const { res, err, asPath } = context;
21 |
22 | // Workaround for https://github.com/vercel/next.js/issues/8592, mark when
23 | // getInitialProps has run
24 | errorInitialProps.hasGetInitialPropsRun = true;
25 |
26 | // Returning early because we don't want to log 404 errors to Sentry.
27 | if (res?.statusCode === 404) {
28 | return errorInitialProps;
29 | }
30 |
31 | // Running on the server, the response object (`res`) is available.
32 | //
33 | // Next.js will pass an err on the server if a page's data fetching methods
34 | // threw or returned a Promise that rejected
35 | //
36 | // Running on the client (browser), Next.js will provide an err if:
37 | //
38 | // - a page's `getInitialProps` threw or returned a Promise that rejected
39 | // - an exception was thrown somewhere in the React lifecycle (render,
40 | // componentDidMount, etc) that was caught by Next.js's React Error
41 | // Boundary. Read more about what types of exceptions are caught by Error
42 | // Boundaries: https://reactjs.org/docs/error-boundaries.html
43 |
44 | if (err) {
45 | Sentry.captureException(err);
46 |
47 | // Flushing before returning is necessary if deploying to Vercel, see
48 | // https://vercel.com/docs/platform/limits#streaming-responses
49 | await Sentry.flush(2000);
50 |
51 | return errorInitialProps;
52 | }
53 |
54 | // If this point is reached, getInitialProps was called without any
55 | // information about what the error might be. This is unexpected and may
56 | // indicate a bug introduced in Next.js, so record it in Sentry
57 | Sentry.captureException(
58 | new Error(`_error.js getInitialProps missing data at path: ${asPath}`),
59 | );
60 | await Sentry.flush(2000);
61 |
62 | return errorInitialProps;
63 | };
64 |
65 | export default MyError;
66 |
--------------------------------------------------------------------------------
/pages/account.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 | import Layout from "../components/layout";
3 | import { Alert, AlertTitle, Box, Grid, TextField } from "@mui/material";
4 | import fetch from "isomorphic-unfetch";
5 | import useAuth from "../hooks/useAuth";
6 | import fetcher from "../utils/fetcher";
7 | import useSWR from "swr";
8 | import dynamic from "next/dynamic";
9 |
10 | const Tokens = dynamic(() => import("../components/account/tokens"));
11 | const Success = dynamic(() => import("../components/notifications/success"));
12 |
13 | const metaTags = {
14 | title: "apr",
15 | description: "Anchor Programs Registry",
16 | shouldIndex: false,
17 | url: "https://apr.dev",
18 | };
19 |
20 | export default function Account() {
21 | const { session, status } = useAuth(true);
22 | const { data: user } = useSWR("/api/user", fetcher);
23 | const [username, setUsername] = useState("");
24 | const [show, setShow] = useState(false);
25 |
26 | useEffect(() => {
27 | if (username === "" && user) setUsername(user.username);
28 | }, [username, user]);
29 |
30 | if (!session) return null;
31 |
32 | const handleUpdateUsername = async () => {
33 | await fetch(`/api/user`, {
34 | method: "PUT",
35 | body: JSON.stringify({ username }),
36 | });
37 | setShow(true);
38 | setTimeout(() => setShow(false), 3000);
39 | };
40 |
41 | return (
42 |
43 |
44 |
45 |
55 | setUsername(e.target.value)}
61 | />
62 |
68 | Update Username
69 |
70 |
71 |
72 |
73 |
74 | https://anchor.projectserum.com
75 | If you have a user already in the old version, please continue managing your keys in
76 | that UI
77 |
78 |
79 |
80 |
81 |
82 |
88 |
89 |
90 | );
91 | }
92 |
--------------------------------------------------------------------------------
/pages/api/auth/[...nextauth].js:
--------------------------------------------------------------------------------
1 | import NextAuth from "next-auth";
2 | import CredentialsProvider from "next-auth/providers/credentials";
3 |
4 | export default NextAuth({
5 | providers: [
6 | CredentialsProvider({
7 | async authorize(credentials) {
8 | const payload = {
9 | public_key: credentials.publicKey,
10 | signed_message: credentials.signature,
11 | };
12 |
13 | const res = await fetch(
14 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/auth/v0/wallet`,
15 | {
16 | method: "POST",
17 | body: JSON.stringify(payload),
18 | headers: {
19 | "Content-Type": "application/json",
20 | },
21 | }
22 | );
23 |
24 | const user = await res.json();
25 |
26 | if (!res.ok) {
27 | throw new Error(user.exception);
28 | }
29 | // If no error and we have user data, return it
30 | if (res.ok && user) {
31 | return user;
32 | }
33 |
34 | // Return null if user data could not be retrieved
35 | return null;
36 | },
37 | }),
38 | ],
39 | callbacks: {
40 | async jwt({ token, user, account }) {
41 | if (account && user) {
42 | return {
43 | ...token,
44 | accessToken: user.token.access,
45 | refreshToken: user.token.refresh,
46 | user: {
47 | username: user.user.username,
48 | picture: user.user.image_id,
49 | pk: user.user.pk,
50 | id: user.user.id,
51 | },
52 | accessTokenExpires: Date.now() * 43200,
53 | };
54 | }
55 |
56 | // Return previous token if the access token has not expired yet
57 | if (Date.now() < token.accessTokenExpires) {
58 | return token;
59 | }
60 |
61 | // Access token has expired, try to update it
62 | return refreshAccessToken(token);
63 | },
64 |
65 | async session({ session, token }) {
66 | session.user = {
67 | accessToken: token.accessToken,
68 | refreshToken: token.refreshToken,
69 | username: token.user.username,
70 | id: token.user.id,
71 | picture: token.user.image_id,
72 | pk: token.user.pk,
73 | };
74 |
75 | return session;
76 | },
77 | },
78 | jwt: {
79 | secret: "SECRET_HERE",
80 | encryption: true,
81 | },
82 | // Enable debug messages in the console if you are having problems
83 | debug: process.env.NODE_ENV === "development",
84 | });
85 |
86 | /**
87 | * Takes a token, and returns a new token with updated
88 | * `accessToken` and `accessTokenExpires`. If an error occurs,
89 | * returns the old token and an error property
90 | */
91 | async function refreshAccessToken(token) {
92 | try {
93 | const response = await fetch(
94 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/auth/v0/refresh`,
95 | {
96 | headers: {
97 | "Content-Type": "application/json",
98 | Authorization: `Bearer ${token.accessToken}`,
99 | "X-REFRESH": token.refreshToken,
100 | },
101 | body: JSON.stringify({
102 | auth: {
103 | access: token.accessToken,
104 | refresh: token.refreshToken,
105 | },
106 | }),
107 | method: "POST",
108 | }
109 | );
110 |
111 | const refreshedTokens = await response.json();
112 |
113 | if (!response.ok) {
114 | throw refreshedTokens;
115 | }
116 |
117 | return {
118 | ...token,
119 | accessToken: refreshedTokens.access,
120 | accessTokenExpires: Date.now() * 43200,
121 | username: token.user.username,
122 | picture: token.user.image_id,
123 | id: token.user.id,
124 | pk: token.user.pk,
125 | refreshToken: refreshedTokens.refresh ?? token.refreshToken, // Fall back to old refresh token
126 | };
127 | } catch (error) {
128 | console.error(error);
129 |
130 | return {
131 | ...token,
132 | error: "RefreshAccessTokenError",
133 | };
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/pages/api/idl.ts:
--------------------------------------------------------------------------------
1 | import { NextApiRequest, NextApiResponse } from "next";
2 | import { Connection, PublicKey } from "@solana/web3.js";
3 | import { Address, AnchorProvider, Program } from "@project-serum/anchor";
4 |
5 | export default async function handler(
6 | req: NextApiRequest,
7 | res: NextApiResponse
8 | ) {
9 | if (req.method === "GET") {
10 | try {
11 | const address = req.query.address as Address;
12 |
13 | const connection = new Connection(
14 | process.env.NEXT_PUBLIC_NODE_URL as string
15 | );
16 |
17 | const provider = new AnchorProvider(
18 | connection,
19 | {
20 | publicKey: PublicKey.default,
21 | signAllTransactions: undefined,
22 | signTransaction: undefined,
23 | },
24 | { commitment: "processed", skipPreflight: true }
25 | );
26 |
27 | const idl = await Program.fetchIdl(address, provider);
28 |
29 | res.status(200).json({
30 | name: idl.name,
31 | address: address,
32 | id: 1,
33 | idl,
34 | });
35 | } catch (e) {
36 | console.error("Error:", e);
37 | res.status(500).json({ error: e.message });
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/pages/api/keys.ts:
--------------------------------------------------------------------------------
1 | import type { NextApiRequest, NextApiResponse } from "next";
2 | import { getSession } from "next-auth/react";
3 | import fetch from "isomorphic-unfetch";
4 | import { withSentry } from "@sentry/nextjs";
5 |
6 | async function handler(req: NextApiRequest, res: NextApiResponse) {
7 | const session = await getSession({ req });
8 |
9 | if (req.method === "GET") {
10 | const response = await fetch(
11 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/apikey`,
12 | {
13 | method: "GET",
14 | headers: {
15 | "Content-Type": "application/json",
16 | Authorization: `Bearer ${session.user.accessToken}`,
17 | },
18 | }
19 | );
20 |
21 | const data = await response.json();
22 |
23 | res.status(200).json(data);
24 | } else if (req.method === "POST") {
25 | try {
26 | const { name } = JSON.parse(req.body);
27 |
28 | const response = await fetch(
29 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/apikey`,
30 | {
31 | method: "POST",
32 | headers: {
33 | "Content-Type": "application/json",
34 | Authorization: `Bearer ${session.user.accessToken}`,
35 | },
36 | body: JSON.stringify({
37 | name: name,
38 | }),
39 | }
40 | );
41 |
42 | res.status(200).send(await response.json());
43 | } catch (error) {
44 | res.status(500).json({
45 | message: error.message,
46 | });
47 | }
48 | } else if (req.method === "DELETE") {
49 | try {
50 | const { id } = JSON.parse(req.body);
51 |
52 | await fetch(
53 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/apikey/revoke`,
54 | {
55 | method: "POST",
56 | headers: {
57 | "Content-Type": "application/json",
58 | Authorization: `Bearer ${session.user.accessToken}`,
59 | },
60 | body: JSON.stringify({
61 | id,
62 | }),
63 | }
64 | );
65 |
66 | res.status(204).send("");
67 | } catch (error) {
68 | res.status(500).json({
69 | message: error.message,
70 | });
71 | }
72 | }
73 | }
74 |
75 | export default withSentry(handler);
76 |
--------------------------------------------------------------------------------
/pages/api/user.ts:
--------------------------------------------------------------------------------
1 | import type { NextApiRequest, NextApiResponse } from "next";
2 | import { getSession } from "next-auth/react";
3 | import fetch from "isomorphic-unfetch";
4 | import { withSentry } from "@sentry/nextjs";
5 |
6 | async function handler(req: NextApiRequest, res: NextApiResponse) {
7 | const session = await getSession({ req });
8 |
9 | if (req.method === "GET") {
10 | try {
11 | const response = await fetch(
12 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/user/current/wallet`,
13 | {
14 | headers: {
15 | Authorization: `Bearer ${session.user.accessToken}`,
16 | },
17 | }
18 | );
19 | const data = await response.json();
20 |
21 | res.status(200).send(data);
22 | } catch (error) {
23 | res.status(500).json({
24 | message: error.message,
25 | });
26 | }
27 | } else if (req.method === "PUT") {
28 | const { username } = JSON.parse(req.body);
29 |
30 | try {
31 | await fetch(`${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/user`, {
32 | method: "PUT",
33 | headers: {
34 | "Content-Type": "application/json",
35 | Authorization: `Bearer ${session.user.accessToken}`,
36 | },
37 | body: JSON.stringify({
38 | id: session.user.id,
39 | image_id: session.user.picture || 0,
40 | username,
41 | }),
42 | });
43 |
44 | res.status(204).send("");
45 | } catch (error) {
46 | res.status(500).json({
47 | message: error.message,
48 | });
49 | }
50 | }
51 | }
52 |
53 | export default withSentry(handler);
54 |
--------------------------------------------------------------------------------
/pages/idl/[address].tsx:
--------------------------------------------------------------------------------
1 | import fetch from "isomorphic-unfetch";
2 | import Layout from "../../components/layout";
3 | import {
4 | ClockIcon,
5 | CodeIcon,
6 | DatabaseIcon,
7 | DocumentTextIcon,
8 | TerminalIcon,
9 | } from "@heroicons/react/solid";
10 | import dynamic from "next/dynamic";
11 |
12 | const ProgramBanner = dynamic(
13 | () => import("../../components/program/program-banner")
14 | );
15 | const Tabs = dynamic(() => import("../../components/program/tabs"));
16 |
17 | const tabs = [
18 | { name: "Readme", icon: DocumentTextIcon, disabled: true },
19 | { name: "Explorer", icon: CodeIcon, disabled: true },
20 | { name: "IDL", icon: TerminalIcon, disabled: false },
21 | { name: "Accounts Data", icon: DatabaseIcon, disabled: true },
22 | { name: "Builds", icon: ClockIcon, disabled: true },
23 | ];
24 |
25 | export async function getStaticPaths() {
26 | return {
27 | paths: [],
28 | fallback: "blocking",
29 | };
30 | }
31 |
32 | export async function getStaticProps({ params }) {
33 | const res = await fetch(
34 | `${process.env.NEXT_PUBLIC_API}/api/idl?address=${params.address}`
35 | );
36 | const idl = await res.json();
37 |
38 | return {
39 | props: {
40 | data: idl,
41 | },
42 | revalidate: 3600,
43 | };
44 | }
45 |
46 | export default function IDLViewerPage({ data }) {
47 | const metaTags = {
48 | title: `apr - ${data?.name}`,
49 | description: `IDL Viewer - ${data?.name} - ${data?.address}`,
50 | url: `https://apr.dev/idl/${data.address}`,
51 | };
52 |
53 | return (
54 |
55 |
73 |
74 | );
75 | }
76 |
--------------------------------------------------------------------------------
/pages/index.tsx:
--------------------------------------------------------------------------------
1 | import type { GetStaticProps } from "next";
2 | import Image from "next/future/image";
3 | import fetch from "../utils/fetcher";
4 | import { useState } from "react";
5 | import dynamic from "next/dynamic";
6 | import Layout from "../components/layout";
7 | import { SearchIcon } from "@heroicons/react/outline";
8 | import { GlobalHotKeys } from "react-hotkeys";
9 |
10 | const Search = dynamic(() => import("../components/search"));
11 | const ProgramMiniCard = dynamic(
12 | () => import("../components/program-mini-card")
13 | );
14 |
15 | function loadMorePrograms(programs, amount, buildType = false) {
16 | let size;
17 |
18 | if (programs.length < amount) {
19 | size = programs.length;
20 | } else {
21 | size = amount;
22 | }
23 |
24 | let component = [];
25 | for (let i = 0; i < size; i++) {
26 | component.push(
27 |
33 | );
34 | }
35 |
36 | return component;
37 | }
38 |
39 | export async function getStaticProps({}: GetStaticProps) {
40 | const builds = await fetch(
41 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/builds/latest`
42 | );
43 | const programs = await fetch(
44 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/programs/latest`
45 | );
46 |
47 | // Sort programs by created_at (desc)
48 | programs.sort(function (a, b) {
49 | return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
50 | });
51 |
52 | // Reduce data size for UI
53 | const justUpdated = builds.map((build) => {
54 | return {
55 | id: build.id,
56 | name: build.name,
57 | address: build.address,
58 | };
59 | });
60 |
61 | let newPrograms = [];
62 | for await (const program of programs) {
63 | newPrograms.push({
64 | id: program.id,
65 | name: program.name,
66 | address: program.address,
67 | });
68 | }
69 |
70 | return {
71 | props: {
72 | justUpdated,
73 | newPrograms,
74 | },
75 | revalidate: 60,
76 | };
77 | }
78 |
79 | export default function Home({ justUpdated, newPrograms }: HomeProps) {
80 | const [open, setOpen] = useState(false);
81 | const [newProgramsSize, setNewProgramsSize] = useState(10);
82 | const [justUpdatedSize, setJustUpdatedSize] = useState(10);
83 |
84 | const keyMap = {
85 | SEARCH: "command+k",
86 | };
87 |
88 | const handlers = {
89 | SEARCH: () => setOpen(true),
90 | };
91 |
92 | const metaTags = {
93 | title: "apr",
94 | description: "Anchor Programs Registry",
95 | url: "https://apr.dev",
96 | };
97 |
98 | return (
99 | <>
100 |
101 |
102 |
103 |
104 |
112 |
113 |
114 | {/* Search */}
115 |
116 |
setOpen(true)}
118 | className="shadow-xs flex h-14 w-96 min-w-full cursor-text
119 | items-center justify-between rounded-md border border-gray-200/80 bg-gray-100 px-5 font-medium shadow hover:border-slate-200/80 hover:bg-slate-100 focus:outline-none md:w-[600px]"
120 | >
121 |
122 |
123 | Search by name or address
124 |
125 |
126 |
127 | ⌘K
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 | {/* New Programs List */}
136 |
137 |
138 | New Programs
139 |
140 |
141 | {loadMorePrograms(newPrograms, newProgramsSize)}
142 | setNewProgramsSize(newProgramsSize + 10)}
145 | >
146 | View More
147 |
148 |
149 |
150 |
151 | {/* Just Updated List */}
152 |
153 |
154 | Just Updated
155 |
156 |
157 | {loadMorePrograms(justUpdated, justUpdatedSize, true)}
158 | setJustUpdatedSize(justUpdatedSize + 10)}
161 | >
162 | View More
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 | >
171 | );
172 | }
173 |
174 | interface HomeProps {
175 | justUpdated: any[];
176 | newPrograms: any[];
177 | }
178 |
--------------------------------------------------------------------------------
/pages/program/[address]/build/[id].tsx:
--------------------------------------------------------------------------------
1 | import { GetStaticPaths, GetStaticProps } from "next";
2 | import fetch from "../../../../utils/fetcher";
3 | import fetchMD from "../../../../utils/fetcher-md";
4 | import markdownToHtml from "../../../../utils/markdown";
5 | import dynamic from "next/dynamic";
6 | import Layout from "../../../../components/layout";
7 | import buildStatus from "../../../../utils/build-status";
8 |
9 | const ProgramComponent = dynamic(
10 | () => import("../../../../components/program")
11 | );
12 |
13 | export const getStaticPaths: GetStaticPaths = async () => {
14 | if (process.env.SKIP_BUILD_STATIC_GENERATION) {
15 | return { paths: [], fallback: "blocking" };
16 | }
17 |
18 | const builds: any[] = await fetch(
19 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/builds/latest`
20 | );
21 |
22 | const paths = builds.map((build) => {
23 | return {
24 | params: {
25 | address: build.address,
26 | id: build.id.toString(),
27 | },
28 | };
29 | });
30 |
31 | // All missing paths are going to be server-side rendered and cached
32 | return { paths, fallback: "blocking" };
33 | };
34 |
35 | export const getStaticProps: GetStaticProps = async ({ params }) => {
36 | const program = await fetch(
37 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/program/${params.address}`
38 | );
39 | let builds = await fetch(
40 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/program/${params.address}/latest`
41 | );
42 |
43 | // find the selected build,
44 | const selectedBuild = builds.find(
45 | (build) => build.id.toString() === params.id
46 | );
47 |
48 | // Find selected build artifacts
49 | selectedBuild.artifacts = await fetch(
50 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/build/${selectedBuild.id}/artifacts`
51 | );
52 |
53 | let slimBuilds = [];
54 | for await (const build of builds) {
55 | slimBuilds.push({
56 | buildStatus: await buildStatus(build, false),
57 | id: build.id,
58 | address: build.address,
59 | updated_at: build.updated_at,
60 | sha256: build.sha256,
61 | });
62 | }
63 |
64 | // If the program contains a Readme, we need to process it
65 | let readmeUrl: string | boolean = false;
66 |
67 | selectedBuild.descriptor.forEach((item) => {
68 | if (item.split(":")[0] === "README.md") {
69 | readmeUrl = item.split(":")[2];
70 | }
71 | });
72 |
73 | let readme: string | boolean;
74 | if (readmeUrl) {
75 | readme = await fetchMD(`https://${readmeUrl}`);
76 | } else {
77 | readme = false;
78 | }
79 | readme = await markdownToHtml(readme || "");
80 |
81 | selectedBuild.buildStatus = await buildStatus(selectedBuild, true);
82 |
83 | return {
84 | props: {
85 | program,
86 | builds: slimBuilds,
87 | selectedBuild,
88 | readme,
89 | files: selectedBuild?.descriptor || null,
90 | },
91 | revalidate: 60,
92 | };
93 | };
94 |
95 | export default function ProgramBuild({
96 | program,
97 | selectedBuild,
98 | builds,
99 | readme,
100 | files,
101 | }: AddressProps) {
102 | const metaTags = {
103 | title: `apr - ${selectedBuild.name}`,
104 | description: `apr - ${selectedBuild.name} - ${selectedBuild.address}`,
105 | url: `https://apr.dev/program/${selectedBuild.address}/build/${selectedBuild.id}`,
106 | };
107 |
108 | return (
109 |
110 |
117 |
118 | );
119 | }
120 |
121 | interface AddressProps {
122 | program: any;
123 | builds: any[];
124 | selectedBuild: any;
125 | readme: string;
126 | files: string[];
127 | }
128 |
--------------------------------------------------------------------------------
/pages/program/[address]/index.tsx:
--------------------------------------------------------------------------------
1 | import { GetStaticPaths, GetStaticProps } from "next";
2 | import fetch from "../../../utils/fetcher";
3 | import fetchMD from "../../../utils/fetcher-md";
4 | import markdownToHtml from "../../../utils/markdown";
5 | import dynamic from "next/dynamic";
6 | import Layout from "../../../components/layout";
7 | import buildStatus from "../../../utils/build-status";
8 |
9 | const ProgramComponent = dynamic(() => import("../../../components/program"));
10 |
11 | export const getStaticPaths: GetStaticPaths = async () => {
12 | if (process.env.SKIP_BUILD_STATIC_GENERATION) {
13 | return { paths: [], fallback: "blocking" };
14 | }
15 |
16 | const programs = await fetch(
17 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/programs/latest`
18 | );
19 |
20 | const paths: any[] = [];
21 |
22 | for (let i = 0; i < programs.length; i++) {
23 | // Patch for weird issue, will fix later
24 | if (
25 | programs[i].address === "So1endDq2YkqhipRh3WViPa8hdiSpxWy6z3Z6tMCpAo" ||
26 | programs[i].address === "ninaN2tm9vUkxoanvGcNApEeWiidLMM2TdBX8HoJuL4"
27 | )
28 | continue;
29 |
30 | paths.push({
31 | params: {
32 | address: programs[i].address,
33 | },
34 | });
35 | }
36 |
37 | // All missing paths are going to be server-side rendered and cached
38 | return { paths, fallback: "blocking" };
39 | };
40 |
41 | export const getStaticProps: GetStaticProps = async ({ params }) => {
42 | const program = await fetch(
43 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/program/${params.address}`
44 | );
45 | let builds = await fetch(
46 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/program/${params.address}/latest`
47 | );
48 |
49 | let selectedBuild = builds[0] || {};
50 |
51 | // Find selected build artifacts
52 | selectedBuild.artifacts = await fetch(
53 | `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/v0/build/${selectedBuild.id}/artifacts`
54 | );
55 |
56 | let slimBuilds = [];
57 | for await (const build of builds) {
58 | const status = await buildStatus(build, false);
59 |
60 | slimBuilds.push({
61 | buildStatus: status,
62 | id: build.id,
63 | address: build.address,
64 | updated_at: build.updated_at,
65 | sha256: build.sha256,
66 | });
67 | }
68 |
69 | // If the program contains a Readme, we need to process it
70 | let readmeUrl: string | boolean = false;
71 |
72 | selectedBuild.descriptor.forEach((item) => {
73 | if (item.split(":")[0] === "README.md") {
74 | readmeUrl = item.split(":")[2];
75 | }
76 | });
77 |
78 | let readme: string | boolean;
79 | if (readmeUrl) {
80 | readme = await fetchMD(`https://${readmeUrl}`);
81 | } else {
82 | readme = false;
83 | }
84 | readme = await markdownToHtml(readme || "");
85 |
86 | selectedBuild.buildStatus = await buildStatus(selectedBuild, true);
87 |
88 | return {
89 | props: {
90 | program,
91 | builds: slimBuilds,
92 | selectedBuild,
93 | readme,
94 | files: selectedBuild?.descriptor || null,
95 | },
96 | revalidate: 60,
97 | };
98 | };
99 |
100 | export default function Program({
101 | program,
102 | selectedBuild,
103 | builds,
104 | readme,
105 | files,
106 | }: ProgramProps) {
107 | const metaTags = {
108 | title: `apr - ${selectedBuild.name}`,
109 | description: `apr - ${selectedBuild.name} - ${selectedBuild.address}`,
110 | url: `https://apr.dev/program/${selectedBuild.address}`,
111 | };
112 |
113 | return (
114 |
115 |
122 |
123 | );
124 | }
125 |
126 | interface ProgramProps {
127 | program: any;
128 | builds: any[];
129 | selectedBuild: any;
130 | readme: string;
131 | files: string[];
132 | }
133 |
--------------------------------------------------------------------------------
/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | },
6 | };
7 |
--------------------------------------------------------------------------------
/public/banner-text copy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/banner-text copy.png
--------------------------------------------------------------------------------
/public/banner-text.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/banner-text.png
--------------------------------------------------------------------------------
/public/boxes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/boxes.png
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/favicon.ico
--------------------------------------------------------------------------------
/public/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/logo.png
--------------------------------------------------------------------------------
/public/missing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/missing.png
--------------------------------------------------------------------------------
/public/social.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coral-xyz/apr-ui/b0d144f3d4583cef565d25ab9e36d8dc2c1b8f09/public/social.png
--------------------------------------------------------------------------------
/sentry.client.config.js:
--------------------------------------------------------------------------------
1 | // This file configures the initialization of Sentry on the browser.
2 | // The config you add here will be used whenever a page is visited.
3 | // https://docs.sentry.io/platforms/javascript/guides/nextjs/
4 |
5 | import * as Sentry from "@sentry/nextjs";
6 | import { BrowserTracing } from "@sentry/tracing";
7 |
8 | const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;
9 |
10 | Sentry.init({
11 | dsn: SENTRY_DSN,
12 | integrations: [new BrowserTracing()],
13 | // Adjust this value in production, or use tracesSampler for greater control
14 | tracesSampleRate: 1.0,
15 | // ...
16 | // Note: if you want to override the automatic release value, do not set a
17 | // `release` value here - use the environment variable `SENTRY_RELEASE`, so
18 | // that it will also get attached to your source maps
19 | environment: process.env.VERCEL_ENV,
20 | });
21 |
--------------------------------------------------------------------------------
/sentry.properties:
--------------------------------------------------------------------------------
1 | defaults.url=https://sentry.io/
2 | defaults.org=coral-ob
3 | defaults.project=apr-ui
4 | cli.executable=../../../.npm/_npx/a8388072043b4cbc/node_modules/@sentry/cli/bin/sentry-cli
5 |
--------------------------------------------------------------------------------
/sentry.server.config.js:
--------------------------------------------------------------------------------
1 | // This file configures the initialization of Sentry on the server.
2 | // The config you add here will be used whenever the server handles a request.
3 | // https://docs.sentry.io/platforms/javascript/guides/nextjs/
4 |
5 | import * as Sentry from "@sentry/nextjs";
6 |
7 | const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;
8 |
9 | Sentry.init({
10 | dsn: SENTRY_DSN,
11 | // Adjust this value in production, or use tracesSampler for greater control
12 | tracesSampleRate: 1.0,
13 | // ...
14 | // Note: if you want to override the automatic release value, do not set a
15 | // `release` value here - use the environment variable `SENTRY_RELEASE`, so
16 | // that it will also get attached to your source maps
17 | environment: process.env.VERCEL_ENV,
18 | });
19 |
--------------------------------------------------------------------------------
/src/Copyright.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import Typography from '@mui/material/Typography';
3 | import MuiLink from '@mui/material/Link';
4 |
5 | export default function Copyright() {
6 | return (
7 |
8 | {'Copyright © '}
9 |
10 | Your Website
11 | {' '}
12 | {new Date().getFullYear()}.
13 |
14 | );
15 | }
16 |
--------------------------------------------------------------------------------
/src/ProTip.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import Link from '@mui/material/Link';
3 | import SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon';
4 | import Typography from '@mui/material/Typography';
5 |
6 | function LightBulbIcon(props: SvgIconProps) {
7 | return (
8 |
9 |
10 |
11 | );
12 | }
13 |
14 | export default function ProTip() {
15 | return (
16 |
17 |
18 | Pro tip: See more templates on
19 | the MUI documentation.
20 |
21 | );
22 | }
23 |
--------------------------------------------------------------------------------
/src/createEmotionCache.ts:
--------------------------------------------------------------------------------
1 | import createCache from '@emotion/cache';
2 |
3 | // prepend: true moves MUI styles to the top of the so they're loaded first.
4 | // It allows developers to easily override MUI styles with other styling solutions, like CSS modules.
5 | export default function createEmotionCache() {
6 | return createCache({ key: 'css', prepend: true });
7 | }
8 |
--------------------------------------------------------------------------------
/src/theme.ts:
--------------------------------------------------------------------------------
1 | import { createTheme } from "@mui/material/styles";
2 |
3 | // Create a theme instance.
4 | const theme = createTheme({
5 | typography: {
6 | fontFamily: 'Inter',
7 | },
8 | palette: {
9 | primary: {
10 | main: "#fafafa",
11 | },
12 | secondary: {
13 | main: "#212121",
14 | },
15 | },
16 | });
17 |
18 | export default theme;
19 |
--------------------------------------------------------------------------------
/style.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 |
6 | a {
7 | text-decoration: none;
8 | color: black;
9 | }
10 |
--------------------------------------------------------------------------------
/tailwind.config.js:
--------------------------------------------------------------------------------
1 | const defaultTheme = require("tailwindcss/defaultTheme");
2 |
3 | /** @type {import('tailwindcss').Config} */
4 | module.exports = {
5 | content: [
6 | "./pages/**/*.{js,ts,jsx,tsx}",
7 | "./components/**/*.{js,ts,jsx,tsx}",
8 | ],
9 | theme: {
10 | extend: {
11 | fontFamily: {
12 | sans: ["Inter", ...defaultTheme.fontFamily.sans],
13 | },
14 | },
15 | },
16 | plugins: [
17 | require("@tailwindcss/forms"),
18 | require("@tailwindcss/typography"),
19 | require("@tailwindcss/aspect-ratio"),
20 | ],
21 | };
22 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es6",
4 | "lib": ["dom", "dom.iterable", "esnext"],
5 | "allowJs": true,
6 | "skipLibCheck": true,
7 | "strict": false,
8 | "forceConsistentCasingInFileNames": true,
9 | "noEmit": true,
10 | "esModuleInterop": true,
11 | "module": "esnext",
12 | "moduleResolution": "node",
13 | "resolveJsonModule": true,
14 | "isolatedModules": true,
15 | "jsx": "preserve",
16 | "jsxImportSource": "@emotion/react",
17 | "incremental": true,
18 | "typeRoots": ["./node_modules/@types", "./types"]
19 | },
20 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
21 | "exclude": ["node_modules"]
22 | }
23 |
--------------------------------------------------------------------------------
/types/index.d.ts:
--------------------------------------------------------------------------------
1 | export {};
2 |
3 | declare global {
4 | interface Window {
5 | solana: any;
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/types/next-auth.d.ts:
--------------------------------------------------------------------------------
1 | import { DefaultSession } from "next-auth";
2 |
3 | declare module "next-auth" {
4 | interface Session {
5 | user: {
6 | accessToken: string;
7 | id: string;
8 | picture: number;
9 | } & DefaultSession["user"];
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/utils/apps-data.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "promoted": true,
4 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
5 | "id": 0,
6 | "name": "Mango Swap",
7 | "category": "Swap",
8 | "description": "Swap your Tokens"
9 | },
10 | {
11 | "promoted": false,
12 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
13 | "id": 1,
14 | "name": "Jupiter",
15 | "category": "Swap",
16 | "description": "Swap your Tokens"
17 | },
18 | {
19 | "promoted": false,
20 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
21 | "id": 2,
22 | "name": "Serum Surfers NFT",
23 | "category": "NFT",
24 | "description": "Mint Surum Surfers"
25 | },
26 | {
27 | "promoted": true,
28 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
29 | "id": 3,
30 | "name": "Ardrive",
31 | "category": "Storage",
32 | "description": "Store data in arweave"
33 | },
34 | {
35 | "promoted": false,
36 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
37 | "id": 4,
38 | "name": "Mango Swap",
39 | "category": "Swap",
40 | "description": "Swap your Tokens"
41 | },
42 | {
43 | "promoted": false,
44 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
45 | "id": 5,
46 | "name": "Serum Surfers NFT",
47 | "category": "NFT",
48 | "description": "Mint Surum Surfers"
49 | },
50 | {
51 | "promoted": false,
52 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
53 | "id": 6,
54 | "name": "Ardrive",
55 | "category": "Storage",
56 | "description": "Store data in arweave"
57 | },
58 | {
59 | "promoted": false,
60 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
61 | "id": 7,
62 | "name": "Mango Swap",
63 | "category": "Swap",
64 | "description": "Swap your Tokens"
65 | },
66 | {
67 | "promoted": false,
68 | "tx": "nnLNdp6nuTb8mJ-qOgbUEx-9SBtBXQc_jejYOWzYEkM",
69 | "id": 8,
70 | "name": "Serum Surfers NFT",
71 | "category": "NFT",
72 | "description": "Mint Surum Surfers"
73 | }
74 | ]
75 |
--------------------------------------------------------------------------------
/utils/build-status.ts:
--------------------------------------------------------------------------------
1 | import networkStatus from "./network-status";
2 |
3 | /**
4 | * Returns the current build status.
5 | * @param build Program build
6 | * @param confirmNetwork Whether to confirm the network status
7 | * @returns {Promise}
8 | */
9 | export default async function buildStatus(
10 | build: any,
11 | confirmNetwork: boolean
12 | ): Promise {
13 | if (build.verified === "Verified") {
14 | // Confirm the build is verified in mainnet. Only needed
15 | // for selected builds.
16 | if (confirmNetwork) {
17 | const networkVerified = await networkStatus(build.address);
18 |
19 | if (networkVerified) {
20 | return "verified";
21 | }
22 |
23 | return "failed";
24 | }
25 |
26 | return "verified";
27 | } else if (build.aborted) {
28 | return "aborted";
29 | } else if (build.state === "Ready" && build.verified === "None") {
30 | return "building";
31 | } else if (build.state === "Built" && build.verified === "None") {
32 | return "built";
33 | } else {
34 | return "failed";
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/utils/fetcher-md.js:
--------------------------------------------------------------------------------
1 | import fetch from "isomorphic-unfetch";
2 |
3 | export default async function FetcherMD(...args) {
4 | const res = await fetch(...args);
5 |
6 | return res.text();
7 | }
8 |
--------------------------------------------------------------------------------
/utils/fetcher-multi.js:
--------------------------------------------------------------------------------
1 | import fetch from "isomorphic-unfetch";
2 |
3 | export default async function FetcherMulti(...args) {
4 | const res = await fetch(...args);
5 | const text = await res.text();
6 |
7 | console.log(json);
8 | return { text, json };
9 | }
10 |
--------------------------------------------------------------------------------
/utils/fetcher.js:
--------------------------------------------------------------------------------
1 | import fetch from "isomorphic-unfetch";
2 |
3 | // eslint-disable-next-line
4 | export default async function Fetcher(...args) {
5 | const res = await fetch(...args);
6 | return res.json();
7 | }
8 |
--------------------------------------------------------------------------------
/utils/files-tree.ts:
--------------------------------------------------------------------------------
1 | export default function filesTree(paths: string[]): any {
2 | let result = [];
3 | let level = { result };
4 |
5 | paths.forEach((path) => {
6 | let parts = path.split(":")[0];
7 | let url = path.split(":")[1] + ":" + path.split(":")[2];
8 | parts.split("/").reduce((r, name, i, a) => {
9 | if (!r[name]) {
10 | r[name] = { result: [] };
11 | let type = name.split(".").length > 1 ? "file" : "folder";
12 |
13 | if (type === "folder" && name === "LICENSE") {
14 | type = "file";
15 | }
16 |
17 | const elem = { name, type, children: r[name].result, url: "" };
18 | if (type === "file") elem.url = url;
19 | r.result.push(elem);
20 | }
21 |
22 | return r[name];
23 | }, level);
24 | });
25 |
26 | return result;
27 | }
28 |
--------------------------------------------------------------------------------
/utils/format-date.ts:
--------------------------------------------------------------------------------
1 | // Format date to show plain english time elapsed
2 | export default function FormatDate(date: string): string {
3 | const time = new Date(date).getTime();
4 | const now = new Date().getTime();
5 | const diff = (now - time) / 1000;
6 | const day = Math.floor(diff / 86400);
7 | const hour = Math.floor(diff / 3600);
8 | const minute = Math.floor(diff / 60);
9 | const second = Math.floor(diff);
10 | if (day > 0) {
11 | return `${day} day${day > 1 ? "s" : ""} ago`;
12 | } else if (hour > 0) {
13 | return `${hour} hour${hour > 1 ? "s" : ""} ago`;
14 | } else if (minute > 0) {
15 | return `${minute} minute${minute > 1 ? "s" : ""} ago`;
16 | } else if (second > 0) {
17 | return `${second} second${second > 1 ? "s" : ""} ago`;
18 | } else {
19 | return "Just now";
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/utils/from-now.js:
--------------------------------------------------------------------------------
1 | export default function fromNow(input) {
2 | const date = input instanceof Date ? input : new Date(input);
3 |
4 | const formatter = new Intl.RelativeTimeFormat("en");
5 |
6 | const ranges = {
7 | years: 3600 * 24 * 365,
8 | months: 3600 * 24 * 30,
9 | weeks: 3600 * 24 * 7,
10 | days: 3600 * 24,
11 | hours: 3600,
12 | minutes: 60,
13 | seconds: 1,
14 | };
15 |
16 | const secondsElapsed = (date.getTime() - Date.now()) / 1000;
17 |
18 | for (let key in ranges) {
19 | if (ranges[key] < Math.abs(secondsElapsed)) {
20 | const delta = secondsElapsed / ranges[key];
21 | return formatter.format(Math.round(delta), key);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/utils/loadMoreApps.js:
--------------------------------------------------------------------------------
1 | import AppMiniCard from "../components/apps/app-mini-card";
2 |
3 | export default function loadMoreApps(apps, amount) {
4 | let size;
5 |
6 | if (apps.length < amount) {
7 | size = apps.length;
8 | } else {
9 | size = amount;
10 | }
11 |
12 | let component = [];
13 | for (let i = 0; i < size; i++) {
14 | component.push(
15 |
22 | );
23 | }
24 |
25 | return component;
26 | }
27 |
--------------------------------------------------------------------------------
/utils/markdown.js:
--------------------------------------------------------------------------------
1 | import { remark } from "remark";
2 | import remarkGfm from "remark-gfm";
3 | import html from "remark-html";
4 | import prism from "remark-prism";
5 |
6 | export default async function markdownToHtml(markdown) {
7 | const result = await remark()
8 | .use(remarkGfm)
9 | .use(html, { sanitize: false })
10 | .use(prism, {
11 | transformInlineCode: true,
12 | })
13 | .process(markdown);
14 |
15 | return result.toString();
16 | }
17 |
--------------------------------------------------------------------------------
/utils/network-status.ts:
--------------------------------------------------------------------------------
1 | import { Connection, PublicKey } from "@solana/web3.js";
2 | import * as anchor from "@project-serum/anchor";
3 |
4 | /**
5 | * Returns the current network status.
6 | * @param {String} programId
7 | * @return {Promise}
8 | */
9 | export default async function networkStatus(
10 | programId: string
11 | ): Promise {
12 | const pubkey = new PublicKey(programId);
13 | const connection = new Connection(process.env.NEXT_PUBLIC_NODE_URL as string);
14 |
15 | try {
16 | const result = await anchor.utils.registry.verifiedBuild(
17 | connection,
18 | pubkey,
19 | 10
20 | );
21 |
22 | if (result === null) return false;
23 | } catch (e) {
24 | console.log("Error: ", e);
25 | return false;
26 | }
27 |
28 | return true;
29 | }
30 |
--------------------------------------------------------------------------------
/utils/renderArguments.tsx:
--------------------------------------------------------------------------------
1 | export default function renderArguments(args) {
2 | let component = [];
3 |
4 | for (let i = 0; i < args.length; i++) {
5 | let type = "";
6 |
7 | if (args[i].type.array) {
8 | type = `[${args[i].type.array[0]}; ${args[i].type.array[1]}]`;
9 | } else if (args[i].type.vec) {
10 | if (args[i].type.vec.defined) {
11 | type = `Vec<${args[i].type.vec.defined}>`;
12 | } else if (args[i].type.vec.array) {
13 | type = `Vec<[${args[i].type.vec.array[0]}; ${args[i].type.vec.array[1]}]>`;
14 | } else {
15 | type = `Vec<${args[i].type.vec}>`;
16 | }
17 | } else if (args[i].type.defined) {
18 | type = args[i].type.defined;
19 | } else if (args[i].type.option) {
20 | type = `Option<${args[i].type.option}>`;
21 | } else {
22 | type = args[i].type;
23 | }
24 | component.push(
25 |
26 |
27 | {args[i].name}:
28 |
29 | `{type}`
30 |
31 | {args[i].index && (
32 |
33 | index
34 |
35 | )}
36 |
37 |
38 | );
39 | }
40 |
41 | return component;
42 | }
43 |
--------------------------------------------------------------------------------