diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 0000000..2cc1dae --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json", + "changelog": ["@changesets/changelog-github", { "repo": "scio-labs/inkathon" }], + "commit": false, + "fixed": [], + "privatePackages": { "version": true, "tag": true }, + "linked": [["@inkathon/*"]], + "baseBranch": "main", + "updateInternalDependencies": "patch" +} diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml new file mode 100644 index 0000000..6b07c5b --- /dev/null +++ b/.github/workflows/add-to-project.yml @@ -0,0 +1,22 @@ +# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json +name: Add issue or pull request to project + +on: + issues: + types: + - opened + - reopened + # pull_request: + # types: + # - opened + # - reopened + +jobs: + add-to-project: + name: Add issue or pull request to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v0.5.0 + with: + project-url: https://github.com/orgs/scio-labs/projects/3 + github-token: ${{ secrets.ADD_TO_PROJECT_PAT }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2d23c94 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,49 @@ +# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json +name: Release + +on: + push: + branches: + - main + +concurrency: ${{ github.workflow }}-${{ github.ref }} + +jobs: + release: + name: Release + runs-on: ubuntu-latest + strategy: + matrix: + node-version: [20] + pnpm-version: [8.11] + steps: + - name: Checkout Repo + uses: actions/checkout@v3 + with: + # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits + fetch-depth: 0 + submodules: true + + - name: Set up pnpm action ${{ matrix.pnpm-version }} + uses: pnpm/action-setup@v2 + with: + version: ${{ matrix.pnpm-version }} + + - name: Set up Node ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + cache: 'pnpm' + node-version: ${{ matrix.node-version }} + + - name: Install Dependencies + run: pnpm install --frozen-lockfile + + - name: Create Release Pull Request + uses: changesets/action@v1 + with: + title: 'chore(changeset): Bump package version' + commit: 'chore(changeset): Bump package version' + version: pnpm changeset version + publish: pnpm changeset publish + env: + GITHUB_TOKEN: ${{ secrets.CHANGESETS_PAT }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..657428b --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# package management +**/node_modules +**/.pnp +.pnp.js +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env +.env*.local + +# vercel +.vercel +.gitsigners + +# typescript +*.tsbuildinfo +dist + +# turbo +.turbo + +# coverage +coverage +coverage.json + +# VSCode +.history/ diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..3bf54bc --- /dev/null +++ b/.npmrc @@ -0,0 +1,10 @@ +init-author-name=Scio Labs +init-author-email=hello@scio.xyz +init-author-url=https://scio.xyz/ +init-license=GPL-3.0 + +auto-install-peers = true +enable-pre-post-scripts = true + +public-hoist-pattern[]=*eslint* +public-hoist-pattern[]=*prettier* diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..85aee5a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +v20 \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..696a85e --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +package-lock.json +pnpm-lock.yaml +node_modules +LICENSE \ No newline at end of file diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 0000000..d6f6bc5 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,8 @@ +module.exports = { + semi: false, + singleQuote: true, + trailingComma: 'all', + printWidth: 100, + tabWidth: 2, + useTabs: false, +} diff --git a/.simple-git-hooks.js b/.simple-git-hooks.js new file mode 100644 index 0000000..f507fab --- /dev/null +++ b/.simple-git-hooks.js @@ -0,0 +1,8 @@ +module.exports = { + 'pre-commit': ` +export NVM_DIR="$HOME/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" + +pnpm lint-staged + `, +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..a18c1bd --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,13 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "wayou.vscode-todo-highlight", + "tamasfe.even-better-toml", + "rust-lang.rust-analyzer", + "ink-analyzer.ink-analyzer", + "gruntfuggly.todo-tree", + "mikestead.dotenv", + "bradlc.vscode-tailwindcss" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..238a4e4 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,47 @@ +{ + "search.exclude": { + "**/*.{jpg,jpeg,png,svg,webm,mp4,ttf,woff,woff2}": true + }, + "search.useIgnoreFiles": true, + "search.useGlobalIgnoreFiles": true, + "search.useParentIgnoreFiles": true, + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "always", + "source.fixAll.eslint": "always" + }, + "files.associations": { + ".env.*": "dotenv", + "*.css": "tailwindcss" + }, + "[javascriptreact][typescriptreact][javascript][typescript][markdown][html][css][scss][sass][json][jsonc][yaml]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[javascriptreact][typescriptreact][javascript][typescript]": { + "tailwindCSS.experimental.classRegex": [ + ["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"], + ["cx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"] + ] + }, + "typescript.updateImportsOnFileMove.enabled": "always", + "javascript.updateImportsOnFileMove.enabled": "always", + "javascript.preferences.importModuleSpecifier": "shortest", + "typescript.preferences.importModuleSpecifier": "shortest", + "[toml]": { + "editor.defaultFormatter": "tamasfe.even-better-toml" + }, + "evenBetterToml.formatter.indentString": " ", + "evenBetterToml.formatter.columnWidth": 120, + "[rust]": { + "editor.defaultFormatter": "rust-lang.rust-analyzer" + }, + "peacock.color": "#8758FF", + "workbench.colorCustomizations": { + "sash.hoverBorder": "#ac8bff", + "statusBar.background": "#8758ff", + "statusBar.foreground": "#e7e7e7", + "statusBarItem.hoverBackground": "#ac8bff", + "statusBarItem.remoteBackground": "#8758ff", + "statusBarItem.remoteForeground": "#e7e7e7" + } +} diff --git a/.vscode/workshop.code-snippets b/.vscode/workshop.code-snippets new file mode 100644 index 0000000..841288e --- /dev/null +++ b/.vscode/workshop.code-snippets @@ -0,0 +1,109 @@ +{ + "Workshop Contracts Snippet #1": { + "scope": "rust", + "prefix": "Workshop Contracts Snippet #1", + "body": [ + "/// Reverses and stores the `message` string", + "#[ink(message)]", + "pub fn reverse_message(&mut self) {", + " self.message = self.message.chars().rev().collect::();", + "}" + ] + }, + "Workshop Contracts Snippet #2": { + "scope": "rust", + "prefix": "Workshop Contracts Snippet #2", + "body": [ + "#[ink::test]", + "fn reverse_message_works() {", + " let message_1 = String::from(\"gm ink!\");", + " let message_1_reversed = String::from(\"!kni mg\");", + " let mut greeter = Greeter::new(message_1.clone());", + " assert_eq!(greeter.greet(), message_1);", + " greeter.reverse_message();", + " assert_eq!(greeter.greet(), message_1_reversed);", + "}" + ] + }, + "Workshop Frontend Snippet #1": { + "scope": "typescriptreact", + "prefix": "Workshop Frontend Snippet #1", + "body": [ + "// Reverse Greeting", + "const reverseGreeting = async () => {", + " if (!activeAccount || !contract || !activeSigner || !api) {", + " toast.error('Wallet not connected. Try again…')", + " return", + " }", + "", + " setUpdateIsLoading(true)", + " try {", + " await contractTxWithToast(api, activeAccount.address, contract, 'reverseMessage', {}, [])", + " } catch (e) {", + " console.error(e)", + " } finally {", + " setUpdateIsLoading(false)", + " await fetchGreeting()", + " }", + "}", + ] + }, + "Workshop Frontend Snippet #2": { + "scope": "typescriptreact", + "prefix": "Workshop Frontend Snippet #2", + "body": [ + "{/* Reverse Greeting */}", + "", + " ", + " ", + " Submit", + " ", + " ", + "", + ] + } + "Workshop Scripts Snippet #1": { + "scope": "typescript", + "prefix": "Workshop Scripts Snippet #1", + "body": [ + "import { transferBalance } from '@scio-labs/use-inkathon'", + "import { initPolkadotJs } from './utils/initPolkadotJs'", + "", + "/**", + " * Example script that transfers tokens to the passed address from Alice.", + " *", + " * Parameters:", + " * - `ACCOUNT_URI`: Sender address URI (i.e. `//Alice`)", + " * - `ADDRESS`: Receiver address", + " * - `AMOUNT`: Token amount to transfer (optional, defaults to `100`)", + " * - `CHAIN`: Chain ID (optional, defaults to `development`)", + " *", + " * Example usage:", + " * - `ADDRESS=5fei… pnpm run script make-it-rain`", + " */", + "const main = async () => {", + " const { api, account, toBNWithDecimals } = await initPolkadotJs()", + "", + " const receiverAddress = process.env.ADDRESS", + " if (!receiverAddress) throw new Error('Missing `ADDRESS` variable')", + " const tokenAmount = toBNWithDecimals(process.env.AMOUNT ? parseInt(process.env.AMOUNT) : 100)", + "", + " console.log(`\nTransferring ${tokenAmount} tokens to ${receiverAddress}…`)", + " await transferBalance(api, account, receiverAddress, tokenAmount)", + "}", + "", + "main()", + " .catch((error) => {", + " console.error(error)", + " process.exit(1)", + " })", + " .finally(() => process.exit(0))", + ] + } +} diff --git a/.yarnrc.yml b/.yarnrc.yml new file mode 100644 index 0000000..3186f3f --- /dev/null +++ b/.yarnrc.yml @@ -0,0 +1 @@ +nodeLinker: node-modules diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..829fd1f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,45 @@ +# Contributing Guidelines + +[Scio Labs](https://scio.xyz) actively welcomes contributions from anyone to make this a community-driven effort. There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests, or writing code. + +Our ink! developer tooling initiative is made up of the following projects: + +- `create-ink-app` CLI (_Coming soon_) +- [`ink!athon`](https://github.com/scio-labs/inkathon) Boilerplate +- [`useInkathon`](https://github.com/scio-labs/use-inkathon) Hooks & Utility Library +- [`zink!`](https://github.com/scio-labs/zink) Smart Contract Macros + +_To ensure a smooth and efficient collaboration, please follow the guidelines below._ + +## Issues + +- Before starting work, please check the existing issues for your planned feature or bug fix. +- If there isn't an existing issue, create one. This allows us to avoid duplicate work and discuss the implementation details upfront. +- If you want to work on an issue, please comment on it to let us know. This helps us keep track of who is working on what. + +## Pull Requests + +- All changes should be made through pull requests (PRs). +- Please ensure your PR is linked to the relevant issue. +- Include a clear and detailed description of the changes in your PR. +- Request a review once your PR is ready. + +## Code Style + +- Please follow the existing coding style. +- Make sure your changes pass the lint checks. + +> [!IMPORTANT] +> +> - Please install all recommended VSCode extensions (see `.vscode/extensions.json`). +> - After installing dependencies, enable the `pre-commit` hook in your local repository via `pnpm simple-git-hooks`. +> - Make sure to always use the `inkathon.code-workspace` file when working on the project in VSCode. + +## Communication + +- Be respectful and considerate in all interactions. +- If you have questions or need help, don't hesitate to ask. +- For code, feature, or bug discussions, please use the relevant GitHub issue or PR. +- To chat with us or ask questions, join our [Telegram Group](https://t.me/inkathon). πŸ’¬ + +Thanks for your contributions! πŸ™ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c2a0cce --- /dev/null +++ b/README.md @@ -0,0 +1,327 @@ +![inkathon Devtooling Banner](inkathon-devtooling-banner.png) + +# ink!athon Boilerplate + +[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) +[![Built with ink!](https://raw.githubusercontent.com/paritytech/ink/master/.images/badge.svg)](https://use.ink) +![Rust](https://img.shields.io/badge/Rust-000000?logo=rust&logoColor=white) +![TypeScript](https://img.shields.io/badge/TypeScript-000000?logo=typescript&logoColor=white) +![Next.js](https://img.shields.io/badge/Next.js-000000?logo=next.js&logoColor=white) + +This is a full-stack dApp boilerplate for ink! smart contracts with an integrated frontend. It can be used to quickly start developing your hackathon idea or to scaffold a production-ready Web3 application. + +The project is part of a [Scio Labs](https://scio.xyz) initiative to improve the developer experience in the ink! ecosystem and a proud member of the [Aleph Zero EFP](https://alephzero.org/ecosystem-funding-program). πŸ’œ + +Other projects include: + +- `create-ink-app` CLI (_Coming soon_) +- [`ink!athon`](https://github.com/scio-labs/inkathon) Boilerplate +- [`useInkathon`](https://github.com/scio-labs/use-inkathon) Hooks & Utility Library +- [`zink!`](https://github.com/scio-labs/zink) Smart Contract Macros + +**Join the discussion in our [Telegram Group](https://t.me/inkathon)** πŸ’¬ + +**If you want to contribute, please read our [Contributor Guidelines](https://github.com/scio-labs/inkathon/blob/main/CONTRIBUTING.md)** πŸ™ + +--- + +**Table of Contents:** + +1. [About πŸ“–](#about-) +2. [Getting started πŸš€](#getting-started-) + 1. [1. Run the frontend](#1-run-the-frontend) + 2. [2. Build \& deploy contracts on a local node](#2-build--deploy-contracts-on-a-local-node) + 3. [3. Connect the frontend to the local node](#3-connect-the-frontend-to-the-local-node) +3. [Customization 🎨](#customization-) + 1. [1. Project Name](#1-project-name) + 2. [2. Custom Contracts](#2-custom-contracts) + 3. [3. Custom Scripts](#3-custom-scripts) +4. [The Stack πŸ₯ž](#the-stack-) +5. [Live Examples 🌐](#live-examples-) +6. [Deployment 🚒](#deployment-) + 1. [Environment Variables](#environment-variables) + 2. [Contract Deployment](#contract-deployment) +7. [VSCode Setup πŸ› ](#vscode-setup-) + 1. [Workspace](#workspace) + 2. [Plugins](#plugins) +8. [FAQs \& Troubleshooting πŸ’¬](#faqs--troubleshooting-) + +--- + +## About πŸ“– + +The boilerplate comes with a small sample ink! `Greeter` contract which stores a `message` (the "greeting") and allows anyone to update it. The frontend contains simple UI components to connect your wallet and interact with the contract (i.e. read & write the `message`). Try it out live on [inkathon.xyz](https://inkathon.xyz). + +## Getting started πŸš€ + +### 1. Run the frontend + +The frontend works out of the box, without a local node running, as the sample contract is pre-deployed on certain live testnets (i.e. `alephzero-testnet` and `shibuya`). Necessary deployment metadata and addresses are provided under `contracts/deployments/`. + +> **Pre-requisites:** +> +> - Setup Node.js v18+ (recommended via [nvm](https://github.com/nvm-sh/nvm) with `nvm install 18`) +> - Install [pnpm](https://pnpm.io/installation) (recommended via [Node.js Corepack](https://nodejs.org/api/corepack.html) or `npm i -g pnpm`) +> - Clone this repository + +
+Special Instructions for Windows Users + +> [!IMPORTANT] +> Windows users must either use [WSL](https://learn.microsoft.com/windows/wsl/install) (recommended) or a custom shell like [Git Bash](https://git-scm.com/downloads). PowerShell is not supported. + +> **Pre-requisites when using WSL for Linux:** +> +> - Install [WSL](https://learn.microsoft.com/windows/wsl/install) and execute _all_ commands in the WSL terminal +> - Setup Node.js v18+ (recommended via [nvm](https://github.com/nvm-sh/nvm) with `nvm install 18`) +> - Install the following npm packages globally: +> - `npm i -g npm` +> - `npm i -g pnpm node-gyp make` +> - Clone this repository into the WSL file system (e.g. `/home//inkathon`). +> +> **Tip:** You can enter `\\wsl$\` in the top bar of the Windows Explorer to access the WSL file system visually. + +
+ +```bash +# Install dependencies (once) +# NOTE: This automatically creates an `.env.local` file +pnpm install + +# Start Next.js frontend +pnpm run dev +``` + +Optionally, to enable [`simple-git-hooks`](https://github.com/toplenboren/simple-git-hooks) (for automatic linting & formatting when committing), you can run the following command once: `pnpm simple-git-hooks`. + +### 2. Build & deploy contracts on a local node + +The `contracts/package.json` file contains shorthand scripts for building, testing, and deploying your contracts. To run these scripts, you need to set `contracts/` as the active working directory in your terminal. + +> **Pre-requisites:** +> +> - Install Rust via the [Substrate Docs](https://docs.substrate.io/install/) (skip the "Compile a Substrate node" section) +> - Install [`cargo contract`](https://github.com/paritytech/cargo-contract) +> - Install [`substrate-contracts-node`](https://github.com/paritytech/substrate-contracts-node) + +```bash +# Build contracts and move artifacts to `contracts/deployments/{contract}/` folders +pnpm run build + +# Start local node with persistence (contracts stay deployed after restart) +# NOTE: When using Brave, shields have to be taken down for the UIs +pnpm run node + +## IMPORTANT: Open a separate terminal window and keep the node running + +# Deploy the contracts on the local node +pnpm run deploy +``` + +Alternatively, you can also deploy contracts manually using [Contracts UI](https://contracts-ui.substrate.io/) (`pnpm contracts-ui`) in the browser. + +### 3. Connect the frontend to the local node + +Open the `frontend/.env.local` file and set the `NEXT_PUBLIC_DEFAULT_CHAIN` variable to `development`. Then restart the frontend and you should be able to interact with the contracts deployed on your local node. + +_Read more about environment variables and all available chain constants in the [Environment Variables](#environment-variables) section below._ + +## Customization 🎨 + +### 1. Project Name + +There are multiple places where you need to insert your project's name and identifier. Most of these occurrences are highlighted with a `/* TODO */` comment in the code. You can easily replace them one by one by installing the [`todo-tree`](https://marketplace.visualstudio.com/items?itemName=gruntfuggly.todo-tree) plugin. + +Additionally, there are the following un-highlighted occurrences: + +- the name of the `inkathon.code-workspace` file +- the `package.json`'s name & metadata in the root directory as well as in the `contracts/` and `frontend/` packages +- the workspace dependency (`@inkathon/contracts`) defined in `frontend/package.json` and imported in `frontend/src/deployments/deployments.ts` + +### 2. Custom Contracts + +To replace the default `Greeter` contract or add a new one, you need to do the following: + +- Add a new contract directory under `contracts/src/` +- Add it as another workspace member to the `contracts/Cargo.toml` file +- Add another deployment script or adjust `contracts/scripts/deploy.ts` +- Adjust the `ContractIds` enum and `getDeployments` function in `frontend/src/deployments/deployments.ts` + +### 3. Custom Scripts + +Adding custom scripts is useful to interact with your contracts or test certain functionality. Therefore, just duplicate & reuse the `contracts/scripts/script.template.ts` file and run it via `pnpm run script `. This command will run the TypeScript file directly via [`tsx`](https://github.com/privatenumber/tsx). + +For general scripts, the same environment variable initialization & configuration applies as described below in the [Deployment](#deployment) section (e.g. to change the target network). + +## The Stack πŸ₯ž + +
+The Stack in Detail + +- Monorepo Workspace with `contracts/` and `frontend/` directories as packages. +- Package Manager: `pnpm` or `yarn@stable` (Read more in the [FAQs](#faqs--troubleshooting) section below) +- Smart Contract Development: Rust, ink!, `cargo-contract`, `substrate-contracts-node` +- Frontend: Next.js (app-dir), React, TypeScript + - Contract Interactions: `polkadot-js`, [`useInkathon`](https://github.com/scio-labs/use-inkathon) React Hooks & Utility Library (alternatively: [`useInk`](https://use.ink/frontend/getting-started)) + - Styling: `shadcn/ui`, `tailwindcss` + - Linting & Formatting: `eslint`, `prettier`, `simple-git-hooks`, `lint-staged` + +Styling, linting, and formatting libraries can be fully dropped or replaced with alternatives. + +
+ +![inkathon Stack Diagram](inkathon-stack-diagram.png) + +## Live Examples 🌐 + +Below you find live examples that use this boilerplate or have a similar setup inspired by it: + +- [inkathon.xyz](https://inkathon.xyz) – Live demo deployment of this boilerplate +- [AZERO.ID](https://azero.id) – Domain Name Service for Aleph Zero and beyond +- Multiple hackathon projects from [ETHWarsaw](https://ethwarsaw-2023.devpost.com/submissions/), [HackOnChain](https://www.hackonchain.xyz/), [ETHDam](https://www.ethdam.com/), and the [Polkadot ink! Hackathon](https://www.encode.club/polkadot-ink-hackathon). + +## Deployment 🚒 + +Spinning up a deployment via Vercel is pretty straightforward as the necessary settings are already configured in `vercel.json`. If you haven't cloned the repository yet, you can also use the **Deploy** button below to create a new repository from this template. + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fhello-world&env=NEXT_PUBLIC_DEFAULT_CHAIN&envDescription=Insert%20%60alephzero-testnet%60%20or%20%60shibuya%60&envLink=https%3A%2F%2Fgithub.com%2Fscio-labs%2Finkathon%23environment-variables&project-name=inkathon&repository-name=inkathon&redirect-url=https%3A%2F%2Fgithub.com%2Fscio-labs%2Finkathon&demo-url=https%3A%2F%2Finkathon.xyz) + +### Environment Variables + +One key element making this boilerplate so flexible is the usage of environment variables to configure the active network in the frontend. This is done by setting the `NEXT_PUBLIC_DEFAULT_CHAIN` variable in the `frontend/.env.local` file, or in the Vercel deployment settings respectively. + +
+All Supported Chain Constants + +| Network Identifier | Name | Type | +| ------------------- | ----------------------- | ------- | +| `development` | ️Local Development Node | Testnet | +| `alephzero-testnet` | Aleph Zero Testnet | Testnet | +| `rococo` | Rococo | Testnet | +| `shibuya` | Shibuya Testnet | Testnet | +| `shiden` | Shiden | Mainnet | +| `alephzero` | Aleph Zero | Mainnet | +| `astar` | Astar | Mainnet | + +Source: https://github.com/scio-labs/use-inkathon/blob/main/src/chains.ts + +> [!NOTE] +> Chains can also be supplied manually by creating a [`SubstrateChain`](https://github.com/scio-labs/use-inkathon/blob/main/src/chains.ts#L4) object. If you think a chain is missing, please open an issue or PR. + +
+ +All environment variables are imported from `process.env` in [`frontend/src/config/environment.ts`](https://github.com/scio-labs/inkathon/blob/main/frontend/src/config/environment.ts) and re-exported from there. For improved type safety, Always only import environment variables from `@/config/environment` and never directly from `process.env`. + +| Environment Variables | [Default Values](https://github.com/scio-labs/inkathon/blob/main/frontend/.env.local.example) | Description | +| ------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `NEXT_PUBLIC_DEFAULT_CHAIN` \*️⃣ | ️`alephzero-testnet` | The network (Substrate-based chain) the frontend should connect to by default and what contract deployment artifacts to import. | +| `NEXT_PUBLIC_PRODUCTION_MODE` | `false` | Optional boolean flag to differentiate production environment (e.g. for SEO or Analytics). | +| `NEXT_PUBLIC_URL` | `http://localhost:3000` | Optional string that defines the base URL of the frontend (will be auto-inferred from Vercel environment variables). | +| `NEXT_PUBLIC_SUPPORTED_CHAINS` | – | Optional array with network identifers (e.g. `["alephzero-testnet", "shibuya"]`) that are supported by the frontend, **if the dApp is supposed to be multi-chain**. | + +\*️⃣ Required + +### Contract Deployment + +In the [Getting Started](#getting-started) section above, we've already deployed the sample `Greeter` contract on a local node. To target a live network, we can use the `CHAIN` environment variable when running the `deploy` script. + +```bash +CHAIN=alephzero-testnet pnpm run deploy +``` + +Further, dynamically loaded environment files with the `.env.{chain}` naming convention can be used to add additional configuration about the deployer account. + +```bash +# .env.alephzero-testnet +ACCOUNT_URI=bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice +``` + +When running the same script again, this deployer account defined there will be used to sign the extrinsic. + +> [!WARNING] +> These files are gitignored by default, but you should still be extra cautious when adding sensitive information to them. + +## VSCode Setup πŸ›  + +### Workspace + +It can be helpful to develop in VSCode by opening the workspace file `inkathon.code-workspace` instead of just the plain directory. This approach offers multiple advantages, like sections in the file explorer, or shortcut actions to open the terminal in the correct directory. + +Consider installin the [`zoma.vscode-auto-open-workspace`](https://marketplace.visualstudio.com/items?itemName=zoma.vscode-auto-open-workspace) extension to automatically open the workspace file when opening the directory. + +### Plugins + +Additionally, the VSCode plugins listed below are recommended as they can be very helpful when working with this boilerplate. + +
+All Recommended Plugins + +| Plugin Name | Description | +| ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | +| [`dbaeumer.vscode-eslint`](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) | Adds ESLint editor support. | +| [`esbenp.prettier-vscode`](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) | Adds Prettier editor support. | +| [`bradlc.vscode-tailwindcss`](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) | Adds tailwindcss editor support. | +| [`rust-lang.rust-analyzer`](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) | Adds Rust language support. | +| [`ink-analyzer.ink-analyzer`](https://marketplace.visualstudio.com/items?itemName=ink-analyzer.ink-analyzer) | Adds ink! language support. | +| [`tamasfe.even-better-toml`](https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml) | Adds `.toml` file support. | +| [`gruntfuggly.todo-tree`](https://marketplace.visualstudio.com/items?itemName=gruntfuggly.todo-tree) | Lists all `TODO` comments in your workspace. | +| [`wayou.vscode-todo-highlight`](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight) | Highlights `TODO` comments in your workspace. | +| [`mikestead.dotenv`](https://marketplace.visualstudio.com/items?itemName=mikestead.dotenv) | Adds syntax highlighting for `.env` files. | + +
+ +## FAQs & Troubleshooting πŸ’¬ + +
+Which package managers are supported? Do I have to use pnpm? + +For monorepo workspaces, [pnpm](https://pnpm.io) is likely the fastest and most reliable choice. When using it though, it's strongly recommended everyone on the team uses it. No installs should be performed nor any other lock files should be committed. + +As an alternative, [yarn](https://yarnpkg.com/) is also supported and can be used for installation. Caveats when using yarn: + +- Only the stable version of yarn (currently v3) is supported, not [yarn classic](https://classic.yarnpkg.com/) (v1). +- `yarn.lock` files should be committed instead of `.pnpm-lock.yaml` files. +- The `pnpm` CLI is still used in many `package.json` scripts, so these would have to be adjusted manually. + +> [!IMPORTANT] +> As [npm](https://www.npmjs.com/) lacks support for the `workspace` import protocol, it's not compatible with ink!athon. + +
+ +
+How to solve `Cannot find module './greeter/development.ts'`? + +Sometimes, Next.js doesn't pick up changes (i.e. file creations) in the `contracts/deployments/{contract}/` folders correctly. E.g., when you just deployed on a local node for the first time and set the frontend's `.env.local` to connect to the `development` network. + +To fix this, you can delete the build cache at `frontend/.next`. This is currently the only solution and will force Next.js to rebuild the project and pick up the new files. + +> [!NOTE] +> To prevent this behavior, the `contracts/package.json` file contains a small `postinstall` script that creates an empty `development.ts` file if none exists. + +
+ +
+How to approach styling? + +Currently it offers styling via the following options out of the box: + +- [shadcn/ui](https://ui.shadcn.com/) - Re-usable components built using [Radix UI](https://radix-ui.com/) and [Tailwind CSS](https://tailwindcss.com/). +- Vanilla [Tailwind CSS](https://tailwindcss.com/) styled styles via `className` and `*.module.(s)css` files. +- Default (S)CSS styles. + +> [!INFO] +> This boilerplate tries to stay as un-opinonated in regards to styling, which means you can use any styling or component library. + +
+ +
+Resources to learn more about Substrate, ink!, and polkadot.js + +- [ink! Documentation](https://use.ink/) +- [polkadot.js Documentation](https://polkadot.js.org/docs/) +- [Polkadot Wiki ink! Tools](https://wiki.polkadot.network/docs/build-open-source) +- [Aleph Zero Documentation](https://docs.alephzero.org/aleph-zero/build/) +- [ink!athon Workshop Recording](https://youtube.com/watch?v=SoNLZfsd0mQ) +- [ink!athon Telegram Group](https://t.me/inkathon) + +
diff --git a/contracts/.env.development.example b/contracts/.env.development.example new file mode 100644 index 0000000..951988b --- /dev/null +++ b/contracts/.env.development.example @@ -0,0 +1 @@ +ACCOUNT_URI=//Alice \ No newline at end of file diff --git a/contracts/.eslintignore b/contracts/.eslintignore new file mode 100644 index 0000000..709c9aa --- /dev/null +++ b/contracts/.eslintignore @@ -0,0 +1,6 @@ +node_modules +deployments +target +src +dist +.node-data \ No newline at end of file diff --git a/contracts/.eslintrc.json b/contracts/.eslintrc.json new file mode 100644 index 0000000..6fcf228 --- /dev/null +++ b/contracts/.eslintrc.json @@ -0,0 +1,16 @@ +{ + "root": true, + "parser": "@typescript-eslint/parser", + "plugins": ["@typescript-eslint"], + "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"], + "rules": { + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/no-non-null-assertion": "warn", + "@typescript-eslint/no-empty-function": "warn", + "no-extra-boolean-cast": "off", + "prefer-const": "warn" + } +} diff --git a/contracts/.gitignore b/contracts/.gitignore new file mode 100755 index 0000000..44d4cf1 --- /dev/null +++ b/contracts/.gitignore @@ -0,0 +1,134 @@ +### Rust ### + +# Ignore build artifacts from the local tests sub-crate. +target/ +debug/ + +# Ignore backup files creates by cargo fmt. +**/*.rs.bk + +# Remove Cargo.lock when creating an executable, leave it for libraries +# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock +Cargo.lock + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +### Editors ### + +# JetBrains +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### JetBrains Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Custom ### + +# misc +.DS_Store +*.pem + +# Substrate Contracts Node Persistence Cache +.node-data + +# Local deployments +deployments/**/development.json +deployments/**/development.ts + +# Environment files +*.env* +!.env*.example diff --git a/contracts/.lintstagedrc.json b/contracts/.lintstagedrc.json new file mode 100644 index 0000000..ffda8b8 --- /dev/null +++ b/contracts/.lintstagedrc.json @@ -0,0 +1,4 @@ +{ + "*.{js,ts}": ["pnpm run lint:fix"], + "*.{json,md,mdx,html,css,yml,yaml}": ["pnpm run lint:format"] +} diff --git a/contracts/.prettierignore b/contracts/.prettierignore new file mode 100644 index 0000000..709c9aa --- /dev/null +++ b/contracts/.prettierignore @@ -0,0 +1,6 @@ +node_modules +deployments +target +src +dist +.node-data \ No newline at end of file diff --git a/contracts/CHANGELOG.md b/contracts/CHANGELOG.md new file mode 100644 index 0000000..be4258c --- /dev/null +++ b/contracts/CHANGELOG.md @@ -0,0 +1,87 @@ +# @inkathon/contracts + +## 0.4.2 + +### Patch Changes + +- [`cf68f5f`](https://github.com/scio-labs/inkathon/commit/cf68f5f96888c69434014ff4f8eccdd3558d20bc) Thanks [@wottpal](https://github.com/wottpal)! - Further simplify contract scripts by moving required explicit types to `use-inkathon`. Also changing the module resolution setting in `tsconfig.json` to import directly from sub-paths like `@scio-labs/use-inkathon/types` which makes the scripts in a context like Next.js app-dir API routes. + +- [`bc7d7ed`](https://github.com/scio-labs/inkathon/commit/bc7d7ed546fc2f17b6adaf96e34645f84ac2a5e0) Thanks [@wottpal](https://github.com/wottpal)! - Move VSCode settings to `settings.json` file but keep `inkathon.code-workspace`. It's now also supported by default to develop with ink!athon without opening the code-workspace file. + +## 0.4.1 + +### Patch Changes + +- [`14e8e11`](https://github.com/scio-labs/inkathon/commit/14e8e11ebc857e81b7cfa97e7c3c7f28d8dbccc3) Thanks [@wottpal](https://github.com/wottpal)! - Add sample code snippets from live workshops (greeter message reversion & make-it-rain script) + +## 0.4.0 + +### Minor Changes + +- [#42](https://github.com/scio-labs/inkathon/pull/42) [`0533391`](https://github.com/scio-labs/inkathon/commit/0533391ac6f9b953ba0cb231af8b3037e80bcbab) Thanks [@ical10](https://github.com/ical10)! - Update project default to Node 20. + +## 0.3.2 + +### Patch Changes + +- [#39](https://github.com/scio-labs/inkathon/pull/39) [`47aed1b`](https://github.com/scio-labs/inkathon/commit/47aed1b722138bd6fca2883337151d3c0b77e4a3) Thanks [@ical10](https://github.com/ical10)! - Deploy contracts & add deployment addresses for Rococo Contracts test-network. + +## 0.3.1 + +### Patch Changes + +- [`e73d9b8`](https://github.com/scio-labs/inkathon/commit/e73d9b86a4299702c59538ac43612b9977d479be) Thanks [@wottpal](https://github.com/wottpal)! - Replace `ts-node` with `tsx` (https://github.com/privatenumber/tsx) for less-verbose TypeScript script execution. + +## 0.3.0 + +### Minor Changes + +- [`cda19ae`](https://github.com/scio-labs/inkathon/commit/cda19aeb4107c076daeb17a455fecfbd7f373044) Thanks [@wottpal](https://github.com/wottpal)! - Vastly reduce boilerplate for JS/TS script initialization of Polkadot.js. You no longer need to read and parse dotenv environment variables in every script. + +## 0.2.1 + +### Patch Changes + +- [`3f4179e`](https://github.com/scio-labs/inkathon/commit/3f4179e9325b155324d23796234d9f853ae03dd9) Thanks [@wottpal](https://github.com/wottpal)! - Add workaround to run ESM-enabled ts-node scripts with Node.js 20. Related: https://github.com/TypeStrong/ts-node/issues/1997 + +## 0.2.0 + +### Minor Changes + +- [`c2cfbe4`](https://github.com/scio-labs/inkathon/commit/c2cfbe428a4e86f7ddb3d25886d4da79238b69be) Thanks [@wottpal](https://github.com/wottpal)! - Ensure & document Windows, Ubuntu, and macOS compatibility. 🌈 + +## 0.1.3 + +### Patch Changes + +- [`4bda28d`](https://github.com/scio-labs/inkathon/commit/4bda28d645abc8d8684d33bac788f04c278d7b4e) Thanks [@wottpal](https://github.com/wottpal)! - Further cross-platform script improvements (i.e. regarding the touch command). + +## 0.1.2 + +### Patch Changes + +- [`2b9bc68`](https://github.com/scio-labs/inkathon/commit/2b9bc689876ea195a1cf2f6af1ca2414bcf04172) Thanks [@wottpal](https://github.com/wottpal)! - Make cp/copy command work cross-platform (i.e. on Windows) for postinstall and build-all scripts. + +## 0.1.0 + +### Minor Changes + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`cf04f67`](https://github.com/scio-labs/inkathon/commit/cf04f671c06276ffc51e33c1e38c181173227d75) Thanks [@wottpal](https://github.com/wottpal)! - Add `contract/scripts/script.template.ts` template script and simplify script initialization in general. + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Move `frontend` and `contracts` packages to the root level + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Auto-detect available contracts in build & test shell scripts + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`7a41afe`](https://github.com/scio-labs/inkathon/commit/7a41afe1e7c2f45b6d3972760c173a4a2197c643) Thanks [@wottpal](https://github.com/wottpal)! - Add contributor guidelines at `CONTRIBUTING.md`. + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Add pnpm/npm shorthand script for JS/TS script execution (i.e. `pnpm run script deploy`) + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`3598618`](https://github.com/scio-labs/inkathon/commit/3598618f87d788ec51964167557210ed8b659797) Thanks [@wottpal](https://github.com/wottpal)! - Major README.md overhaul & improvements + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Switch from `husky` to `simple-git-hooks` pre-commit hooks + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`07d8381`](https://github.com/scio-labs/inkathon/commit/07d83819c48f4aaa129ccc3d27929767b916c93d) Thanks [@wottpal](https://github.com/wottpal)! - Add compatability for using yarn (stable only, not classic v1) as the package manager. Note: npm is still not compatible as it lacks support for the workspace import protocol. + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Move ink! contract files under `contracts/src/` + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Setup changeset integration for version, release, and changelog management. diff --git a/contracts/Cargo.toml b/contracts/Cargo.toml new file mode 100644 index 0000000..3596028 --- /dev/null +++ b/contracts/Cargo.toml @@ -0,0 +1,4 @@ +[workspace] + +resolver = "1" +members = ["src/greeter"] diff --git a/contracts/build-all.sh b/contracts/build-all.sh new file mode 100755 index 0000000..2d97e4d --- /dev/null +++ b/contracts/build-all.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -eu + +# ENVIRONMENT VARIABLES +CONTRACTS_DIR="${CONTRACTS_DIR:=./src}" # Base contract directory +DIR="${DIR:=./deployments}" # Output directory for build files + +# Copy command helper (cross-platform) +CP_CMD=$(command -v cp &> /dev/null && echo "cp" || echo "copy") + +# Determine all contracts under `$CONTRACTS_DIR` +contracts=($(find $CONTRACTS_DIR -maxdepth 1 -type d -exec test -f {}/Cargo.toml \; -print | xargs -n 1 basename)) + +# Build all contracts +for i in "${contracts[@]}" +do + echo -e "\nBuilding '$CONTRACTS_DIR/$i/Cargo.toml'…" + cargo contract build --release --quiet --manifest-path $CONTRACTS_DIR/$i/Cargo.toml + + echo "Copying build files to '$DIR/$i/'…" + mkdir -p $DIR/$i + $CP_CMD ./target/ink/$i/$i.contract $DIR/$i/ + $CP_CMD ./target/ink/$i/$i.wasm $DIR/$i/ + $CP_CMD ./target/ink/$i/$i.json $DIR/$i/ +done \ No newline at end of file diff --git a/contracts/deployments/greeter/alephzero-testnet.ts b/contracts/deployments/greeter/alephzero-testnet.ts new file mode 100644 index 0000000..134525b --- /dev/null +++ b/contracts/deployments/greeter/alephzero-testnet.ts @@ -0,0 +1,2 @@ +export const address = '5CrtpVyLB8iaRPJyB39DvfGgHP1BLGpEfmb9XF1qzN5CFQbX' +export const blockNumber = 41737105 diff --git a/contracts/deployments/greeter/alephzero.ts b/contracts/deployments/greeter/alephzero.ts new file mode 100644 index 0000000..e7cf6f6 --- /dev/null +++ b/contracts/deployments/greeter/alephzero.ts @@ -0,0 +1,2 @@ +export const address = '5DhCVg3QmsPXPpYBGGPerVfnopMUSr49L3eMKmetmJkLfpot' +export const blockNumber = 58304564 diff --git a/contracts/deployments/greeter/greeter.contract b/contracts/deployments/greeter/greeter.contract new file mode 100644 index 0000000..5d00d06 --- /dev/null +++ b/contracts/deployments/greeter/greeter.contract @@ -0,0 +1 @@ +{"source":{"hash":"0x586a59fc04eeb2b7d0e89b7d7ce98689f8e520a27a3522ca3b1a112f0129af9d","language":"ink! 4.3.0","compiler":"rustc 1.75.0","wasm":"0x0061736d0100000001290760027f7f0060037f7f7f0060000060047f7f7f7f017f60037f7f7f017f60047f7f7f7f006000017f02b10109057365616c310b6765745f73746f726167650003057365616c301176616c75655f7472616e736665727265640000057365616c3005696e7075740000057365616c300663616c6c65720000057365616c300f686173685f626c616b65325f3235360001057365616c300d6465706f7369745f6576656e740005057365616c320b7365745f73746f726167650003057365616c300b7365616c5f72657475726e000103656e76066d656d6f7279020102100313120404000106010100010000020000000002020608017f01418080040b0711020463616c6c0018066465706c6f7900190ad31c122b01017f037f2002200346047f200005200020036a200120036a2d00003a0000200341016a21030c010b0b0b8e0101017f20002d00042103200041003a0004027f0240200304402001200041056a2d00003a00004101200028020022002802042203200241016b2202490d021a200141016a20002802002201200210081a0c010b41012000280200220028020422032002490d011a200120002802002201200210081a0b2000200320026b3602042000200120026a36020041000b0b2601017f230041106b220224002002200036020c20012002410c6a4104100b200241106a24000b4801027f024002402000280208220320026a22042003490d00200420002802044b0d00200420036b2002470d01200028020020036a2001200210081a200020043602080f0b000b000b4d02017f027e230041206b2200240020004200370308200042003703002000411036021c20002000411c6a10012000290308210120002903002102200041206a2400410541042001200284501b0b4801027f230041106b22032400200341086a20024100100e200328020c210420032802082001200210082101200020023602082000200436020420002001360200200341106a24000bab0101017f024002402001450440410121020c010b20014100480d01200245044041a482052d00001a0b419c8204280200220220016a22032002490d0141a082042802002003490440200141ffff036a22034110764000220241ffff034b0d022002411074220220034180807c716a22032002490d0241a082042003360200200120026a22032002490d020b419c820420033602002002450d010b20002001360204200020023602000f0b000b7401017f230041106b2202240002402000413f4d04402001200041027410170c010b200041ffff004d0440200220004102744101723b010e20012002410e6a4102100b0c010b200041ffffffff034d044020004102744102722001100a0c010b20014103101720002001100a0b200241106a24000b100020012002100f200220002001100b0b0a00200120004120100b0bca0702087f017e230041206b220324000240024020012802042204450d00200128020022052d000021022001200441016b3602042001200541016a36020002400240024002400240200241037141016b0e03020301000b200241027621020c030b2004410549200241034b720d03200528000121022001200441056b3602042001200541056a36020020024180808080044f0d020c030b200341196a20023a0000200341013a001820032001360214200341003b011c200341146a2003411c6a410210090d0220032f011c220241ff014d0d02200241027621020c010b200341196a20023a0000200341013a0018200320013602142003410036021c200341146a2003411c6a410410090d01200328021c220241808004490d01200241027621020b20012802042002490d00200341086a20024101100e200128020422052002490d00200335020c210a2003280208200128020022062002100821042001200520026b3602042001200220066a36020002402002450d00200241076b22014100200120024d1b2108200441036a417c7120046b21094100210103400240024002400240024002400240024002400240200120046a2d00002205411874411875220741004804402005419a80046a2d000041026b0e03030102080b200920016b410371450440200120084f0d090340200120046a220541046a280200200528020072418081828478710d0a2008200141086a22014b0d000b0c090b200141016a21010c090b200141016a220620024f0d06200420066a2c000021060240200541e001470440200541ed01460d012007411f6a41ff0171410c490d042007417e71416e470d0820064140480d050c080b200641607141a07f460d040c070b2006419f7f4a0d060c030b200141016a220620024f0d05200420066a2c000021060240024002400240200541f0016b0e050100000002000b2007410f6a41ff017141024b0d0820064140480d020c080b200641f0006a41ff01714130490d010c070b2006418f7f4a0d060b200141026a220520024f0d05200420056a2c000041bf7f4a0d05200141036a220120024f0d05200120046a2c000041bf7f4a0d050c040b200141016a22012002490d020c040b200641404e0d030b200141026a220120024f0d02200120046a2c000041bf7f4c0d010c020b200120046a2c000041bf7f4a0d010b200141016a21010c020b200041003602000c050b200120024f0d000340200120046a2c00004100480d012002200141016a2201470d000b0c020b20012002490d000b0b20002002ad422086200a84370204200020043602000c010b200041003602000b200341206a24000b120041a4820441003b0100410041021016000b3c01027f027f200145044041a48204210141010c010b4101210241a4820441013a000041a58204210141020b2103200120023a0000200020031016000b8f0101047f230041106b22022400200242808001370208200241a482043602044100200241046a100a024020022802082205200228020c2203490d00200228020421042002410036020c2002200520036b3602082002200320046a36020420002001200241046a1010200228020c220020022802084b0d00200420032002280204200010061a200241106a24000f0b000b0d00200041a4820420011007000b2d01017f2000280208220220002802044904402000200241016a360208200028020020026a20013a00000f0b000be10a020e7f017e230041306b2201240002400240100c41ff01714105470d0020014180800136022041a48204200141206a100220012802202200418180014f0d00024020004104490d00200141a8820436020c2001200041046b36021041a782042d0000210041a682042d0000210241a582042d00002104024041a482042d00002203411f47044020034105472004412c4772200241da0147200041084772720d02410021000c010b200441e70147200241c2004772200041ef0047720d01200141206a2001410c6a101220012802202200450d01200120012800253602182001200141286a28000036001b20012d002421050b2001200128001b36000720012001280218360204200142808001370224200141a482043602204100200141206a100a2001280224220320012802282202490d01200128022021042001200320026b220336022020042002200220046a2202200141206a100020032001280220220449720d012001200436021c20012002360218200141206a200141186a101220012802202202450d0120012001290224220e3702102001200236020c20000d02200141206a2002200e422088a7100d2001280220210220012802282101230041106b22002400200041808001360208200041a482043602040240200245044041a482044181023b0100410221000c010b2000410136020c41a4820441003a000020022001200041046a1010200028020c220041818001490d00000b410020001016000b410141011014000b000b200141286a2001280007360000200120053a0024200120003602202001200128020436002523004180016b22002400200141206a2202280204210320022802002105200041086a200228020822044100100e200028020c2106200028020820052004100821072001410c6a22022004360208200220063602042002200736020020004180800136021041a48204200041106a100341a482042d00002102200041356a41bc82042900003700002000412e6a41b58204290000370100200041266a41ad8204290000370100200041a5820429000037011e200020023a001d200041013a001c200020043602182000200336021420002005360210200042808001370264200041a482043602604101200041e0006a100f0240024020002802682203418180014f0d002000410036026820004180800120036b22073602642000200341a482046a2208360260418080044100200041e0006a220210102002418080044110100b2000280268220220002802644b0d0020002802602106200041d8006a22094200370300200041d0006a4200370300200041c8006a220a4200370300200042003703400240200241214f0440200041f8006a220b4200370300200041f0006a220c4200370300200041e8006a220d42003703002000420037036020062002200041e0006a10042009200b290300370300200041d0006a200c290300370300200a200d290300370300200020002903603703400c010b200041406b2006200210081a0b200041f8006a200041d8006a290300370300200041f0006a200041d0006a290300370300200041e8006a200041c8006a29030037030020002000290340370360200041003602482000200736024420002008360240200041e0006a200041406b10112003200320002802486a22024b2002418180014f720d0020004180800120026b3602642000200241a482046a2203360260200241808001460d00200341003a0000200241ffff004f0d00200341013a0001200041023602682000411d6a200041e0006a2203101120052004200310102000280268220420002802644b0d0041a48204200220002802602004100520004180016a24000c010b000b200128020c20012802141015410041001014000b830201057f230041206b2200240002400240100c41ff01714105470d0020004180800136021441a48204200041146a100220002802142201418180014f0d0020014104490d01200041a8820436020c2000200141046b36021041a782042d0000210141a682042d0000210241a582042d00002103024041a482042d0000220441ed014704402004419b0147200341ae0147722002419d0147720d03200141de00460d010c030b200341cb00472002419d0147722001411b47720d02200041146a41908004410a100d2000280214200028021c10151013000b200041146a2000410c6a101220002802142201450d012001200028021c10151013000b000b410141011014000b0bdd010200418080040b9a01477265657465723a3a4772656574656448656c6c6f20696e6b2101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010041dc81040b33020202020202020202020202020202020202020202020202020202020202030303030303030303030303030303030404040404","build_info":{"build_mode":"Release","cargo_contract_version":"3.2.0","rust_toolchain":"stable-aarch64-apple-darwin","wasm_opt_settings":{"keep_debug_symbols":false,"optimization_passes":"Z"}}},"contract":{"name":"greeter","version":"0.0.1","authors":["Scio Labs "]},"spec":{"constructors":[{"args":[{"label":"init_value","type":{"displayName":["String"],"type":0}}],"default":false,"docs":["Creates a new greeter contract initialized with the given value."],"label":"new","payable":false,"returnType":{"displayName":["ink_primitives","ConstructorResult"],"type":1},"selector":"0x9bae9d5e"},{"args":[],"default":false,"docs":["Creates a new greeter contract initialized to 'Hello ink!'."],"label":"default","payable":false,"returnType":{"displayName":["ink_primitives","ConstructorResult"],"type":1},"selector":"0xed4b9d1b"}],"docs":[],"environment":{"accountId":{"displayName":["AccountId"],"type":6},"balance":{"displayName":["Balance"],"type":9},"blockNumber":{"displayName":["BlockNumber"],"type":12},"chainExtension":{"displayName":["ChainExtension"],"type":13},"hash":{"displayName":["Hash"],"type":10},"maxEventTopics":4,"timestamp":{"displayName":["Timestamp"],"type":11}},"events":[{"args":[{"docs":[],"indexed":false,"label":"from","type":{"displayName":["Option"],"type":5}},{"docs":[],"indexed":false,"label":"message","type":{"displayName":["String"],"type":0}}],"docs":[],"label":"Greeted"}],"lang_error":{"displayName":["ink","LangError"],"type":3},"messages":[{"args":[],"default":false,"docs":[" Returns the current value of `message`."],"label":"greet","mutates":false,"payable":false,"returnType":{"displayName":["ink","MessageResult"],"type":4},"selector":"0x052cda08"},{"args":[{"label":"new_value","type":{"displayName":["String"],"type":0}}],"default":false,"docs":[" Sets `message` to the given value."],"label":"set_message","mutates":true,"payable":false,"returnType":{"displayName":["ink","MessageResult"],"type":1},"selector":"0x1fe7426f"}]},"storage":{"root":{"layout":{"struct":{"fields":[{"layout":{"leaf":{"key":"0x00000000","ty":0}},"name":"message"}],"name":"Greeter"}},"root_key":"0x00000000"}},"types":[{"id":0,"type":{"def":{"primitive":"str"}}},{"id":1,"type":{"def":{"variant":{"variants":[{"fields":[{"type":2}],"index":0,"name":"Ok"},{"fields":[{"type":3}],"index":1,"name":"Err"}]}},"params":[{"name":"T","type":2},{"name":"E","type":3}],"path":["Result"]}},{"id":2,"type":{"def":{"tuple":[]}}},{"id":3,"type":{"def":{"variant":{"variants":[{"index":1,"name":"CouldNotReadInput"}]}},"path":["ink_primitives","LangError"]}},{"id":4,"type":{"def":{"variant":{"variants":[{"fields":[{"type":0}],"index":0,"name":"Ok"},{"fields":[{"type":3}],"index":1,"name":"Err"}]}},"params":[{"name":"T","type":0},{"name":"E","type":3}],"path":["Result"]}},{"id":5,"type":{"def":{"variant":{"variants":[{"index":0,"name":"None"},{"fields":[{"type":6}],"index":1,"name":"Some"}]}},"params":[{"name":"T","type":6}],"path":["Option"]}},{"id":6,"type":{"def":{"composite":{"fields":[{"type":7,"typeName":"[u8; 32]"}]}},"path":["ink_primitives","types","AccountId"]}},{"id":7,"type":{"def":{"array":{"len":32,"type":8}}}},{"id":8,"type":{"def":{"primitive":"u8"}}},{"id":9,"type":{"def":{"primitive":"u128"}}},{"id":10,"type":{"def":{"composite":{"fields":[{"type":7,"typeName":"[u8; 32]"}]}},"path":["ink_primitives","types","Hash"]}},{"id":11,"type":{"def":{"primitive":"u64"}}},{"id":12,"type":{"def":{"primitive":"u32"}}},{"id":13,"type":{"def":{"variant":{}},"path":["ink_env","types","NoChainExtension"]}}],"version":"4"} \ No newline at end of file diff --git a/contracts/deployments/greeter/greeter.json b/contracts/deployments/greeter/greeter.json new file mode 100644 index 0000000..b123d6a --- /dev/null +++ b/contracts/deployments/greeter/greeter.json @@ -0,0 +1,468 @@ +{ + "source": { + "hash": "0x586a59fc04eeb2b7d0e89b7d7ce98689f8e520a27a3522ca3b1a112f0129af9d", + "language": "ink! 4.3.0", + "compiler": "rustc 1.75.0", + "build_info": { + "build_mode": "Release", + "cargo_contract_version": "3.2.0", + "rust_toolchain": "stable-aarch64-apple-darwin", + "wasm_opt_settings": { + "keep_debug_symbols": false, + "optimization_passes": "Z" + } + } + }, + "contract": { + "name": "greeter", + "version": "0.0.1", + "authors": [ + "Scio Labs " + ] + }, + "spec": { + "constructors": [ + { + "args": [ + { + "label": "init_value", + "type": { + "displayName": [ + "String" + ], + "type": 0 + } + } + ], + "default": false, + "docs": [ + "Creates a new greeter contract initialized with the given value." + ], + "label": "new", + "payable": false, + "returnType": { + "displayName": [ + "ink_primitives", + "ConstructorResult" + ], + "type": 1 + }, + "selector": "0x9bae9d5e" + }, + { + "args": [], + "default": false, + "docs": [ + "Creates a new greeter contract initialized to 'Hello ink!'." + ], + "label": "default", + "payable": false, + "returnType": { + "displayName": [ + "ink_primitives", + "ConstructorResult" + ], + "type": 1 + }, + "selector": "0xed4b9d1b" + } + ], + "docs": [], + "environment": { + "accountId": { + "displayName": [ + "AccountId" + ], + "type": 6 + }, + "balance": { + "displayName": [ + "Balance" + ], + "type": 9 + }, + "blockNumber": { + "displayName": [ + "BlockNumber" + ], + "type": 12 + }, + "chainExtension": { + "displayName": [ + "ChainExtension" + ], + "type": 13 + }, + "hash": { + "displayName": [ + "Hash" + ], + "type": 10 + }, + "maxEventTopics": 4, + "timestamp": { + "displayName": [ + "Timestamp" + ], + "type": 11 + } + }, + "events": [ + { + "args": [ + { + "docs": [], + "indexed": false, + "label": "from", + "type": { + "displayName": [ + "Option" + ], + "type": 5 + } + }, + { + "docs": [], + "indexed": false, + "label": "message", + "type": { + "displayName": [ + "String" + ], + "type": 0 + } + } + ], + "docs": [], + "label": "Greeted" + } + ], + "lang_error": { + "displayName": [ + "ink", + "LangError" + ], + "type": 3 + }, + "messages": [ + { + "args": [], + "default": false, + "docs": [ + " Returns the current value of `message`." + ], + "label": "greet", + "mutates": false, + "payable": false, + "returnType": { + "displayName": [ + "ink", + "MessageResult" + ], + "type": 4 + }, + "selector": "0x052cda08" + }, + { + "args": [ + { + "label": "new_value", + "type": { + "displayName": [ + "String" + ], + "type": 0 + } + } + ], + "default": false, + "docs": [ + " Sets `message` to the given value." + ], + "label": "set_message", + "mutates": true, + "payable": false, + "returnType": { + "displayName": [ + "ink", + "MessageResult" + ], + "type": 1 + }, + "selector": "0x1fe7426f" + } + ] + }, + "storage": { + "root": { + "layout": { + "struct": { + "fields": [ + { + "layout": { + "leaf": { + "key": "0x00000000", + "ty": 0 + } + }, + "name": "message" + } + ], + "name": "Greeter" + } + }, + "root_key": "0x00000000" + } + }, + "types": [ + { + "id": 0, + "type": { + "def": { + "primitive": "str" + } + } + }, + { + "id": 1, + "type": { + "def": { + "variant": { + "variants": [ + { + "fields": [ + { + "type": 2 + } + ], + "index": 0, + "name": "Ok" + }, + { + "fields": [ + { + "type": 3 + } + ], + "index": 1, + "name": "Err" + } + ] + } + }, + "params": [ + { + "name": "T", + "type": 2 + }, + { + "name": "E", + "type": 3 + } + ], + "path": [ + "Result" + ] + } + }, + { + "id": 2, + "type": { + "def": { + "tuple": [] + } + } + }, + { + "id": 3, + "type": { + "def": { + "variant": { + "variants": [ + { + "index": 1, + "name": "CouldNotReadInput" + } + ] + } + }, + "path": [ + "ink_primitives", + "LangError" + ] + } + }, + { + "id": 4, + "type": { + "def": { + "variant": { + "variants": [ + { + "fields": [ + { + "type": 0 + } + ], + "index": 0, + "name": "Ok" + }, + { + "fields": [ + { + "type": 3 + } + ], + "index": 1, + "name": "Err" + } + ] + } + }, + "params": [ + { + "name": "T", + "type": 0 + }, + { + "name": "E", + "type": 3 + } + ], + "path": [ + "Result" + ] + } + }, + { + "id": 5, + "type": { + "def": { + "variant": { + "variants": [ + { + "index": 0, + "name": "None" + }, + { + "fields": [ + { + "type": 6 + } + ], + "index": 1, + "name": "Some" + } + ] + } + }, + "params": [ + { + "name": "T", + "type": 6 + } + ], + "path": [ + "Option" + ] + } + }, + { + "id": 6, + "type": { + "def": { + "composite": { + "fields": [ + { + "type": 7, + "typeName": "[u8; 32]" + } + ] + } + }, + "path": [ + "ink_primitives", + "types", + "AccountId" + ] + } + }, + { + "id": 7, + "type": { + "def": { + "array": { + "len": 32, + "type": 8 + } + } + } + }, + { + "id": 8, + "type": { + "def": { + "primitive": "u8" + } + } + }, + { + "id": 9, + "type": { + "def": { + "primitive": "u128" + } + } + }, + { + "id": 10, + "type": { + "def": { + "composite": { + "fields": [ + { + "type": 7, + "typeName": "[u8; 32]" + } + ] + } + }, + "path": [ + "ink_primitives", + "types", + "Hash" + ] + } + }, + { + "id": 11, + "type": { + "def": { + "primitive": "u64" + } + } + }, + { + "id": 12, + "type": { + "def": { + "primitive": "u32" + } + } + }, + { + "id": 13, + "type": { + "def": { + "variant": {} + }, + "path": [ + "ink_env", + "types", + "NoChainExtension" + ] + } + } + ], + "version": "4" +} \ No newline at end of file diff --git a/contracts/deployments/greeter/greeter.wasm b/contracts/deployments/greeter/greeter.wasm new file mode 100644 index 0000000..950fc49 Binary files /dev/null and b/contracts/deployments/greeter/greeter.wasm differ diff --git a/contracts/deployments/greeter/rococo.ts b/contracts/deployments/greeter/rococo.ts new file mode 100644 index 0000000..5cd358c --- /dev/null +++ b/contracts/deployments/greeter/rococo.ts @@ -0,0 +1,2 @@ +export const address = '5HT9eGQSd4en8ey5fmehiq4kjkubSh4MKcF3n8b4wZXggibV' +export const blockNumber = 3661917 diff --git a/contracts/deployments/greeter/shibuya.ts b/contracts/deployments/greeter/shibuya.ts new file mode 100644 index 0000000..173c26c --- /dev/null +++ b/contracts/deployments/greeter/shibuya.ts @@ -0,0 +1,2 @@ +export const address = 'Wnng7DETEUr9Vq1Sj1FTpCHgQmBmtWPhA4fQWf3QzafNk1Y' +export const blockNumber = 4663436 diff --git a/contracts/package.json b/contracts/package.json new file mode 100644 index 0000000..f587ccb --- /dev/null +++ b/contracts/package.json @@ -0,0 +1,40 @@ +{ + "name": "@inkathon/contracts", + "type": "module", + "private": true, + "version": "0.4.2", + "scripts": { + "postinstall": "bash postinstall.sh", + "test": "bash test-all.sh", + "build": "bash build-all.sh", + "node": "substrate-contracts-node --dev --base-path ./.node-data", + "script": "f() { tsx ./scripts/$1; }; f \"$@\"", + "deploy": "pnpm run script deploy", + "contracts-ui": "open https://contracts-ui.substrate.io/?rpc=ws://127.0.0.1:9944", + "explorer-ui": "open https://polkadot.js.org/apps/#/explorer?rpc=ws://127.0.0.1:9944", + "type-check": "tsc --pretty --noEmit", + "sync-types": "typesync", + "lint": "prettier . --check && eslint .", + "lint:fix": "prettier . --write && eslint . --fix", + "lint:format": "prettier . --write" + }, + "devDependencies": { + "@polkadot/api": "^10.11.2", + "@polkadot/api-contract": "^10.11.2", + "@polkadot/keyring": "^12.6.2", + "@polkadot/types": "^10.11.2", + "@polkadot/util": "^12.6.2", + "@polkadot/util-crypto": "^12.6.2", + "@scio-labs/use-inkathon": "^0.6.3", + "@types/eslint": "^8.44.9", + "@types/eslint-config-prettier": "^6.11.3", + "@types/node": "^20.10.5", + "@typescript-eslint/eslint-plugin": "^6.15.0", + "@typescript-eslint/parser": "^6.15.0", + "dotenv": "^16.3.1", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "tsx": "^4.6.2", + "typescript": "^5.3.3" + } +} diff --git a/contracts/postinstall.sh b/contracts/postinstall.sh new file mode 100755 index 0000000..753d719 --- /dev/null +++ b/contracts/postinstall.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -eu + +# The script creates an empty 'development.ts' file if it doesn't exist yet. +# This is kind of a hack to prevent a nasty Next.js error when running the frontend +# for the first time after deploying to a local node which forces to clear `frontend/.next`. + +if [[ ! -e deployments/greeter/development.ts ]]; then + echo "Creating empty 'development.ts'…" + if command -v touch &> /dev/null; then + touch deployments/greeter/development.ts + else + copy /b deployments/greeter/development.ts +,, + fi +else + echo "Great, 'development.ts' already exists! Skipping…" +fi diff --git a/contracts/rust-toolchain b/contracts/rust-toolchain new file mode 100644 index 0000000..870bbe4 --- /dev/null +++ b/contracts/rust-toolchain @@ -0,0 +1 @@ +stable \ No newline at end of file diff --git a/contracts/scripts/deploy.ts b/contracts/scripts/deploy.ts new file mode 100644 index 0000000..d503dae --- /dev/null +++ b/contracts/scripts/deploy.ts @@ -0,0 +1,36 @@ +import { getDeploymentData } from '@/utils/getDeploymentData' +import { initPolkadotJs } from '@/utils/initPolkadotJs' +import { writeContractAddresses } from '@/utils/writeContractAddresses' +import { deployContract } from '@scio-labs/use-inkathon/helpers' + +/** + * Script that deploys the greeter contract and writes its address to a file. + * + * Parameters: + * - `DIR`: Directory to read contract build artifacts & write addresses to (optional, defaults to `./deployments`) + * - `CHAIN`: Chain ID (optional, defaults to `development`) + * + * Example usage: + * - `pnpm run deploy` + * - `CHAIN=alephzero-testnet pnpm run deploy` + */ +const main = async () => { + const initParams = await initPolkadotJs() + const { api, chain, account } = initParams + + // Deploy greeter contract + const { abi, wasm } = await getDeploymentData('greeter') + const greeter = await deployContract(api, account, abi, wasm, 'default', []) + + // Write contract addresses to `{contract}/{network}.ts` file(s) + await writeContractAddresses(chain.network, { + greeter, + }) +} + +main() + .catch((error) => { + console.error(error) + process.exit(1) + }) + .finally(() => process.exit(0)) diff --git a/contracts/scripts/script.template.ts b/contracts/scripts/script.template.ts new file mode 100644 index 0000000..69b73b6 --- /dev/null +++ b/contracts/scripts/script.template.ts @@ -0,0 +1,50 @@ +import { getDeploymentData } from '@/utils/getDeploymentData' +import { initPolkadotJs } from '@/utils/initPolkadotJs' +import { ContractPromise } from '@polkadot/api-contract' +import { + contractQuery, + contractTx, + decodeOutput, + deployContract, +} from '@scio-labs/use-inkathon/helpers' + +/** + * Example script that updates & reads a message from a greeter contract. + * Can be used as a template for other scripts. + * + * Parameters: + * - `DIR`: Directory to read contract build artifacts (optional, defaults to `./deployments`) + * - `CHAIN`: Chain ID (optional, defaults to `development`) + * + * Example usage: + * - `pnpm run script ` + * - `CHAIN=alephzero-testnet pnpm run script ` + */ +const main = async () => { + const { api, account } = await initPolkadotJs() + + // Deploy greeter contract + const { abi, wasm } = await getDeploymentData('greeter') + const { address } = await deployContract(api, account, abi, wasm, 'default', []) + const contract = new ContractPromise(api, abi, address) + + // Update message + try { + await contractTx(api, account, contract, 'set_message', {}, ['Hello, script!']) + console.log('\nSuccessfully updated greeting') + } catch (error) { + console.error('Error while updating greeting', error) + } + + // Read message + const result = await contractQuery(api, '', contract, 'greet') + const { decodedOutput } = decodeOutput(result, contract, 'greet') + console.log('\nQueried greeting:', decodedOutput) +} + +main() + .catch((error) => { + console.error(error) + process.exit(1) + }) + .finally(() => process.exit(0)) diff --git a/contracts/scripts/utils/getDeploymentData.ts b/contracts/scripts/utils/getDeploymentData.ts new file mode 100644 index 0000000..3a1e7c1 --- /dev/null +++ b/contracts/scripts/utils/getDeploymentData.ts @@ -0,0 +1,26 @@ +import { readFile } from 'fs/promises' +import path from 'path' + +/** + * Reads the contract deployment files (wasm & abi). + * NOTE: Base directory can be configured via the `DIR` environment variable + */ +export const getDeploymentData = async (contractName: string) => { + const baseDir = process.env.DIR || './deployments' + const contractPath = path.join(path.resolve(), baseDir, contractName) + + let abi, wasm + try { + abi = JSON.parse(await readFile(path.join(contractPath, `${contractName}.json`), 'utf-8')) + wasm = await readFile(path.join(contractPath, `${contractName}.wasm`)) + } catch (e) { + console.error(e) + throw new Error("Couldn't find contract deployment files. Did you build it via `pnpm build`?") + } + + return { + contractPath, + abi, + wasm, + } +} diff --git a/contracts/scripts/utils/initPolkadotJs.ts b/contracts/scripts/utils/initPolkadotJs.ts new file mode 100644 index 0000000..ef2efd6 --- /dev/null +++ b/contracts/scripts/utils/initPolkadotJs.ts @@ -0,0 +1,50 @@ +import { ApiPromise, Keyring } from '@polkadot/api' +import { IKeyringPair } from '@polkadot/types/types/interfaces' +import { BN } from '@polkadot/util' +import { getSubstrateChain } from '@scio-labs/use-inkathon/chains' +import { getBalance, initPolkadotJs as initApi } from '@scio-labs/use-inkathon/helpers' +import { SubstrateChain } from '@scio-labs/use-inkathon/types' +import * as dotenv from 'dotenv' + +// Dynamically load environment from `.env.{chainId}` +const chainId = process.env.CHAIN || 'development' +dotenv.config({ path: `.env.${chainId}` }) + +/** + * Initialize Polkadot.js API with given RPC & account from given URI. + */ +export type InitParams = { + chain: SubstrateChain + api: ApiPromise + keyring: Keyring + account: IKeyringPair + decimals: number + prefix: number + toBNWithDecimals: (_: number | string) => BN +} +export const initPolkadotJs = async (): Promise => { + const accountUti = process.env.ACCOUNT_URI || '//Alice' + const chain = getSubstrateChain(chainId) + if (!chain) throw new Error(`Chain '${chainId}' not found`) + + // Initialize api + const { api } = await initApi(chain, { noInitWarn: true }) + + // Print chain info + const network = (await api.rpc.system.chain())?.toString() || '' + const version = (await api.rpc.system.version())?.toString() || '' + console.log(`Initialized API on ${network} (${version})`) + + // Get decimals & prefix + const decimals = api.registry.chainDecimals?.[0] || 12 + const prefix = api.registry.chainSS58 || 42 + const toBNWithDecimals = (n: number | string) => new BN(n).mul(new BN(10).pow(new BN(decimals))) + + // Initialize account & set signer + const keyring = new Keyring({ type: 'sr25519' }) + const account = keyring.addFromUri(accountUti) + const balance = await getBalance(api, account.address) + console.log(`Initialized Account: ${account.address} (${balance.balanceFormatted})\n`) + + return { api, chain, keyring, account, decimals, prefix, toBNWithDecimals } +} diff --git a/contracts/scripts/utils/writeContractAddresses.ts b/contracts/scripts/utils/writeContractAddresses.ts new file mode 100644 index 0000000..d3d1b1a --- /dev/null +++ b/contracts/scripts/utils/writeContractAddresses.ts @@ -0,0 +1,42 @@ +import { DeployedContract } from '@scio-labs/use-inkathon/types' +import { writeFile } from 'fs/promises' +import path from 'path' + +/** + * Writes each given contract address & blockNumber to a `{baseDir}/{contract}/{network}.ts` file. + * NOTE: Base directory can be configured via the `DIR` environment variable + */ +export const writeContractAddresses = async ( + networkId: string, + contractDeployments: Record, + metadata?: { [key: string]: string | number }, +) => { + const baseDir = process.env.DIR || './deployments' + + console.log() + for (const [contractName, deployment] of Object.entries(contractDeployments)) { + const relativePath = path.join(baseDir, contractName, `${networkId}.ts`) + const absolutePath = path.join(path.resolve(), relativePath) + + let fileContents = '' + + if (deployment?.address) { + fileContents += `export const address = '${deployment.address}'\n` + } + + if (deployment?.blockNumber) { + fileContents += `export const blockNumber = ${deployment.blockNumber}\n` + } + + // Iterate over metadata keys and write them to the file + if (metadata) { + for (const [key, value] of Object.entries(metadata)) { + const valueFormatted = typeof value === 'string' ? `'${value}'` : value + fileContents += `export const ${key} = ${valueFormatted}\n` + } + } + + await writeFile(absolutePath, fileContents) + console.log(`Exported deployment info to file: ${relativePath}`) + } +} diff --git a/contracts/src/greeter/Cargo.toml b/contracts/src/greeter/Cargo.toml new file mode 100755 index 0000000..b5fe189 --- /dev/null +++ b/contracts/src/greeter/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "greeter" +version = "0.0.1" +authors = ["Scio Labs "] +edition = "2021" + +[dependencies] +ink = { version = "4.3.0", default-features = false } + +scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } +scale-info = { version = "2", default-features = false, features = ["derive"], optional = true } + +[lib] +path = "lib.rs" + +[features] +default = ["std"] +std = ["ink/std", "scale/std", "scale-info/std"] +ink-as-dependency = [] diff --git a/contracts/src/greeter/lib.rs b/contracts/src/greeter/lib.rs new file mode 100755 index 0000000..3ebc2a4 --- /dev/null +++ b/contracts/src/greeter/lib.rs @@ -0,0 +1,81 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +#[ink::contract] +mod greeter { + use ink::prelude::string::String; + + #[ink(event)] + pub struct Greeted { + from: Option, + message: String, + } + + #[ink(storage)] + pub struct Greeter { + message: String, + } + + impl Greeter { + /// Creates a new greeter contract initialized with the given value. + #[ink(constructor)] + pub fn new(init_value: String) -> Self { + Self { + message: init_value, + } + } + + /// Creates a new greeter contract initialized to 'Hello ink!'. + #[ink(constructor)] + pub fn default() -> Self { + let default_message = String::from("Hello ink!"); + Self::new(default_message) + } + + /// Returns the current value of `message`. + #[ink(message)] + pub fn greet(&self) -> String { + self.message.clone() + } + + /// Sets `message` to the given value. + #[ink(message)] + pub fn set_message(&mut self, new_value: String) { + self.message = new_value.clone(); + + let from = self.env().caller(); + self.env().emit_event(Greeted { + from: Some(from), + message: new_value, + }); + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[ink::test] + fn new_works() { + let message = "Hello ink! v4".to_string(); + let greeter = Greeter::new(message.clone()); + assert_eq!(greeter.greet(), message); + } + + #[ink::test] + fn default_new_works() { + let greeter = Greeter::default(); + let default_message = String::from("Hello ink!"); + assert_eq!(greeter.greet(), default_message); + } + + #[ink::test] + fn set_message_works() { + let message_1 = String::from("gm ink!"); + let mut greeter = Greeter::new(message_1.clone()); + assert_eq!(greeter.greet(), message_1); + let message_2 = String::from("gn"); + greeter.set_message(message_2.clone()); + assert_eq!(greeter.greet(), message_2); + } + } +} diff --git a/contracts/test-all.sh b/contracts/test-all.sh new file mode 100755 index 0000000..7350556 --- /dev/null +++ b/contracts/test-all.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +set -eu + +# ENVIRONMENT VARIABLES +CONTRACTS_DIR="${CONTRACTS_DIR:=./src}" # Base contract directory + +# Determine all contracts under `$CONTRACTS_DIR` +contracts=($(find $CONTRACTS_DIR -maxdepth 1 -type d -exec test -f {}/Cargo.toml \; -print | xargs -n 1 basename)) + +# Test all contracts +for i in "${contracts[@]}" +do + echo -e "\nTesting '$CONTRACTS_DIR/$i/Cargo.toml'…" + cargo test --manifest-path $CONTRACTS_DIR/$i/Cargo.toml +done \ No newline at end of file diff --git a/contracts/tsconfig.json b/contracts/tsconfig.json new file mode 100644 index 0000000..8bcbc3d --- /dev/null +++ b/contracts/tsconfig.json @@ -0,0 +1,24 @@ +{ + "ts-node": { + "esm": true, + "experimentalSpecifierResolution": "node" + }, + "compilerOptions": { + "module": "esnext", + "moduleResolution": "bundler", + "target": "esnext", + "sourceMap": true, + "outDir": "dist", + "resolveJsonModule": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowJs": true, + "composite": true, + "baseUrl": ".", + "paths": { + "@/*": ["./scripts/*"] + } + }, + "exclude": ["node_modules", "dist", "target", "./*/target"], + "include": ["./deployments/**/*.json", "./deployments/**/*.ts", "./scripts/**/*.ts"] +} diff --git a/frontend/.env.local.example b/frontend/.env.local.example new file mode 100644 index 0000000..accd13a --- /dev/null +++ b/frontend/.env.local.example @@ -0,0 +1,19 @@ +## DOCS: https://github.com/scio-labs/inkathon#environment-variables + +## How use those variables in the frontend code? +## β†’ 1. Add them in `./src/config/environment.ts` +## β†’ 2. Always import `env` from `@config/environment` (not from `process.env`) + +## Flag to differentiate production environments (i.e. for analytics) +NEXT_PUBLIC_PRODUCTION_MODE=false + +## Active deployment url (i.e. useful for fetching from Next.js API routes) +NEXT_PUBLIC_URL=http://localhost:3000 + +## Default chain identifer the frontend should connect to first +NEXT_PUBLIC_DEFAULT_CHAIN=alephzero-testnet +# NEXT_PUBLIC_DEFAULT_CHAIN=development + +## [Optional] Multiple supported chain identifers the frontend connects to +## IMPORTANT: It's mandatory to use double quotes in the array +# NEXT_PUBLIC_SUPPORTED_CHAINS=[ "development", "alephzero-testnet", "rococo", "shibuya" ] \ No newline at end of file diff --git a/frontend/.eslintignore b/frontend/.eslintignore new file mode 100644 index 0000000..c4c528d --- /dev/null +++ b/frontend/.eslintignore @@ -0,0 +1,8 @@ +package-lock.json +pnpm-lock.yaml +node_modules +LICENSE + +out +.next +public \ No newline at end of file diff --git a/frontend/.eslintrc.json b/frontend/.eslintrc.json new file mode 100644 index 0000000..19a6e8c --- /dev/null +++ b/frontend/.eslintrc.json @@ -0,0 +1,25 @@ +{ + "root": true, + "parser": "@typescript-eslint/parser", + "plugins": ["@typescript-eslint"], + "extends": [ + "eslint:recommended", + "next/core-web-vitals", + "plugin:@typescript-eslint/recommended", + "prettier" + ], + "rules": { + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/no-non-null-assertion": "warn", + "@typescript-eslint/no-empty-function": "warn", + "react/no-children-prop": "warn", + "react-hooks/exhaustive-deps": "off", + "react/jsx-no-target-blank": "off", + "no-extra-boolean-cast": "off", + "prefer-const": "warn", + "no-restricted-imports": ["warn", { "patterns": ["process"] }] + } +} diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..69f6e69 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,44 @@ +# package management +**/node_modules +**/.pnp +.pnp.js +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# testing +/coverage + +# next.js +/.next/ +/out/ +next-env.d.ts + +# production +/build + +# local env files +.env +.env*.local + +# vercel +.vercel +.gitsigners + +# typescript +*.tsbuildinfo +dist diff --git a/frontend/.lintstagedrc.json b/frontend/.lintstagedrc.json new file mode 100644 index 0000000..6fb5b53 --- /dev/null +++ b/frontend/.lintstagedrc.json @@ -0,0 +1,4 @@ +{ + "*.{js,jsx,ts,tsx}": ["pnpm run lint:fix"], + "*.{json,md,mdx,html,css,yml,yaml}": ["pnpm run lint:format"] +} diff --git a/frontend/.prettierignore b/frontend/.prettierignore new file mode 100644 index 0000000..ea0d543 --- /dev/null +++ b/frontend/.prettierignore @@ -0,0 +1,10 @@ +package-lock.json +pnpm-lock.yaml +node_modules +LICENSE + +out +.next +public + +src/components/ui \ No newline at end of file diff --git a/frontend/.prettierrc.js b/frontend/.prettierrc.js new file mode 100644 index 0000000..65e90e0 --- /dev/null +++ b/frontend/.prettierrc.js @@ -0,0 +1,26 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-env node */ + +/** @type {import('prettier').Config} */ +module.exports = { + ...require('../.prettierrc.js'), + plugins: ['@trivago/prettier-plugin-sort-imports', 'prettier-plugin-tailwindcss'], + importOrder: [ + '^((react|next)/(.*)$)|^((react|next)$)', + '', + '^@/(config|types|styles|shared|lib|utils|hooks|components|app|pages|features)/(.*)$', + '^[./]', + ], + importOrderSeparation: true, + overrides: [ + { + files: ['*.ts', '*.tsx'], + options: { + parser: 'typescript', + importOrderParserPlugins: ['typescript', 'jsx'], + }, + }, + ], + tailwindConfig: 'tailwind.config.ts', + tailwindFunctions: ['clsx', 'cva'], +} diff --git a/frontend/CHANGELOG.md b/frontend/CHANGELOG.md new file mode 100644 index 0000000..a874ce3 --- /dev/null +++ b/frontend/CHANGELOG.md @@ -0,0 +1,127 @@ +# @inkathon/frontend + +## 0.4.2 + +### Patch Changes + +- [`bc7d7ed`](https://github.com/scio-labs/inkathon/commit/bc7d7ed546fc2f17b6adaf96e34645f84ac2a5e0) Thanks [@wottpal](https://github.com/wottpal)! - Move VSCode settings to `settings.json` file but keep `inkathon.code-workspace`. It's now also supported by default to develop with ink!athon without opening the code-workspace file. + +- Updated dependencies [[`cf68f5f`](https://github.com/scio-labs/inkathon/commit/cf68f5f96888c69434014ff4f8eccdd3558d20bc), [`bc7d7ed`](https://github.com/scio-labs/inkathon/commit/bc7d7ed546fc2f17b6adaf96e34645f84ac2a5e0)]: + - @inkathon/contracts@0.4.2 + +## 0.4.1 + +### Patch Changes + +- [`14e8e11`](https://github.com/scio-labs/inkathon/commit/14e8e11ebc857e81b7cfa97e7c3c7f28d8dbccc3) Thanks [@wottpal](https://github.com/wottpal)! - Add sample code snippets from live workshops (greeter message reversion & make-it-rain script) + +- Updated dependencies [[`14e8e11`](https://github.com/scio-labs/inkathon/commit/14e8e11ebc857e81b7cfa97e7c3c7f28d8dbccc3)]: + - @inkathon/contracts@0.4.1 + +## 0.4.0 + +### Minor Changes + +- [#42](https://github.com/scio-labs/inkathon/pull/42) [`0533391`](https://github.com/scio-labs/inkathon/commit/0533391ac6f9b953ba0cb231af8b3037e80bcbab) Thanks [@ical10](https://github.com/ical10)! - Update project default to Node 20. + +- [#42](https://github.com/scio-labs/inkathon/pull/42) [`bc721ea`](https://github.com/scio-labs/inkathon/commit/bc721ea638a33d5d9d993eecddfd2a6f3ece1bfe) Thanks [@ical10](https://github.com/ical10)! - - Migrate the current pages directory to the Next.js 13 app directory. + - Migrate to `shadcn/ui` components and vanilla tailwind. + +### Patch Changes + +- Updated dependencies [[`0533391`](https://github.com/scio-labs/inkathon/commit/0533391ac6f9b953ba0cb231af8b3037e80bcbab)]: + - @inkathon/contracts@0.4.0 + +## 0.3.2 + +### Patch Changes + +- Updated dependencies [[`47aed1b`](https://github.com/scio-labs/inkathon/commit/47aed1b722138bd6fca2883337151d3c0b77e4a3)]: + - @inkathon/contracts@0.3.2 + +## 0.3.1 + +### Patch Changes + +- Updated dependencies [[`e73d9b8`](https://github.com/scio-labs/inkathon/commit/e73d9b86a4299702c59538ac43612b9977d479be)]: + - @inkathon/contracts@0.3.1 + +## 0.3.0 + +### Minor Changes + +- [`64adba1`](https://github.com/scio-labs/inkathon/commit/64adba196dd98ad272bbb4a99b4f7bc7186ae385) Thanks [@wottpal](https://github.com/wottpal)! - Add Nightly Connect support for Aleph Zero, Aleph Zero Testnet, and Local Node. Checkout: https://connect.nightly.app/. + +## 0.3.0 + +### Patch Changes + +- Updated dependencies [[`cda19ae`](https://github.com/scio-labs/inkathon/commit/cda19aeb4107c076daeb17a455fecfbd7f373044)]: + - @inkathon/contracts@0.3.0 + +## 0.2.1 + +### Patch Changes + +- Updated dependencies [[`3f4179e`](https://github.com/scio-labs/inkathon/commit/3f4179e9325b155324d23796234d9f853ae03dd9)]: + - @inkathon/contracts@0.2.1 + +## 0.2.0 + +### Minor Changes + +- [`c2cfbe4`](https://github.com/scio-labs/inkathon/commit/c2cfbe428a4e86f7ddb3d25886d4da79238b69be) Thanks [@wottpal](https://github.com/wottpal)! - Ensure & document Windows, Ubuntu, and macOS compatibility. 🌈 + +### Patch Changes + +- Updated dependencies [[`c2cfbe4`](https://github.com/scio-labs/inkathon/commit/c2cfbe428a4e86f7ddb3d25886d4da79238b69be)]: + - @inkathon/contracts@0.2.0 + +## 0.1.3 + +### Patch Changes + +- [`4bda28d`](https://github.com/scio-labs/inkathon/commit/4bda28d645abc8d8684d33bac788f04c278d7b4e) Thanks [@wottpal](https://github.com/wottpal)! - Further cross-platform script improvements (i.e. regarding the touch command). + +- Updated dependencies [[`4bda28d`](https://github.com/scio-labs/inkathon/commit/4bda28d645abc8d8684d33bac788f04c278d7b4e)]: + - @inkathon/contracts@0.1.3 + +## 0.1.2 + +### Patch Changes + +- [`2b9bc68`](https://github.com/scio-labs/inkathon/commit/2b9bc689876ea195a1cf2f6af1ca2414bcf04172) Thanks [@wottpal](https://github.com/wottpal)! - Make cp/copy command work cross-platform (i.e. on Windows) for postinstall and build-all scripts. + +- Updated dependencies [[`2b9bc68`](https://github.com/scio-labs/inkathon/commit/2b9bc689876ea195a1cf2f6af1ca2414bcf04172)]: + - @inkathon/contracts@0.1.2 + +## 0.1.1 + +### Patch Changes + +- [`1556c0f`](https://github.com/scio-labs/inkathon/commit/1556c0fb526c0b0219217cd19ab2a47dcc038ba4) Thanks [@wottpal](https://github.com/wottpal)! - Fix `@polkadot/*` package warnings about cjs/esm duplications. + +## 0.1.0 + +### Minor Changes + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Move `frontend` and `contracts` packages to the root level + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`7a41afe`](https://github.com/scio-labs/inkathon/commit/7a41afe1e7c2f45b6d3972760c173a4a2197c643) Thanks [@wottpal](https://github.com/wottpal)! - Add contributor guidelines at `CONTRIBUTING.md`. + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`3598618`](https://github.com/scio-labs/inkathon/commit/3598618f87d788ec51964167557210ed8b659797) Thanks [@wottpal](https://github.com/wottpal)! - Major README.md overhaul & improvements + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Switch from `husky` to `simple-git-hooks` pre-commit hooks + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`07d8381`](https://github.com/scio-labs/inkathon/commit/07d83819c48f4aaa129ccc3d27929767b916c93d) Thanks [@wottpal](https://github.com/wottpal)! - Add compatability for using yarn (stable only, not classic v1) as the package manager. Note: npm is still not compatible as it lacks support for the workspace import protocol. + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Auto-create `.env.local` files upon first package install if non-existent + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964) Thanks [@wottpal](https://github.com/wottpal)! - Setup changeset integration for version, release, and changelog management. + +- [#30](https://github.com/scio-labs/inkathon/pull/30) [`bda4108`](https://github.com/scio-labs/inkathon/commit/bda4108c9aac8234bdb5989caea0daa8d12f46fb) Thanks [@wottpal](https://github.com/wottpal)! - Change `@…` local import path shortcut to `@/…` (create-next-app default). + +### Patch Changes + +- Updated dependencies [[`cf04f67`](https://github.com/scio-labs/inkathon/commit/cf04f671c06276ffc51e33c1e38c181173227d75), [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964), [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964), [`7a41afe`](https://github.com/scio-labs/inkathon/commit/7a41afe1e7c2f45b6d3972760c173a4a2197c643), [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964), [`3598618`](https://github.com/scio-labs/inkathon/commit/3598618f87d788ec51964167557210ed8b659797), [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964), [`07d8381`](https://github.com/scio-labs/inkathon/commit/07d83819c48f4aaa129ccc3d27929767b916c93d), [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964), [`1839164`](https://github.com/scio-labs/inkathon/commit/183916440fb3043d06c1fd603aba923eb21a5964)]: + - @inkathon/contracts@0.1.0 diff --git a/frontend/components.json b/frontend/components.json new file mode 100644 index 0000000..9990aa4 --- /dev/null +++ b/frontend/components.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "tailwind.config.ts", + "css": "src/app/globals.css", + "baseColor": "zinc", + "cssVariables": true + }, + "aliases": { + "components": "@/components", + "utils": "@/utils/cn" + } +} diff --git a/frontend/next.config.js b/frontend/next.config.js new file mode 100644 index 0000000..b4bb55b --- /dev/null +++ b/frontend/next.config.js @@ -0,0 +1,25 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-env node */ +// @ts-check + +/** + * @type {import('next').NextConfig} + **/ +const nextConfig = { + reactStrictMode: true, + // Fix for warnings about cjs/esm package duplication + // See: https://github.com/polkadot-js/api/issues/5636 + transpilePackages: [ + '**@polkadot/**', + '@polkadot/api', + '@polkadot/api-contract', + '@polkadot/extension-dapp', + '@polkadot/extension-inject', + '@polkadot/keyring', + '@polkadot/types', + '@polkadot/util', + '@polkadot/util-crypto', + ], +} + +module.exports = nextConfig diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..ae704f9 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,76 @@ +{ + "name": "@inkathon/frontend", + "private": true, + "version": "0.4.2", + "scripts": { + "postinstall": "bash postinstall.sh", + "dev": "NODE_ENV=development POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG=1 next dev", + "node": "pnpm run -F contracts node", + "dev-and-node": "concurrently \"pnpm dev\" \"pnpm node\" --names \"Next,Node\" --kill-others", + "build": "NODE_ENV=production next build", + "start": "NODE_ENV=production next start", + "type-check": "tsc --pretty --noEmit", + "sync-types": "typesync", + "lint": "prettier . --check && eslint .", + "lint:fix": "prettier . --write && eslint . --fix", + "lint:format": "prettier . --write" + }, + "dependencies": { + "@azns/resolver-core": "^1.6.0", + "@azns/resolver-react": "^1.6.0", + "@hookform/resolvers": "^3.3.2", + "@inkathon/contracts": "workspace:*", + "@polkadot/api": "^10.11.2", + "@polkadot/api-contract": "^10.11.2", + "@polkadot/extension-dapp": "^0.46.6", + "@polkadot/extension-inject": "^0.46.6", + "@polkadot/keyring": "^12.6.2", + "@polkadot/types": "^10.11.2", + "@polkadot/util": "^12.6.2", + "@polkadot/util-crypto": "^12.6.2", + "@radix-ui/react-dropdown-menu": "^2.0.6", + "@radix-ui/react-label": "^2.0.2", + "@radix-ui/react-slot": "^1.0.2", + "@radix-ui/react-tooltip": "^1.0.7", + "@scio-labs/use-inkathon": "^0.6.3", + "@vercel/analytics": "^1.1.1", + "autoprefixer": "^10.4.16", + "class-variance-authority": "^0.7.0", + "clsx": "^2.0.0", + "geist": "^1.2.0", + "lucide-react": "^0.298.0", + "next": "^14.0.4", + "postcss": "^8.4.32", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-hook-form": "^7.49.2", + "react-hot-toast": "^2.4.1", + "react-icons": "^4.12.0", + "sharp": "^0.33.1", + "spinners-react": "^1.0.7", + "tailwind-merge": "^2.1.0", + "tailwindcss-animate": "^1.0.7", + "use-async-effect": "^2.2.7", + "zod": "^3.22.4" + }, + "devDependencies": { + "@trivago/prettier-plugin-sort-imports": "^4.3.0", + "@types/downloadjs": "^1.4.5", + "@types/eslint": "^8.44.9", + "@types/eslint-config-prettier": "^6.11.3", + "@types/node": "^20.10.5", + "@types/react": "^18.2.45", + "@types/react-dom": "^18.2.18", + "@typescript-eslint/eslint-plugin": "^6.15.0", + "@typescript-eslint/parser": "^6.15.0", + "concurrently": "^8.2.2", + "eslint": "^8.56.0", + "eslint-config-next": "^14.0.4", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-react": "^7.33.2", + "prettier": "^3.1.1", + "prettier-plugin-tailwindcss": "^0.5.9", + "tailwindcss": "^3.3.7", + "typescript": "^5.3.3" + } +} diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 0000000..33ad091 --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,6 @@ +module.exports = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/frontend/postinstall.sh b/frontend/postinstall.sh new file mode 100755 index 0000000..4e5a231 --- /dev/null +++ b/frontend/postinstall.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -eu + +# This script creates a default '.env.local' file if it doesn't exist yet. +# More information about environment variables: https://github.com/scio-labs/inkathon#environment-variables + +if [[ ! -e .env.local ]]; then + echo "Creating default '.env.local'…" + CP_CMD=$(command -v cp &> /dev/null && echo "cp" || echo "copy") + $CP_CMD .env.local.example .env.local +else + echo "Great, '.env.local' already exists! Skipping…" +fi diff --git a/frontend/public/icons/azns-icon.svg b/frontend/public/icons/azns-icon.svg new file mode 100644 index 0000000..7c22548 --- /dev/null +++ b/frontend/public/icons/azns-icon.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/frontend/public/icons/github-button.svg b/frontend/public/icons/github-button.svg new file mode 100644 index 0000000..2558614 --- /dev/null +++ b/frontend/public/icons/github-button.svg @@ -0,0 +1,17 @@ + + + github-button + + + + + + + + + + + + + + \ No newline at end of file diff --git a/frontend/public/icons/github.svg b/frontend/public/icons/github.svg new file mode 100644 index 0000000..eb0a499 --- /dev/null +++ b/frontend/public/icons/github.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/icons/telegram-button.svg b/frontend/public/icons/telegram-button.svg new file mode 100644 index 0000000..d279023 --- /dev/null +++ b/frontend/public/icons/telegram-button.svg @@ -0,0 +1,23 @@ + + + telegram-button + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/frontend/public/icons/vercel-button.svg b/frontend/public/icons/vercel-button.svg new file mode 100644 index 0000000..614f528 --- /dev/null +++ b/frontend/public/icons/vercel-button.svg @@ -0,0 +1,17 @@ + + + vercel-button + + + + + + + + + + + + + + \ No newline at end of file diff --git a/frontend/public/images/inkathon-logo.png b/frontend/public/images/inkathon-logo.png new file mode 100644 index 0000000..6bf77da Binary files /dev/null and b/frontend/public/images/inkathon-logo.png differ diff --git a/frontend/public/images/inkathon-og-banner.jpg b/frontend/public/images/inkathon-og-banner.jpg new file mode 100644 index 0000000..9ed5b7a Binary files /dev/null and b/frontend/public/images/inkathon-og-banner.jpg differ diff --git a/frontend/src/app/components/home-page-title.tsx b/frontend/src/app/components/home-page-title.tsx new file mode 100644 index 0000000..3d8639e --- /dev/null +++ b/frontend/src/app/components/home-page-title.tsx @@ -0,0 +1,97 @@ +import Image from 'next/image' +import Link from 'next/link' +import { AnchorHTMLAttributes, FC } from 'react' + +import githubIcon from 'public/icons/github-button.svg' +import telegramIcon from 'public/icons/telegram-button.svg' +import vercelIcon from 'public/icons/vercel-button.svg' +import inkathonLogo from 'public/images/inkathon-logo.png' + +import { cn } from '@/utils/cn' + +interface StyledIconLinkProps extends AnchorHTMLAttributes { + href: string + className?: string +} + +const StyledIconLink: React.FC = ({ className, children, ...rest }) => ( + + {children} + +) + +export const HomePageTitle: FC = () => { + const title = 'ink!athon' + const desc = 'Full-Stack DApp Boilerplate for ink! Smart Contracts' + const githubHref = 'https://github.com/scio-labs/inkathon' + const deployHref = 'https://github.com/scio-labs/inkathon#deployment-' + const telegramHref = 'https://t.me/inkathon' + + return ( + <> +
+ {/* Logo & Title */} + + ink!athon Logo +

{title}

+ + + {/* Tagline & Lincks */} +

{desc}

+

+ Built by{' '} + + Dennis Zoma + {' '} + &{' '} + + Scio Labs + + . Supported by{' '} + + Aleph Zero + + . +

+ + {/* Github & Vercel Buttons */} +
+ + Github Repository + + + Deploy with Vercel + + + Telegram Group + +
+ +
+
+ + ) +} diff --git a/frontend/src/app/components/home-top-bar.tsx b/frontend/src/app/components/home-top-bar.tsx new file mode 100644 index 0000000..52afee5 --- /dev/null +++ b/frontend/src/app/components/home-top-bar.tsx @@ -0,0 +1,26 @@ +'use client' + +import Link from 'next/link' +import { FC } from 'react' + +import { HiOutlineExternalLink } from 'react-icons/hi' + +export const HomeTopBar: FC = () => { + return ( + <> + +
+ VIDEOβ–Ά +
+
+ Watch the sub0 ink!athon workshop (45 min) + sub0 ink!athon workshop +
+ + + + ) +} diff --git a/frontend/src/app/favicon.ico b/frontend/src/app/favicon.ico new file mode 100644 index 0000000..a0ec94b Binary files /dev/null and b/frontend/src/app/favicon.ico differ diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css new file mode 100644 index 0000000..11053e9 --- /dev/null +++ b/frontend/src/app/globals.css @@ -0,0 +1,80 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 224 71.4% 4.1%; + + --card: 0 0% 100%; + --card-foreground: 224 71.4% 4.1%; + + --popover: 0 0% 100%; + --popover-foreground: 224 71.4% 4.1%; + + --primary: 262.1 83.3% 57.8%; + --primary-foreground: 210 20% 98%; + + --secondary: 220 14.3% 95.9%; + --secondary-foreground: 220.9 39.3% 11%; + + --muted: 220 14.3% 95.9%; + --muted-foreground: 220 8.9% 46.1%; + + --accent: 220 14.3% 95.9%; + --accent-foreground: 220.9 39.3% 11%; + + --destructive: 0 84.2% 60.2%; + --destructive-foreground: 210 20% 98%; + + --border: 220 13% 91%; + --input: 220 13% 91%; + --ring: 262.1 83.3% 57.8%; + + --radius: 0.75rem; + } + + .dark { + --background: 224 71.4% 4.1%; + + --foreground: 210 20% 98%; + --card: 224 71.4% 4.1%; + --card-foreground: 210 20% 98%; + + --popover: 224 71.4% 4.1%; + --popover-foreground: 210 20% 98%; + + --primary: 263.4 70% 50.4%; + --primary-foreground: 210 20% 98%; + + --secondary: 215 27.9% 16.9%; + --secondary-foreground: 210 20% 98%; + + --muted: 215 27.9% 16.9%; + --muted-foreground: 217.9 10.6% 64.9%; + + --accent: 215 27.9% 16.9%; + --accent-foreground: 210 20% 98%; + + --destructive: 0 62.8% 30.6%; + --destructive-foreground: 210 20% 98%; + + --border: 215 27.9% 16.9%; + --input: 215 27.9% 16.9%; + --ring: 263.4 70% 50.4%; + } +} + +@layer base { + * { + @apply border-border; + } + html { + @apply scroll-smooth antialiased; + } + body { + @apply bg-background font-sans text-foreground; + @apply flex h-screen min-h-screen flex-col; + } +} diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx new file mode 100644 index 0000000..c76b07f --- /dev/null +++ b/frontend/src/app/layout.tsx @@ -0,0 +1,59 @@ +import { Metadata, Viewport } from 'next' +import { PropsWithChildren } from 'react' + +import { Analytics } from '@vercel/analytics/react' +import { GeistMono } from 'geist/font/mono' +import { GeistSans } from 'geist/font/sans' + +import { ToastConfig } from '@/app/toast-config' +import { TooltipProvider } from '@/components/ui/tooltip' +import { env } from '@/config/environment' +import { cn } from '@/utils/cn' + +import './globals.css' +import ClientProviders from './providers' + +export const viewport: Viewport = { + themeColor: '#000000', + colorScheme: 'dark', +} + +export const metadata: Metadata = { + title: 'ink!athon Boilerplate', + description: 'Full-Stack DApp Boilerplate for ink! Smart Contracts', + metadataBase: new URL(env.url), + robots: env.isProduction ? 'all' : 'noindex,nofollow', + openGraph: { + type: 'website', + locale: 'en', + url: env.url, + siteName: 'ink!athon Boilerplate', + images: [ + { + url: '/images/inkathon-og-banner.jpg', + width: 1280, + height: 640, + }, + ], + }, + twitter: { + site: '@scio_xyz', + creator: '@scio_xyz', + card: 'summary_large_image', + }, +} + +export default function RootLayout({ children }: PropsWithChildren) { + return ( + + + + {children} + + + + {!!env.isProduction && } + + + ) +} diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx new file mode 100644 index 0000000..c5a9300 --- /dev/null +++ b/frontend/src/app/page.tsx @@ -0,0 +1,40 @@ +'use client' + +import { useEffect } from 'react' + +import { useInkathon } from '@scio-labs/use-inkathon' +import { toast } from 'react-hot-toast' + +import { HomePageTitle } from '@/app/components/home-page-title' +import { ChainInfo } from '@/components/web3/chain-info' +import { ConnectButton } from '@/components/web3/connect-button' +import { GreeterContractInteractions } from '@/components/web3/greeter-contract-interactions' + +export default function HomePage() { + // Display `useInkathon` error messages (optional) + const { error } = useInkathon() + useEffect(() => { + if (!error) return + toast.error(error.message) + }, [error]) + + return ( + <> +
+ {/* Title */} + + + {/* Connect Wallet Button */} + + +
+ {/* Chain Metadata Information */} + + + {/* Greeter Read/Write Contract Interactions */} + +
+
+ + ) +} diff --git a/frontend/src/app/providers.tsx b/frontend/src/app/providers.tsx new file mode 100644 index 0000000..fb1a52a --- /dev/null +++ b/frontend/src/app/providers.tsx @@ -0,0 +1,21 @@ +'use client' + +import { PropsWithChildren } from 'react' + +import { getDeployments } from '@/deployments/deployments' +import { UseInkathonProvider } from '@scio-labs/use-inkathon' + +import { env } from '@/config/environment' + +export default function ClientProviders({ children }: PropsWithChildren) { + return ( + + {children} + + ) +} diff --git a/frontend/src/app/toast-config.tsx b/frontend/src/app/toast-config.tsx new file mode 100644 index 0000000..b69a6da --- /dev/null +++ b/frontend/src/app/toast-config.tsx @@ -0,0 +1,35 @@ +import { FC } from 'react' + +import { Toaster } from 'react-hot-toast' + +export const ToastConfig: FC = () => { + return ( + + ) +} diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx new file mode 100644 index 0000000..006acdb --- /dev/null +++ b/frontend/src/components/ui/button.tsx @@ -0,0 +1,66 @@ +import { Slot } from '@radix-ui/react-slot' +import { cva, type VariantProps } from 'class-variance-authority' +import * as React from 'react' + +import { cn } from '@/utils/cn' +import { Spinner } from './spinner' + +const buttonVariants = cva( + 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50', + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground hover:bg-primary/90', + destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90', + outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground', + secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80', + ghost: 'hover:bg-accent hover:text-accent-foreground', + link: 'text-primary underline-offset-4 hover:underline', + }, + size: { + default: 'h-10 px-4 py-2', + sm: 'h-9 rounded-md px-3', + lg: 'h-11 rounded-md px-8', + icon: 'h-10 w-10', + }, + }, + defaultVariants: { + variant: 'default', + size: 'default', + }, + }, +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean + isLoading?: boolean +} + +const Button = React.forwardRef( + ({ className, variant, size, asChild = false, isLoading, children, ...props }, ref) => { + const Comp = asChild ? Slot : 'button' + + if (isLoading) + return ( + + + {children} + + ) + + return ( + + {children} + + ) + }, +) +Button.displayName = 'Button' + +export { Button, buttonVariants } diff --git a/frontend/src/components/ui/card.tsx b/frontend/src/components/ui/card.tsx new file mode 100644 index 0000000..487d133 --- /dev/null +++ b/frontend/src/components/ui/card.tsx @@ -0,0 +1,80 @@ +import * as React from "react" + +import { cn } from "@/utils/cn" + +const Card = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +Card.displayName = "Card" + +const CardHeader = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardHeader.displayName = "CardHeader" + +const CardTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardTitle.displayName = "CardTitle" + +const CardDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardDescription.displayName = "CardDescription" + +const CardContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +

+)) +CardContent.displayName = "CardContent" + +const CardFooter = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)) +CardFooter.displayName = "CardFooter" + +export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } + diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsx new file mode 100644 index 0000000..3a4e544 --- /dev/null +++ b/frontend/src/components/ui/dropdown-menu.tsx @@ -0,0 +1,190 @@ +"use client" + +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" +import { Check, ChevronRight, Circle } from "lucide-react" +import * as React from "react" + +import { cn } from "@/utils/cn" + +const DropdownMenu = DropdownMenuPrimitive.Root + +const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger + +const DropdownMenuGroup = DropdownMenuPrimitive.Group + +const DropdownMenuPortal = DropdownMenuPrimitive.Portal + +const DropdownMenuSub = DropdownMenuPrimitive.Sub + +const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup + +const DropdownMenuSubTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean + } +>(({ className, inset, children, ...props }, ref) => ( + + {children} + + +)) +DropdownMenuSubTrigger.displayName = + DropdownMenuPrimitive.SubTrigger.displayName + +const DropdownMenuSubContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DropdownMenuSubContent.displayName = + DropdownMenuPrimitive.SubContent.displayName + +const DropdownMenuContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 4, ...props }, ref) => ( + + + +)) +DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName + +const DropdownMenuItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean + } +>(({ className, inset, ...props }, ref) => ( + +)) +DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName + +const DropdownMenuCheckboxItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, checked, ...props }, ref) => ( + + + + + + + {children} + +)) +DropdownMenuCheckboxItem.displayName = + DropdownMenuPrimitive.CheckboxItem.displayName + +const DropdownMenuRadioItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)) +DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName + +const DropdownMenuLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean + } +>(({ className, inset, ...props }, ref) => ( + +)) +DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName + +const DropdownMenuSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName + +const DropdownMenuShortcut = ({ + className, + ...props +}: React.HTMLAttributes) => { + return ( + + ) +} +DropdownMenuShortcut.displayName = "DropdownMenuShortcut" + +export { + DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, + DropdownMenuShortcut, DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, DropdownMenuTrigger +} + diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsx new file mode 100644 index 0000000..7efbe17 --- /dev/null +++ b/frontend/src/components/ui/form.tsx @@ -0,0 +1,172 @@ +import * as LabelPrimitive from "@radix-ui/react-label" +import { Slot } from "@radix-ui/react-slot" +import * as React from "react" +import { + Controller, + ControllerProps, + FieldPath, + FieldValues, + FormProvider, + useFormContext, +} from "react-hook-form" + +import { Label } from "@/components/ui/label" +import { cn } from "@/utils/cn" + +const Form = FormProvider + +type FormFieldContextValue< + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath +> = { + name: TName +} + +const FormFieldContext = React.createContext( + {} as FormFieldContextValue +) + +const FormField = < + TFieldValues extends FieldValues = FieldValues, + TName extends FieldPath = FieldPath +>({ + ...props +}: ControllerProps) => { + return ( + + + + ) +} + +const useFormField = () => { + const fieldContext = React.useContext(FormFieldContext) + const itemContext = React.useContext(FormItemContext) + const { getFieldState, formState } = useFormContext() + + const fieldState = getFieldState(fieldContext.name, formState) + + if (!fieldContext) { + throw new Error("useFormField should be used within ") + } + + const { id } = itemContext + + return { + id, + name: fieldContext.name, + formItemId: `${id}-form-item`, + formDescriptionId: `${id}-form-item-description`, + formMessageId: `${id}-form-item-message`, + ...fieldState, + } +} + +type FormItemContextValue = { + id: string +} + +const FormItemContext = React.createContext( + {} as FormItemContextValue +) + +const FormItem = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => { + const id = React.useId() + + return ( + +
+ + ) +}) +FormItem.displayName = "FormItem" + +const FormLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => { + const { error, formItemId } = useFormField() + + return ( +