init monorepo
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
# Changesets
|
||||
|
||||
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
|
||||
with multi-package repos, or single-package repos to help you version and publish your code. You can
|
||||
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
|
||||
|
||||
We have a quick list of common questions to get you started engaging with this project in
|
||||
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
|
||||
"changelog": "@changesets/cli/changelog",
|
||||
"commit": false,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "public",
|
||||
"baseBranch": "main",
|
||||
"updateInternalDependencies": "patch",
|
||||
"ignore": []
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
"@thirdweb-dev/auth": patch
|
||||
"thirdweb": patch
|
||||
"@thirdweb-dev/contracts-js": patch
|
||||
"eslint-config-thirdweb": patch
|
||||
"@thirdweb-dev/react": patch
|
||||
"@thirdweb-dev/sdk": patch
|
||||
"@thirdweb-dev/solana": patch
|
||||
"@thirdweb-dev/storage": patch
|
||||
"@thirdweb-dev/tsconfig": patch
|
||||
---
|
||||
|
||||
init monorepo
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
.turbo
|
||||
*.log
|
||||
.next
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.env
|
||||
.cache
|
||||
server/dist
|
||||
public/dist
|
||||
.turbo
|
||||
./packages/contracts-js/abis
|
||||
@@ -0,0 +1,2 @@
|
||||
lib
|
||||
node_modules
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": false,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at <support@thirdweb.com>. All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/js",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"repository": "[email protected]:thirdweb-dev/js.git",
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"packages/*"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.24.3",
|
||||
"eslint": "^8.23.0",
|
||||
"eslint-config-acme": "*",
|
||||
"prettier": "^2.7.1",
|
||||
"turbo": "latest",
|
||||
"yarn-deduplicate": "^5.0.2"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "turbo run test",
|
||||
"build": "turbo run build",
|
||||
"dev": "turbo run dev --no-cache --parallel --continue",
|
||||
"lint": "turbo run lint",
|
||||
"clean": "turbo run clean && rm -rf node_modules",
|
||||
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
|
||||
"changeset": "changeset",
|
||||
"version-packages": "changeset version",
|
||||
"release": "turbo run build && changeset publish",
|
||||
"postinstall": "yarn-deduplicate yarn.lock"
|
||||
},
|
||||
"preconstruct": {
|
||||
"packages": [
|
||||
"packages/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"presets": [
|
||||
"@babel/preset-typescript",
|
||||
"@babel/preset-env"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ["thirdweb"],
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/express
|
||||
/next
|
||||
/.yalc
|
||||
yalc.lock
|
||||
yarn-error.log
|
||||
.DS_Store
|
||||
package-lock.json
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021 Non-Fungible Labs, Inc
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,23 @@
|
||||
<p align="center">
|
||||
<br />
|
||||
<a href="https://thirdweb.com"><img src="https://github.com/thirdweb-dev/typescript-sdk/blob/main/logo.svg?raw=true" width="200" alt=""/></a>
|
||||
<br />
|
||||
</p>
|
||||
<h1 align="center">thirdweb Auth</h1>
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/thirdweb"><img alt="Join our Discord!" src="https://img.shields.io/discord/834227967404146718.svg?color=7289da&label=discord&logo=discord&style=flat"/></a>
|
||||
|
||||
</p>
|
||||
<p align="center"><strong>Best in class wallet authentication for Node backends</strong></p>
|
||||
<br />
|
||||
|
||||
## Installation
|
||||
|
||||
Install the latest version of the SDK with either `npm` or `yarn`:
|
||||
|
||||
```shell
|
||||
npm install @thirdweb-dev/auth @thirdweb-dev/sdk ethers
|
||||
```
|
||||
```shell
|
||||
yarn add @thirdweb-dev/auth @thirdweb-dev/sdk ethers
|
||||
```
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/auth",
|
||||
"version": "0.2.0",
|
||||
"repository": {
|
||||
"directory": "packages/auth",
|
||||
"type": "git",
|
||||
"url": "https://github.com/thirdweb-dev/js.git"
|
||||
},
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist/",
|
||||
"next/",
|
||||
"express/"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "preconstruct build",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"preconstruct": {
|
||||
"entrypoints": [
|
||||
"next/index.ts",
|
||||
"express/index.ts"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.18.10",
|
||||
"@babel/preset-typescript": "^7.18.6",
|
||||
"@microsoft/api-documenter": "^7.19.4",
|
||||
"@microsoft/api-extractor": "^7.29.2",
|
||||
"@microsoft/tsdoc": "^0.14.1",
|
||||
"@preconstruct/cli": "^2.2.1",
|
||||
"@thirdweb-dev/sdk": "*",
|
||||
"@trivago/prettier-plugin-sort-imports": "^3.3.0",
|
||||
"@types/cookie": "^0.5.1",
|
||||
"@types/cookie-parser": "^1.4.3",
|
||||
"@types/express": "^4.17.13",
|
||||
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
||||
"@typescript-eslint/parser": "^5.33.0",
|
||||
"eslint": "^8.21.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-inclusive-language": "^2.2.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"eslint-plugin-tsdoc": "^0.2.16",
|
||||
"ethers": ">=5.5.1",
|
||||
"express": "^4.18.1",
|
||||
"next": "12.2.0",
|
||||
"prettier": "^2.7.1",
|
||||
"typescript": "^4.7.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@thirdweb-dev/sdk": "*",
|
||||
"ethers": ">=5.5.1",
|
||||
"express": "^4.18.1",
|
||||
"next": "12.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"cookie": "^0.5.0",
|
||||
"cookie-parser": "^1.4.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import loginHandler from "./routes/login";
|
||||
import logoutHandler from "./routes/logout";
|
||||
import userHandler from "./routes/user";
|
||||
import {
|
||||
ThirdwebAuthConfig,
|
||||
ThirdwebAuthRoute,
|
||||
ThirdwebAuthUser,
|
||||
} from "./types";
|
||||
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
|
||||
import cookieParser from "cookie-parser";
|
||||
import { Express, NextFunction, Request, Response } from "express";
|
||||
|
||||
export * from "./types";
|
||||
|
||||
export function getUser(req: Request): ThirdwebAuthUser | null {
|
||||
return req.user;
|
||||
}
|
||||
|
||||
export function ThirdwebAuth(app: Express, cfg: ThirdwebAuthConfig) {
|
||||
const ctx = {
|
||||
...cfg,
|
||||
sdk: ThirdwebSDK.fromPrivateKey(cfg.privateKey, "mainnet"),
|
||||
};
|
||||
|
||||
const authUrl = cfg.authUrl?.replace(/\/$/, "") || "/auth";
|
||||
|
||||
app.use(cookieParser());
|
||||
|
||||
app.use(async (req: Request, _: Response, next: NextFunction) => {
|
||||
const { sdk, domain } = ctx;
|
||||
let user = null;
|
||||
const token = req.cookies.thirdweb_auth_token;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const address = await sdk.auth.authenticate(domain, token);
|
||||
user = { address };
|
||||
} catch {
|
||||
// No-op
|
||||
}
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
});
|
||||
|
||||
app.get(`${authUrl}/:route`, (req: Request, res: Response) => {
|
||||
const action = req.params.route as ThirdwebAuthRoute;
|
||||
|
||||
switch (action) {
|
||||
case "login":
|
||||
return loginHandler(req, res, ctx);
|
||||
case "user":
|
||||
return userHandler(req, res);
|
||||
case "logout":
|
||||
return logoutHandler(req, res);
|
||||
default:
|
||||
return res.status(400).json({
|
||||
message: "Invalid route for authentication.",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { ThirdwebAuthContext } from "../types";
|
||||
import { LoginPayload } from "@thirdweb-dev/sdk/dist/src/schema";
|
||||
import { serialize } from "cookie";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
function redirectWithError(req: Request, res: Response, error: string) {
|
||||
const encodedError = encodeURIComponent(error);
|
||||
const url = new URL(req.headers.referer as string);
|
||||
url.searchParams.set("error", encodedError);
|
||||
return res.redirect(url.toString());
|
||||
}
|
||||
|
||||
export default async function handler(
|
||||
req: Request,
|
||||
res: Response,
|
||||
ctx: ThirdwebAuthContext
|
||||
) {
|
||||
if (req.method !== "GET") {
|
||||
return redirectWithError(req, res, "INVALID_METHOD");
|
||||
}
|
||||
|
||||
const { sdk, domain } = ctx;
|
||||
|
||||
// Get signed login payload from the frontend
|
||||
const payload = JSON.parse(atob(req.query.payload as string)) as LoginPayload;
|
||||
if (!payload) {
|
||||
redirectWithError(req, res, "MISSING_LOGIN_PAYLOAD");
|
||||
}
|
||||
|
||||
let token;
|
||||
try {
|
||||
// Generate an access token with the SDK using the signed payload
|
||||
token = await sdk.auth.generateAuthToken(domain, payload);
|
||||
} catch {
|
||||
return redirectWithError(req, res, "INVALID_LOGIN_PAYLOAD");
|
||||
}
|
||||
|
||||
// Securely set httpOnly cookie on request to prevent XSS on frontend
|
||||
// And set path to / to enable thirdweb_auth_token usage on all endpoints
|
||||
res.setHeader(
|
||||
"Set-Cookie",
|
||||
serialize("thirdweb_auth_token", token, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "strict",
|
||||
})
|
||||
);
|
||||
|
||||
return res.status(301).redirect(req.query.redirect as string);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { serialize } from "cookie";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export default async function handler(req: Request, res: Response) {
|
||||
if (req.method !== "GET") {
|
||||
return res.status(400).json({
|
||||
error: "Invalid method. Only GET supported.",
|
||||
});
|
||||
}
|
||||
|
||||
// Set the access token to 'none' and expire in 5 seconds
|
||||
res.setHeader(
|
||||
"Set-Cookie",
|
||||
serialize("thirdweb_auth_token", "", {
|
||||
path: "/",
|
||||
expires: new Date(Date.now() + 5 * 1000),
|
||||
})
|
||||
);
|
||||
|
||||
return res.status(301).redirect(req.headers.referer as string);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
export default async function handler(req: Request, res: Response) {
|
||||
return res.status(200).json(req.user);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ThirdwebAuthUser } from "..";
|
||||
|
||||
export {};
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
namespace Express {
|
||||
export interface Request {
|
||||
user: ThirdwebAuthUser | null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
|
||||
import { Request } from "express";
|
||||
|
||||
export type ThirdwebAuthRoute = "login" | "user" | "logout";
|
||||
|
||||
export type ThirdwebAuthConfig = {
|
||||
privateKey: string;
|
||||
domain: string;
|
||||
authUrl?: string;
|
||||
};
|
||||
|
||||
export type ThirdwebAuthContext = {
|
||||
sdk: ThirdwebSDK;
|
||||
domain: string;
|
||||
};
|
||||
|
||||
export type ThirdwebAuthUser = {
|
||||
address: string;
|
||||
};
|
||||
|
||||
export type RequestWithUser = Request & {
|
||||
user: ThirdwebAuthUser | null;
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import loginHandler from "./routes/login";
|
||||
import logoutHandler from "./routes/logout";
|
||||
import userHandler from "./routes/user";
|
||||
import {
|
||||
ThirdwebAuthConfig,
|
||||
ThirdwebAuthContext,
|
||||
ThirdwebAuthRoute,
|
||||
ThirdwebAuthUser,
|
||||
} from "./types";
|
||||
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
|
||||
import { NextRequest } from "next/server";
|
||||
import {
|
||||
GetServerSidePropsContext,
|
||||
NextApiRequest,
|
||||
NextApiResponse,
|
||||
} from "next/types";
|
||||
|
||||
export * from "./types";
|
||||
|
||||
async function ThirdwebAuthRouter(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
ctx: ThirdwebAuthContext
|
||||
) {
|
||||
// Catch-all route must be named with [...thirdweb]
|
||||
const { thirdweb } = req.query;
|
||||
const action = thirdweb?.[0] as ThirdwebAuthRoute;
|
||||
|
||||
switch (action) {
|
||||
case "login":
|
||||
return await loginHandler(req, res, ctx);
|
||||
case "user":
|
||||
return await userHandler(req, res, ctx);
|
||||
case "logout":
|
||||
return await logoutHandler(req, res);
|
||||
default:
|
||||
return res.status(400).json({
|
||||
message: "Invalid route for authentication.",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function ThirdwebAuth(cfg: ThirdwebAuthConfig) {
|
||||
const ctx = {
|
||||
...cfg,
|
||||
sdk: ThirdwebSDK.fromPrivateKey(cfg.privateKey, "mainnet"),
|
||||
};
|
||||
|
||||
function ThirdwebAuthHandler(
|
||||
...args: [] | [NextApiRequest, NextApiResponse]
|
||||
) {
|
||||
if (args.length === 0) {
|
||||
return async (req: NextApiRequest, res: NextApiResponse) =>
|
||||
await ThirdwebAuthRouter(req, res, ctx);
|
||||
}
|
||||
|
||||
return ThirdwebAuthRouter(args[0], args[1], ctx);
|
||||
}
|
||||
|
||||
async function getUser(
|
||||
req: GetServerSidePropsContext["req"] | NextRequest | NextApiRequest
|
||||
) {
|
||||
const { sdk, domain } = ctx;
|
||||
let user: ThirdwebAuthUser | null = null;
|
||||
const token =
|
||||
typeof req.cookies.get === "function"
|
||||
? (req.cookies as any).get("thirdweb_auth_token")
|
||||
: (req.cookies as any).thirdweb_auth_token;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const address = await sdk.auth.authenticate(domain, token);
|
||||
user = { address };
|
||||
} catch {
|
||||
// No-op
|
||||
}
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
return { ThirdwebAuthHandler, getUser };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { ThirdwebAuthContext } from "../types";
|
||||
import { LoginPayload } from "@thirdweb-dev/sdk/dist/src/schema";
|
||||
import { serialize } from "cookie";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
function redirectWithError(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
error: string
|
||||
) {
|
||||
const encodedError = encodeURIComponent(error);
|
||||
const url = new URL(req.headers.referer as string);
|
||||
url.searchParams.set("error", encodedError);
|
||||
return res.redirect(url.toString());
|
||||
}
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
ctx: ThirdwebAuthContext
|
||||
) {
|
||||
if (req.method !== "GET") {
|
||||
return redirectWithError(req, res, "INVALID_METHOD");
|
||||
}
|
||||
|
||||
const { sdk, domain } = ctx;
|
||||
|
||||
// Get signed login payload from the frontend
|
||||
const payload = JSON.parse(atob(req.query.payload as string)) as LoginPayload;
|
||||
if (!payload) {
|
||||
redirectWithError(req, res, "MISSING_LOGIN_PAYLOAD");
|
||||
}
|
||||
|
||||
let token;
|
||||
try {
|
||||
// Generate an access token with the SDK using the signed payload
|
||||
token = await sdk.auth.generateAuthToken(domain, payload);
|
||||
} catch {
|
||||
return redirectWithError(req, res, "INVALID_LOGIN_PAYLOAD");
|
||||
}
|
||||
|
||||
// Securely set httpOnly cookie on request to prevent XSS on frontend
|
||||
// And set path to / to enable thirdweb_auth_token usage on all endpoints
|
||||
res.setHeader(
|
||||
"Set-Cookie",
|
||||
serialize("thirdweb_auth_token", token, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "strict",
|
||||
})
|
||||
);
|
||||
|
||||
return res.status(301).redirect(req.query.redirect as string);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { serialize } from "cookie";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method !== "GET") {
|
||||
return res.status(400).json({
|
||||
error: "Invalid method. Only GET supported.",
|
||||
});
|
||||
}
|
||||
|
||||
// Set the access token to 'none' and expire in 5 seconds
|
||||
res.setHeader(
|
||||
"Set-Cookie",
|
||||
serialize("thirdweb_auth_token", "", {
|
||||
path: "/",
|
||||
expires: new Date(Date.now() + 5 * 1000),
|
||||
})
|
||||
);
|
||||
|
||||
return res.status(301).redirect(req.headers.referer as string);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ThirdwebAuthContext } from "../types";
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
ctx: ThirdwebAuthContext
|
||||
) {
|
||||
const { sdk, domain } = ctx;
|
||||
let user = null;
|
||||
const token = req.cookies.thirdweb_auth_token;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const address = await sdk.auth.authenticate(domain, token);
|
||||
user = { address };
|
||||
} catch {
|
||||
// No-op
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(200).json(user);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { ThirdwebSDK } from "@thirdweb-dev/sdk";
|
||||
|
||||
export type ThirdwebAuthRoute = "login" | "logout" | "user";
|
||||
|
||||
export type ThirdwebAuthConfig = {
|
||||
privateKey: string;
|
||||
domain: string;
|
||||
};
|
||||
|
||||
export type ThirdwebAuthContext = {
|
||||
sdk: ThirdwebSDK;
|
||||
domain: string;
|
||||
};
|
||||
|
||||
export type ThirdwebAuthUser = {
|
||||
address: string;
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "@thirdweb-dev/tsconfig/base.json",
|
||||
"include": ["."],
|
||||
"exclude": ["dist", "build", "node_modules"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# folders
|
||||
dist/
|
||||
|
||||
# files
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ["thirdweb"],
|
||||
};
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021 Non-Fungible Labs, Inc
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,110 @@
|
||||
<p align="center">
|
||||
<br />
|
||||
<a href="https://thirdweb.com"><img src="https://github.com/thirdweb-dev/typescript-sdk/blob/main/logo.svg?raw=true" width="200" alt=""/></a>
|
||||
<br />
|
||||
</p>
|
||||
<h1 align="center">thirdweb CLI</h1>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/@thirdweb-dev/cli"><img src="https://img.shields.io/npm/v/@thirdweb-dev/cli?color=red&logo=npm" alt="npm version"/></a>
|
||||
<a href="https://discord.gg/thirdweb"><img alt="Join our Discord!" src="https://img.shields.io/discord/834227967404146718.svg?color=7289da&label=discord&logo=discord&style=flat"/></a>
|
||||
|
||||
</p>
|
||||
<p align="center"><strong>Publish and deploy smart contracts without dealing with private keys</strong></p>
|
||||
<br />
|
||||
|
||||
## Getting started
|
||||
|
||||
The thirdweb CLI is your one-stop-shop for publishing custom contracts for your team or the world to use. The CLI uploads all necessary data to decentralized storage and makes it available to deploy via the thirdweb sdk or thirdweb dashboard.
|
||||
|
||||
This brings all the capabilities of thirdweb to your own custom contracts.
|
||||
|
||||
## Deploying your contract
|
||||
|
||||
```shell
|
||||
npx thirdweb@latest deploy
|
||||
```
|
||||
|
||||
This command will:
|
||||
|
||||
- auto-detect any contracts in your project
|
||||
- compile your project
|
||||
- Upload ABIs to IPFS
|
||||
- Open the deploy flow in your thirdweb dashboard in a browser
|
||||
|
||||
From the thirdweb dashboard, you can review and deploy your contracts on any supported EVM chain.
|
||||
|
||||
Deploying contracts this way gives you access to:
|
||||
|
||||
- auto generated SDKs for react, node, python, go
|
||||
- dashboards to manage, monitor and interact with your contracts
|
||||
|
||||
## Releasing your contract
|
||||
|
||||
```shell
|
||||
npx thirdweb@latest release
|
||||
```
|
||||
|
||||
Creates an official release of your contract, along with:
|
||||
|
||||
- author attribution
|
||||
- contract information
|
||||
- instructions on how to use and what it's for
|
||||
- versioning
|
||||
- release notes
|
||||
|
||||
Creating releases this way gives you shareable URL to let others to deploy your contracts in one click. It lets you manage released versions and get attribution for deployed contracts. Contract releases are registered on-chain (Polygon) and IPFS, for free (gasless).
|
||||
|
||||
Deploying released contracts give deployers access to automatic SDKs to integrate into their app and dashboards to manage and monitor the deployed contracts.
|
||||
|
||||
## Detecting contract extensions
|
||||
|
||||
```shell
|
||||
npx thirdweb@latest detect
|
||||
```
|
||||
|
||||
As you're developing your contracts, you may want to implement [Contract Extensions](https://portal.thirdweb.com/thirdweb-deploy/contract-extensions) to unlock functionality on the SDKs (ie. nft minting with automatic upload to IPFS) and the dashboard (ie. generated UI to manage permissions). This command will show what extensions were detected on your contract, unlocking the corresponding functionality on the SDKs and dashboard.
|
||||
|
||||
---
|
||||
|
||||
## Global installation
|
||||
|
||||
We recommend using npx to always get the latest version. Alternatively, you can install the CLI as a global command on your machine:
|
||||
|
||||
```shell
|
||||
npm i -g @thirdweb-dev/cli
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Supported projects
|
||||
|
||||
To publish, you need to be in a directory that contains a project which the CLI is compatible
|
||||
with. The projects we support so far:
|
||||
|
||||
- hardhat
|
||||
- forge
|
||||
- truffle
|
||||
- solc
|
||||
|
||||
---
|
||||
|
||||
## Running the examples
|
||||
|
||||
Clone the repo and run this command after installing the CLI tool:
|
||||
|
||||
```bash
|
||||
$ cd examples/hardhat
|
||||
$ npx thirdweb@latest release
|
||||
```
|
||||
|
||||
## Local Development
|
||||
|
||||
The simplest way to work on the CLI locally is to:
|
||||
|
||||
1. Install the package locally
|
||||
2. Run the `build:watch` command to compile any changes in realtime
|
||||
|
||||
```bash
|
||||
$ npm install -g ./
|
||||
$ yarn run build:watch
|
||||
```
|
||||
@@ -0,0 +1,10 @@
|
||||
node_modules/
|
||||
.env
|
||||
coverage
|
||||
coverage.json
|
||||
typechain
|
||||
|
||||
#brownie files
|
||||
cache
|
||||
build
|
||||
artifacts
|
||||
@@ -0,0 +1,66 @@
|
||||
project_structure:
|
||||
build: build
|
||||
contracts: contracts
|
||||
interfaces: interfaces
|
||||
reports: reports
|
||||
scripts: scripts
|
||||
tests: tests
|
||||
|
||||
networks:
|
||||
default: development
|
||||
development:
|
||||
gas_limit: max
|
||||
gas_buffer: 1
|
||||
gas_price: 0
|
||||
max_fee: null
|
||||
priority_fee: null
|
||||
reverting_tx_gas_limit: max
|
||||
default_contract_owner: true
|
||||
cmd_settings: null
|
||||
live:
|
||||
gas_limit: auto
|
||||
gas_buffer: 1.1
|
||||
gas_price: auto
|
||||
max_fee: null
|
||||
priority_fee: null
|
||||
reverting_tx_gas_limit: false
|
||||
default_contract_owner: false
|
||||
|
||||
compiler:
|
||||
evm_version: null
|
||||
solc:
|
||||
version: null
|
||||
optimizer:
|
||||
enabled: true
|
||||
runs: 200
|
||||
remappings: null
|
||||
vyper:
|
||||
version: null
|
||||
|
||||
console:
|
||||
show_colors: true
|
||||
color_style: monokai
|
||||
auto_suggest: true
|
||||
completions: true
|
||||
editing_mode: emacs
|
||||
|
||||
reports:
|
||||
exclude_paths: null
|
||||
exclude_contracts: null
|
||||
only_include_project: true
|
||||
|
||||
hypothesis:
|
||||
deadline: null
|
||||
max_examples: 50
|
||||
report_multiple_bugs: False
|
||||
stateful_step_count: 10
|
||||
phases:
|
||||
explicit: true
|
||||
reuse: true
|
||||
generate: true
|
||||
target: true
|
||||
shrink: true
|
||||
|
||||
autofetch_sources: false
|
||||
dependencies: null
|
||||
dev_deployment_artifacts: false
|
||||
@@ -0,0 +1,12 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
contract ConstructorParams {
|
||||
bytes32 public immutable contractUri;
|
||||
uint256 contractId;
|
||||
|
||||
constructor(bytes32 uri, uint256 someId) {
|
||||
contractUri = uri;
|
||||
contractId = someId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
contract Greeter {
|
||||
constructor() {}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
node_modules/
|
||||
.env
|
||||
coverage
|
||||
coverage.json
|
||||
typechain
|
||||
yarn.lock
|
||||
|
||||
#forge files
|
||||
cache
|
||||
out
|
||||
artifacts
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
contract ConstructorParams {
|
||||
|
||||
struct Foo {
|
||||
uint256 aNumber;
|
||||
bytes32 aString;
|
||||
address[] anArray;
|
||||
}
|
||||
|
||||
bytes32 public immutable contractUri;
|
||||
uint256 contractId;
|
||||
bytes[] someCode;
|
||||
Foo public foo;
|
||||
|
||||
constructor(bytes32 uri, uint256 someId, bytes[] memory anArray, Foo memory aStruct) {
|
||||
contractUri = uri;
|
||||
contractId = someId;
|
||||
foo = aStruct;
|
||||
someCode = anArray;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Events is ERC20 {
|
||||
|
||||
event MyEvent(uint256 money);
|
||||
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Greeter is ERC20 {
|
||||
constructor() ERC20("MyToken", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract GreeterWithDifferentName is ERC20 {
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
|
||||
import "@thirdweb-dev/contracts/feature/LazyMintERC721.sol";
|
||||
import "@thirdweb-dev/contracts/feature/ContractMetadata.sol";
|
||||
import "@thirdweb-dev/contracts/feature/PermissionsEnumerable.sol";
|
||||
import "@thirdweb-dev/contracts/feature/Royalty.sol";
|
||||
import "@thirdweb-dev/contracts/feature/Multicall.sol";
|
||||
import "@thirdweb-dev/contracts/feature/Drop.sol";
|
||||
|
||||
contract SimpleDrop is ERC721, LazyMintERC721, Drop, ContractMetadata, PermissionsEnumerable, Royalty, Multicall {
|
||||
constructor() ERC721("MyToken", "MTK") {
|
||||
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
|
||||
}
|
||||
|
||||
function tokenURI(uint256 _tokenId) public view override(ERC721, LazyMintERC721) returns (string memory) {
|
||||
return LazyMintERC721.tokenURI(_tokenId);
|
||||
}
|
||||
|
||||
function collectPriceOnClaim(
|
||||
uint256 _quantityToClaim,
|
||||
address _currency,
|
||||
uint256 _pricePerToken
|
||||
) internal override {
|
||||
|
||||
}
|
||||
|
||||
/// @dev Transfers the NFTs being claimed.
|
||||
function transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed)
|
||||
internal
|
||||
override
|
||||
returns (uint256 startTokenId) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
function _canLazyMint() internal view override returns (bool) {
|
||||
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
|
||||
}
|
||||
|
||||
function _canSetContractURI() internal view override returns (bool) {
|
||||
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
|
||||
}
|
||||
|
||||
function _canSetRoyaltyInfo() internal view override returns (bool) {
|
||||
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
|
||||
}
|
||||
|
||||
function _canSetClaimConditions() internal view override returns (bool) {
|
||||
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
[default]
|
||||
remappings = [
|
||||
'@openzeppelin/=node_modules/@openzeppelin/',
|
||||
'@thirdweb-dev/=node_modules/@thirdweb-dev/',
|
||||
]
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "foundry-project",
|
||||
"private": true,
|
||||
"devDependencies": {},
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": "^4.5.0",
|
||||
"@thirdweb-dev/contracts": "^2.3.14"
|
||||
},
|
||||
"scripts": {}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
node_modules/
|
||||
.env
|
||||
coverage
|
||||
coverage.json
|
||||
typechain
|
||||
yarn.lock
|
||||
|
||||
#Hardhat files
|
||||
cache
|
||||
artifacts
|
||||
@@ -0,0 +1,15 @@
|
||||
# Basic Sample Hardhat Project
|
||||
|
||||
This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts.
|
||||
|
||||
Try running some of the following tasks:
|
||||
|
||||
```shell
|
||||
npx hardhat accounts
|
||||
npx hardhat compile
|
||||
npx hardhat clean
|
||||
npx hardhat test
|
||||
npx hardhat node
|
||||
node scripts/sample-script.js
|
||||
npx hardhat help
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
contract ConstructorParams {
|
||||
|
||||
struct Foo {
|
||||
uint256 aNumber;
|
||||
bytes32 aString;
|
||||
address[] anArray;
|
||||
}
|
||||
|
||||
bytes32 public immutable contractUri;
|
||||
uint256 contractId;
|
||||
bytes[] someCode;
|
||||
Foo public foo;
|
||||
|
||||
constructor(bytes32 uri, uint256 someId, bytes[] memory anArray, Foo memory aStruct) {
|
||||
contractUri = uri;
|
||||
contractId = someId;
|
||||
foo = aStruct;
|
||||
someCode = anArray;
|
||||
}
|
||||
|
||||
function updateStruct(Foo memory aStruct) public {
|
||||
foo = aStruct;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Events is ERC20 {
|
||||
|
||||
event MyEvent(uint256 money);
|
||||
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Greeter is ERC20 {
|
||||
|
||||
constructor() ERC20("MyToken", "MTK") {
|
||||
_mint(msg.sender, 1000000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract GreeterWithDifferentName is ERC20 {
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
|
||||
import "@thirdweb-dev/contracts/feature/PrimarySale.sol";
|
||||
|
||||
contract NFT is ERC721, PrimarySale {
|
||||
constructor() ERC721("NFT", "NFT") {
|
||||
|
||||
}
|
||||
|
||||
/// @dev Determine what wallet can update claim conditions
|
||||
function _canSetPrimarySaleRecipient() internal pure override returns (bool) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
require("@nomiclabs/hardhat-waffle");
|
||||
|
||||
// This is a sample Hardhat task. To learn how to create your own go to
|
||||
// https://hardhat.org/guides/create-task.html
|
||||
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
|
||||
const accounts = await hre.ethers.getSigners();
|
||||
|
||||
for (const account of accounts) {
|
||||
console.log(account.address);
|
||||
}
|
||||
});
|
||||
|
||||
// You need to export an object to set up your config
|
||||
// Go to https://hardhat.org/config/ to learn more
|
||||
|
||||
/**
|
||||
* @type import('hardhat/config').HardhatUserConfig
|
||||
*/
|
||||
module.exports = {
|
||||
solidity: {
|
||||
version: "0.8.13",
|
||||
settings: {
|
||||
optimizer: {
|
||||
enabled: true,
|
||||
runs: 200,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
+26831
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "hardhat-project",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@nomiclabs/hardhat-ethers": "^2.0.5",
|
||||
"@nomiclabs/hardhat-waffle": "^2.0.3",
|
||||
"chai": "^4.3.6",
|
||||
"ethereum-waffle": "^3.4.4",
|
||||
"ethers": "^5.6.2",
|
||||
"hardhat": "^2.9.9",
|
||||
"typescript": "^4.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": "^4.7.1",
|
||||
"@thirdweb-dev/contracts": "^2.3.9"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// We require the Hardhat Runtime Environment explicitly here. This is optional
|
||||
// but useful for running the script in a standalone fashion through `node <script>`.
|
||||
//
|
||||
// When running the script with `npx hardhat run <script>` you'll find the Hardhat
|
||||
// Runtime Environment's members available in the global scope.
|
||||
const hre = require("hardhat");
|
||||
|
||||
async function main() {
|
||||
// Hardhat always runs the compile task when running scripts with its command
|
||||
// line interface.
|
||||
//
|
||||
// If this script is run directly using `node` you may want to call compile
|
||||
// manually to make sure everything is compiled
|
||||
// await hre.run('compile');
|
||||
|
||||
// We get the contract to deploy
|
||||
const Greeter = await hre.ethers.getContractFactory("Greeter");
|
||||
const greeter = await Greeter.deploy("Hello, Hardhat!");
|
||||
|
||||
await greeter.deployed();
|
||||
|
||||
console.log("Greeter deployed to:", greeter.address);
|
||||
}
|
||||
|
||||
// We recommend this pattern to be able to use async/await everywhere
|
||||
// and properly handle errors.
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
node_modules/
|
||||
.env
|
||||
coverage
|
||||
coverage.json
|
||||
typechain
|
||||
yarn.lock
|
||||
|
||||
# builder stuff
|
||||
cache
|
||||
artifacts
|
||||
build
|
||||
out
|
||||
@@ -0,0 +1,15 @@
|
||||
# Basic Sample Hardhat Project
|
||||
|
||||
This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts.
|
||||
|
||||
Try running some of the following tasks:
|
||||
|
||||
```shell
|
||||
npx hardhat accounts
|
||||
npx hardhat compile
|
||||
npx hardhat clean
|
||||
npx hardhat test
|
||||
npx hardhat node
|
||||
node scripts/sample-script.js
|
||||
npx hardhat help
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
project_structure:
|
||||
build: build
|
||||
contracts: contracts
|
||||
interfaces: interfaces
|
||||
reports: reports
|
||||
scripts: scripts
|
||||
tests: tests
|
||||
|
||||
networks:
|
||||
default: development
|
||||
development:
|
||||
gas_limit: max
|
||||
gas_buffer: 1
|
||||
gas_price: 0
|
||||
max_fee: null
|
||||
priority_fee: null
|
||||
reverting_tx_gas_limit: max
|
||||
default_contract_owner: true
|
||||
cmd_settings: null
|
||||
live:
|
||||
gas_limit: auto
|
||||
gas_buffer: 1.1
|
||||
gas_price: auto
|
||||
max_fee: null
|
||||
priority_fee: null
|
||||
reverting_tx_gas_limit: false
|
||||
default_contract_owner: false
|
||||
|
||||
compiler:
|
||||
evm_version: null
|
||||
solc:
|
||||
version: null
|
||||
optimizer:
|
||||
enabled: true
|
||||
runs: 200
|
||||
remappings: null
|
||||
vyper:
|
||||
version: null
|
||||
|
||||
console:
|
||||
show_colors: true
|
||||
color_style: monokai
|
||||
auto_suggest: true
|
||||
completions: true
|
||||
editing_mode: emacs
|
||||
|
||||
reports:
|
||||
exclude_paths: null
|
||||
exclude_contracts: null
|
||||
only_include_project: true
|
||||
|
||||
hypothesis:
|
||||
deadline: null
|
||||
max_examples: 50
|
||||
report_multiple_bugs: False
|
||||
stateful_step_count: 10
|
||||
phases:
|
||||
explicit: true
|
||||
reuse: true
|
||||
generate: true
|
||||
target: true
|
||||
shrink: true
|
||||
|
||||
autofetch_sources: false
|
||||
dependencies: null
|
||||
dev_deployment_artifacts: false
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@thirdweb-dev/contracts/ThirdwebContract.sol";
|
||||
|
||||
contract ConstructorParams is ThirdwebContract {
|
||||
bytes32 public immutable contractUri;
|
||||
uint256 contractId;
|
||||
|
||||
constructor(bytes32 uri, uint256 someId) {
|
||||
contractUri = uri;
|
||||
contractId = someId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Events is ERC20 {
|
||||
|
||||
event MyEvent(uint256 money);
|
||||
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
import "@thirdweb-dev/contracts/ThirdwebContract.sol";
|
||||
|
||||
contract Greeter is ERC20, ThirdwebContract {
|
||||
constructor() ERC20("MyToken", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract GreeterWithDifferentName is ERC20 {
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
[default]
|
||||
auto_detect_solc = true
|
||||
block_base_fee_per_gas = 0
|
||||
block_coinbase = '0x0000000000000000000000000000000000000000'
|
||||
block_difficulty = 0
|
||||
block_number = 0
|
||||
block_timestamp = 0
|
||||
bytecode_hash = 'ipfs'
|
||||
cache = true
|
||||
cache_path = 'cache'
|
||||
evm_version = 'london'
|
||||
extra_output = []
|
||||
extra_output_files = []
|
||||
ffi = false
|
||||
force = false
|
||||
fuzz_max_global_rejects = 65536
|
||||
fuzz_max_local_rejects = 1024
|
||||
fuzz_runs = 256
|
||||
gas_limit = 9223372036854775807
|
||||
gas_price = 0
|
||||
gas_reports = ['*']
|
||||
ignored_error_codes = [1878]
|
||||
initial_balance = '0xffffffffffffffffffffffff'
|
||||
libraries = []
|
||||
libs = ['node_modules']
|
||||
memory_limit = 33554432
|
||||
names = false
|
||||
no_storage_caching = false
|
||||
offline = false
|
||||
optimizer = true
|
||||
optimizer_runs = 200
|
||||
out = 'out'
|
||||
remappings = [
|
||||
'@openzeppelin/=node_modules/@openzeppelin/',
|
||||
'@thirdweb-dev/=node_modules/@thirdweb-dev/',
|
||||
'lib/=node_modules/@thirdweb-dev/contracts/contracts/lib/',
|
||||
]
|
||||
sender = '0x00a329c0648769a73afac7f9381e08fb43dbea72'
|
||||
sizes = false
|
||||
sparse_mode = false
|
||||
src = 'contracts'
|
||||
test = 'test'
|
||||
tx_origin = '0x00a329c0648769a73afac7f9381e08fb43dbea72'
|
||||
verbosity = 0
|
||||
via_ir = false
|
||||
|
||||
[default.rpc_storage_caching]
|
||||
chains = 'all'
|
||||
endpoints = 'all'
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
require("@nomiclabs/hardhat-waffle");
|
||||
|
||||
// This is a sample Hardhat task. To learn how to create your own go to
|
||||
// https://hardhat.org/guides/create-task.html
|
||||
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
|
||||
const accounts = await hre.ethers.getSigners();
|
||||
|
||||
for (const account of accounts) {
|
||||
console.log(account.address);
|
||||
}
|
||||
});
|
||||
|
||||
// You need to export an object to set up your config
|
||||
// Go to https://hardhat.org/config/ to learn more
|
||||
|
||||
/**
|
||||
* @type import('hardhat/config').HardhatUserConfig
|
||||
*/
|
||||
module.exports = {
|
||||
solidity: "0.8.4",
|
||||
};
|
||||
+27000
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "multi-project",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
"@nomiclabs/hardhat-ethers": "^2.0.5",
|
||||
"@nomiclabs/hardhat-waffle": "^2.0.3",
|
||||
"chai": "^4.3.6",
|
||||
"ethereum-waffle": "^3.4.4",
|
||||
"ethers": "^5.6.2",
|
||||
"hardhat": "^2.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": "^4.7.1",
|
||||
"@thirdweb-dev/contracts": "^2.3.5"
|
||||
},
|
||||
"scripts": {
|
||||
"compile": "hardhat compile"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// We require the Hardhat Runtime Environment explicitly here. This is optional
|
||||
// but useful for running the script in a standalone fashion through `node <script>`.
|
||||
//
|
||||
// When running the script with `npx hardhat run <script>` you'll find the Hardhat
|
||||
// Runtime Environment's members available in the global scope.
|
||||
const hre = require("hardhat");
|
||||
|
||||
async function main() {
|
||||
// Hardhat always runs the compile task when running scripts with its command
|
||||
// line interface.
|
||||
//
|
||||
// If this script is run directly using `node` you may want to call compile
|
||||
// manually to make sure everything is compiled
|
||||
// await hre.run('compile');
|
||||
|
||||
// We get the contract to deploy
|
||||
const Greeter = await hre.ethers.getContractFactory("Greeter");
|
||||
const greeter = await Greeter.deploy("Hello, Hardhat!");
|
||||
|
||||
await greeter.deployed();
|
||||
|
||||
console.log("Greeter deployed to:", greeter.address);
|
||||
}
|
||||
|
||||
// We recommend this pattern to be able to use async/await everywhere
|
||||
// and properly handle errors.
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Use this file to configure your truffle project. It's seeded with some
|
||||
* common settings for different networks and features like migrations,
|
||||
* compilation and testing. Uncomment the ones you need or modify
|
||||
* them to suit your project as necessary.
|
||||
*
|
||||
* More information about configuration can be found at:
|
||||
*
|
||||
* https://trufflesuite.com/docs/truffle/reference/configuration
|
||||
*
|
||||
* To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
|
||||
* to sign your transactions before they're sent to a remote public node. Infura accounts
|
||||
* are available for free at: infura.io/register.
|
||||
*
|
||||
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
|
||||
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
|
||||
* phrase from a file you've .gitignored so it doesn't accidentally become public.
|
||||
*
|
||||
*/
|
||||
|
||||
// const HDWalletProvider = require('@truffle/hdwallet-provider');
|
||||
//
|
||||
// const fs = require('fs');
|
||||
// const mnemonic = fs.readFileSync(".secret").toString().trim();
|
||||
|
||||
module.exports = {
|
||||
// contracts_build_directory: "./build-test",
|
||||
// contracts_directory: "./contracts2",
|
||||
/**
|
||||
* Networks define how you connect to your ethereum client and let you set the
|
||||
* defaults web3 uses to send transactions. If you don't specify one truffle
|
||||
* will spin up a development blockchain for you on port 9545 when you
|
||||
* run `develop` or `test`. You can ask a truffle command to use a specific
|
||||
* network from the command line, e.g
|
||||
*
|
||||
* $ truffle test --network <network-name>
|
||||
*/
|
||||
|
||||
networks: {
|
||||
// Useful for testing. The `development` name is special - truffle uses it by default
|
||||
// if it's defined here and no other network is specified at the command line.
|
||||
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
|
||||
// tab if you use this network and you must also set the `host`, `port` and `network_id`
|
||||
// options below to some value.
|
||||
//
|
||||
// development: {
|
||||
// host: "127.0.0.1", // Localhost (default: none)
|
||||
// port: 8545, // Standard Ethereum port (default: none)
|
||||
// network_id: "*", // Any network (default: none)
|
||||
// },
|
||||
// Another network with more advanced options...
|
||||
// advanced: {
|
||||
// port: 8777, // Custom port
|
||||
// network_id: 1342, // Custom network
|
||||
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
|
||||
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
|
||||
// from: <address>, // Account to send txs from (default: accounts[0])
|
||||
// websocket: true // Enable EventEmitter interface for web3 (default: false)
|
||||
// },
|
||||
// Useful for deploying to a public network.
|
||||
// NB: It's important to wrap the provider as a function.
|
||||
// ropsten: {
|
||||
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
|
||||
// network_id: 3, // Ropsten's id
|
||||
// gas: 5500000, // Ropsten has a lower block limit than mainnet
|
||||
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
|
||||
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
|
||||
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
|
||||
// },
|
||||
// Useful for private networks
|
||||
// private: {
|
||||
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
|
||||
// network_id: 2111, // This network is yours, in the cloud.
|
||||
// production: true // Treats this network as if it was a public net. (default: false)
|
||||
// }
|
||||
},
|
||||
|
||||
// Set default mocha options here, use special reporters etc.
|
||||
mocha: {
|
||||
// timeout: 100000
|
||||
},
|
||||
|
||||
// Configure your compilers
|
||||
compilers: {
|
||||
solc: {
|
||||
version: "0.8.13", // Fetch exact version from solc-bin (default: truffle's version)
|
||||
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
|
||||
// settings: { // See the solidity docs for advice about optimization and evmVersion
|
||||
// optimizer: {
|
||||
// enabled: false,
|
||||
// runs: 200
|
||||
// },
|
||||
// evmVersion: "byzantium"
|
||||
// }
|
||||
},
|
||||
},
|
||||
|
||||
// Truffle DB is currently disabled by default; to enable it, change enabled:
|
||||
// false to enabled: true. The default storage location can also be
|
||||
// overridden by specifying the adapter settings, as shown in the commented code below.
|
||||
//
|
||||
// NOTE: It is not possible to migrate your contracts to truffle DB and you should
|
||||
// make a backup of your artifacts to a safe location before enabling this feature.
|
||||
//
|
||||
// After you backed up your artifacts you can utilize db by running migrate as follows:
|
||||
// $ truffle migrate --reset --compile-all
|
||||
//
|
||||
// db: {
|
||||
// enabled: false,
|
||||
// host: "127.0.0.1",
|
||||
// adapter: {
|
||||
// name: "sqlite",
|
||||
// settings: {
|
||||
// directory: ".db"
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
node_modules/
|
||||
.env
|
||||
coverage
|
||||
coverage.json
|
||||
typechain
|
||||
yarn.lock
|
||||
|
||||
#forge files
|
||||
cache
|
||||
artifacts
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@thirdweb-dev/contracts/ThirdwebContract.sol";
|
||||
|
||||
contract ConstructorParams is ThirdwebContract {
|
||||
bytes32 public immutable contractUri;
|
||||
uint256 contractId;
|
||||
|
||||
constructor(bytes32 uri, uint256 someId) {
|
||||
contractUri = uri;
|
||||
contractId = someId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Events is ERC20 {
|
||||
|
||||
event MyEvent(uint256 money);
|
||||
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
import "@thirdweb-dev/contracts/ThirdwebContract.sol";
|
||||
|
||||
contract Greeter is ERC20, ThirdwebContract {
|
||||
constructor() ERC20("MyToken", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract GreeterWithDifferentName is ERC20 {
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "foundry-project",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "foundry-project",
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": "^4.7.1",
|
||||
"@thirdweb-dev/contracts": "^2.3.8"
|
||||
}
|
||||
},
|
||||
"node_modules/@openzeppelin/contracts": {
|
||||
"version": "4.7.1",
|
||||
"resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.7.1.tgz",
|
||||
"integrity": "sha512-UXmAjKARsXORHlHZu5GCD7ZbRKm6nU8UHnbuT/QJJa2JEOEcbvV/X8w/sUk62Sl9VZuuljM1akrZLyAtzUgsxw=="
|
||||
},
|
||||
"node_modules/@thirdweb-dev/contracts": {
|
||||
"version": "2.3.8",
|
||||
"resolved": "https://registry.npmjs.org/@thirdweb-dev/contracts/-/contracts-2.3.8.tgz",
|
||||
"integrity": "sha512-cSVwIzPSYaS8gFlkq4r+G9UyVwr/62uE+p6SzrZFXYCbeCJwJTml3VnrVEptJ7g8RukL4Lh6uwQ6IPtgMTY4cQ=="
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": {
|
||||
"version": "4.7.1",
|
||||
"resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.7.1.tgz",
|
||||
"integrity": "sha512-UXmAjKARsXORHlHZu5GCD7ZbRKm6nU8UHnbuT/QJJa2JEOEcbvV/X8w/sUk62Sl9VZuuljM1akrZLyAtzUgsxw=="
|
||||
},
|
||||
"@thirdweb-dev/contracts": {
|
||||
"version": "2.3.8",
|
||||
"resolved": "https://registry.npmjs.org/@thirdweb-dev/contracts/-/contracts-2.3.8.tgz",
|
||||
"integrity": "sha512-cSVwIzPSYaS8gFlkq4r+G9UyVwr/62uE+p6SzrZFXYCbeCJwJTml3VnrVEptJ7g8RukL4Lh6uwQ6IPtgMTY4cQ=="
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "foundry-project",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": "^4.7.1",
|
||||
"@thirdweb-dev/contracts": "^2.3.8"
|
||||
},
|
||||
"scripts": {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
node_modules/
|
||||
.env
|
||||
coverage
|
||||
coverage.json
|
||||
typechain
|
||||
yarn.lock
|
||||
|
||||
#truffle files
|
||||
cache
|
||||
build
|
||||
migrations
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@thirdweb-dev/contracts/ThirdwebContract.sol";
|
||||
|
||||
contract ConstructorParams is ThirdwebContract {
|
||||
bytes32 public immutable contractUri;
|
||||
uint256 contractId;
|
||||
|
||||
constructor(bytes32 uri, uint256 someId) {
|
||||
contractUri = uri;
|
||||
contractId = someId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract Events is ERC20 {
|
||||
|
||||
event MyEvent(uint256 money);
|
||||
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
import "@thirdweb-dev/contracts/ThirdwebContract.sol";
|
||||
|
||||
contract Greeter is ERC20, ThirdwebContract {
|
||||
constructor() ERC20("MyToken", "MTK") {}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.4;
|
||||
|
||||
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
|
||||
|
||||
contract GreeterWithDifferentName is ERC20 {
|
||||
constructor() ERC20("MyToken2", "MTK") {}
|
||||
}
|
||||
+18006
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "truffle-project",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@openzeppelin/contracts": "^4.7.1",
|
||||
"@thirdweb-dev/contracts": "^2.3.8",
|
||||
"truffle": "^5.5.18"
|
||||
},
|
||||
"scripts": {}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Use this file to configure your truffle project. It's seeded with some
|
||||
* common settings for different networks and features like migrations,
|
||||
* compilation and testing. Uncomment the ones you need or modify
|
||||
* them to suit your project as necessary.
|
||||
*
|
||||
* More information about configuration can be found at:
|
||||
*
|
||||
* https://trufflesuite.com/docs/truffle/reference/configuration
|
||||
*
|
||||
* To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
|
||||
* to sign your transactions before they're sent to a remote public node. Infura accounts
|
||||
* are available for free at: infura.io/register.
|
||||
*
|
||||
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
|
||||
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
|
||||
* phrase from a file you've .gitignored so it doesn't accidentally become public.
|
||||
*
|
||||
*/
|
||||
|
||||
// const HDWalletProvider = require('@truffle/hdwallet-provider');
|
||||
//
|
||||
// const fs = require('fs');
|
||||
// const mnemonic = fs.readFileSync(".secret").toString().trim();
|
||||
|
||||
module.exports = {
|
||||
// contracts_build_directory: "./build-test",
|
||||
// contracts_directory: "./contracts2",
|
||||
/**
|
||||
* Networks define how you connect to your ethereum client and let you set the
|
||||
* defaults web3 uses to send transactions. If you don't specify one truffle
|
||||
* will spin up a development blockchain for you on port 9545 when you
|
||||
* run `develop` or `test`. You can ask a truffle command to use a specific
|
||||
* network from the command line, e.g
|
||||
*
|
||||
* $ truffle test --network <network-name>
|
||||
*/
|
||||
|
||||
networks: {
|
||||
// Useful for testing. The `development` name is special - truffle uses it by default
|
||||
// if it's defined here and no other network is specified at the command line.
|
||||
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
|
||||
// tab if you use this network and you must also set the `host`, `port` and `network_id`
|
||||
// options below to some value.
|
||||
//
|
||||
// development: {
|
||||
// host: "127.0.0.1", // Localhost (default: none)
|
||||
// port: 8545, // Standard Ethereum port (default: none)
|
||||
// network_id: "*", // Any network (default: none)
|
||||
// },
|
||||
// Another network with more advanced options...
|
||||
// advanced: {
|
||||
// port: 8777, // Custom port
|
||||
// network_id: 1342, // Custom network
|
||||
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
|
||||
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
|
||||
// from: <address>, // Account to send txs from (default: accounts[0])
|
||||
// websocket: true // Enable EventEmitter interface for web3 (default: false)
|
||||
// },
|
||||
// Useful for deploying to a public network.
|
||||
// NB: It's important to wrap the provider as a function.
|
||||
// ropsten: {
|
||||
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
|
||||
// network_id: 3, // Ropsten's id
|
||||
// gas: 5500000, // Ropsten has a lower block limit than mainnet
|
||||
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
|
||||
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
|
||||
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
|
||||
// },
|
||||
// Useful for private networks
|
||||
// private: {
|
||||
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
|
||||
// network_id: 2111, // This network is yours, in the cloud.
|
||||
// production: true // Treats this network as if it was a public net. (default: false)
|
||||
// }
|
||||
},
|
||||
|
||||
// Set default mocha options here, use special reporters etc.
|
||||
mocha: {
|
||||
// timeout: 100000
|
||||
},
|
||||
|
||||
// Configure your compilers
|
||||
compilers: {
|
||||
solc: {
|
||||
version: "0.8.13", // Fetch exact version from solc-bin (default: truffle's version)
|
||||
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
|
||||
// settings: { // See the solidity docs for advice about optimization and evmVersion
|
||||
// optimizer: {
|
||||
// enabled: false,
|
||||
// runs: 200
|
||||
// },
|
||||
// evmVersion: "byzantium"
|
||||
// }
|
||||
},
|
||||
},
|
||||
|
||||
// Truffle DB is currently disabled by default; to enable it, change enabled:
|
||||
// false to enabled: true. The default storage location can also be
|
||||
// overridden by specifying the adapter settings, as shown in the commented code below.
|
||||
//
|
||||
// NOTE: It is not possible to migrate your contracts to truffle DB and you should
|
||||
// make a backup of your artifacts to a safe location before enabling this feature.
|
||||
//
|
||||
// After you backed up your artifacts you can utilize db by running migrate as follows:
|
||||
// $ truffle migrate --reset --compile-all
|
||||
//
|
||||
// db: {
|
||||
// enabled: false,
|
||||
// host: "127.0.0.1",
|
||||
// adapter: {
|
||||
// name: "sqlite",
|
||||
// settings: {
|
||||
// directory: ".db"
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"name": "thirdweb",
|
||||
"main": "dist/cli/index.js",
|
||||
"version": "0.6.15",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com:thirdweb-dev/js.git",
|
||||
"directory": "packages/cli"
|
||||
},
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=14.0.0 <19"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@trivago/prettier-plugin-sort-imports": "^3.2.0",
|
||||
"@types/async-retry": "1.3.0",
|
||||
"@types/cross-spawn": "^6.0.2",
|
||||
"@types/inquirer": "^8.2.1",
|
||||
"@types/node": "^18.0.0",
|
||||
"@types/prompts": "^2.0.14",
|
||||
"@types/rimraf": "^3.0.0",
|
||||
"@types/tar": "^6.1.2",
|
||||
"@types/update-notifier": "^5.1.0",
|
||||
"@types/validate-npm-package-name": "^4.0.0",
|
||||
"hardhat": "^2.9.3",
|
||||
"prettier": "^2.6.2",
|
||||
"ts-node": "^10.7.0",
|
||||
"tsc": "^2.0.4",
|
||||
"tsup": "^6.2.3",
|
||||
"typescript": "^4.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@thirdweb-dev/sdk": "*",
|
||||
"@web-std/file": "^3.0.2",
|
||||
"async-retry": "^1.3.3",
|
||||
"cbor": "^8.1.0",
|
||||
"commander": "^9.1.0",
|
||||
"cpy": "^9.0.1",
|
||||
"enquirer": "^2.3.6",
|
||||
"ethers": "^5.6.9",
|
||||
"form-data": "^4.0.0",
|
||||
"got": "11.8.5",
|
||||
"inquirer": "^8.2.3",
|
||||
"ipfs-unixfs": "^6.0.7",
|
||||
"ipld-dag-pb": "^0.22.3",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"multihashes": "^4.0.3",
|
||||
"open": "^8.4.0",
|
||||
"prompts": "^2.4.2",
|
||||
"rimraf": "^3.0.2",
|
||||
"solc": "0.8.13",
|
||||
"tar": "^6.1.11",
|
||||
"tslog": "^3.3.3",
|
||||
"update-check": "^1.5.4",
|
||||
"update-notifier": "^6.0.2",
|
||||
"validate-npm-package-name": "^4.0.0",
|
||||
"yaml": "^2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"thirdweb": "./dist/cli/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"prettier": "prettier --write 'src/**/*'",
|
||||
"clean": "rm -rf dist/",
|
||||
"cli": "node -r ts-node/register src/cli/index.ts",
|
||||
"build": "yarn clean && tsc --noEmit && tsup --env.NODE_ENV production --minify --format cjs --external hardhat --dts-resolve",
|
||||
"build:watch": "yarn run build --watch",
|
||||
"prepublishOnly": "yarn build",
|
||||
"generate-thirdweb-package": "node scripts/generate-thirdweb-package.js"
|
||||
},
|
||||
"files": [
|
||||
"src/",
|
||||
"dist/"
|
||||
],
|
||||
"tsup": {
|
||||
"entry": [
|
||||
"src/cli/index.ts",
|
||||
"src/helpers/hardhat-config-extractor.ts"
|
||||
],
|
||||
"splitting": false,
|
||||
"sourcemap": true,
|
||||
"clean": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const fs = require("fs");
|
||||
|
||||
const existingPackageJson = JSON.parse(fs.readFileSync("package.json", "utf8"));
|
||||
|
||||
const newPackageJson = { ...existingPackageJson, name: "thirdweb" };
|
||||
|
||||
fs.writeFileSync("package.json", JSON.stringify(newPackageJson, null, 2));
|
||||
|
||||
fs.writeFileSync(
|
||||
"README.md",
|
||||
`# thirdweb cli
|
||||
|
||||
This is a proxied package of the \`@thirdweb-dev/cli\` for convenient usage with \`npx thirdweb\`.
|
||||
|
||||
You can find the actual package [here](https://www.npmjs.com/package/@thirdweb-dev/cli).
|
||||
`
|
||||
);
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env node
|
||||
import { installGithubAction } from "../common/ci-installer";
|
||||
import { detectExtensions } from "../common/feature-detector";
|
||||
import { processProject } from "../common/processor";
|
||||
import { cliVersion, pkg } from "../constants/urls";
|
||||
import { info, logger } from "../core/helpers/logger";
|
||||
import { twCreate } from "../create/command";
|
||||
import generateDashboardUrl from "../helpers/generate-dashboard-url";
|
||||
import chalk from "chalk";
|
||||
import { Command } from "commander";
|
||||
import open from "open";
|
||||
import updateNotifier from "update-notifier";
|
||||
|
||||
const main = async () => {
|
||||
const program = new Command();
|
||||
|
||||
//yes this has to look like this, eliminates whitespace
|
||||
console.info(`
|
||||
$$\\ $$\\ $$\\ $$\\ $$\\
|
||||
$$ | $$ | \\__| $$ | $$ |
|
||||
$$$$$$\\ $$$$$$$\\ $$\\ $$$$$$\\ $$$$$$$ |$$\\ $$\\ $$\\ $$$$$$\\ $$$$$$$\\
|
||||
\\_$$ _| $$ __$$\\ $$ |$$ __$$\\ $$ __$$ |$$ | $$ | $$ |$$ __$$\\ $$ __$$\\
|
||||
$$ | $$ | $$ |$$ |$$ | \\__|$$ / $$ |$$ | $$ | $$ |$$$$$$$$ |$$ | $$ |
|
||||
$$ |$$\\ $$ | $$ |$$ |$$ | $$ | $$ |$$ | $$ | $$ |$$ ____|$$ | $$ |
|
||||
\\$$$$ |$$ | $$ |$$ |$$ | \\$$$$$$$ |\\$$$$$\\$$$$ |\\$$$$$$$\\ $$$$$$$ |
|
||||
\\____/ \\__| \\__|\\__|\\__| \\_______| \\_____\\____/ \\_______|\\_______/ `);
|
||||
console.info(`\n 💎 thirdweb-cli v${cliVersion} 💎\n`);
|
||||
updateNotifier({
|
||||
pkg,
|
||||
shouldNotifyInNpmScript: true,
|
||||
//check every time while we're still building the CLI
|
||||
updateCheckInterval: 0,
|
||||
}).notify();
|
||||
|
||||
program
|
||||
.name("thirdweb-cli")
|
||||
.description("Official thirdweb command line interface")
|
||||
.version(cliVersion, "-v, --version", "output the current version");
|
||||
|
||||
program
|
||||
.command("detect")
|
||||
.description(
|
||||
"Compile contracts and detect implemented thirdweb contract extensions",
|
||||
)
|
||||
.option("-p, --path <project-path>", "path to project", ".")
|
||||
.option("-d, --debug", "show debug logs")
|
||||
.option("-a, --all", "run detection on all contracts")
|
||||
.action(async (options) => {
|
||||
await detectExtensions(options);
|
||||
});
|
||||
|
||||
program
|
||||
.command("publish")
|
||||
.description("[Deprecated] use 'release' instead.")
|
||||
.option("-p, --path <project-path>", "path to project", ".")
|
||||
.option("--dry-run", "dry run (skip actually publishing)")
|
||||
.option("-d, --debug", "show debug logs")
|
||||
.option("--ci", "Continuous Integration mode")
|
||||
.action(async (options) => {
|
||||
logger.warn(
|
||||
"'publish' is deprecated adn will be removed in a future update. Please use 'release' instead.",
|
||||
);
|
||||
const url = await processProject(options, "release");
|
||||
info(`Open this link to release your contracts:`);
|
||||
logger.info(chalk.blueBright(url.toString()));
|
||||
open(url.toString());
|
||||
});
|
||||
|
||||
program
|
||||
.command("release")
|
||||
.description(
|
||||
"Release contracts, making them available for others to deploy and unlocking SDKs, Dashboards and Analytics.",
|
||||
)
|
||||
.option("-p, --path <project-path>", "path to project", ".")
|
||||
.option("--dry-run", "dry run (skip actually publishing)")
|
||||
.option("-d, --debug", "show debug logs")
|
||||
.option("--ci", "Continuous Integration mode")
|
||||
.action(async (options) => {
|
||||
const url = await processProject(options, "release");
|
||||
info(`Open this link to release your contracts:`);
|
||||
logger.info(chalk.blueBright(url.toString()));
|
||||
open(url.toString());
|
||||
});
|
||||
|
||||
program
|
||||
.command("deploy")
|
||||
.description(
|
||||
"Deploy contracts through your thirdweb dashboard, without dealing with private keys.",
|
||||
)
|
||||
.option("-p, --path <project-path>", "path to project", ".")
|
||||
.option("--dry-run", "dry run (skip actually publishing)")
|
||||
.option("-d, --debug", "show debug logs")
|
||||
.option("--ci", "Continuous Integration mode")
|
||||
.option(
|
||||
"-n, --name [name]",
|
||||
"Name of the pre-built or released contract (such as nft-drop)",
|
||||
)
|
||||
.option(
|
||||
"-cv, --contract-version [version]",
|
||||
"Version of the released contract",
|
||||
)
|
||||
.action(async (options) => {
|
||||
if (options.name) {
|
||||
const url = generateDashboardUrl(options.name, options.contractVersion);
|
||||
|
||||
if (!url) {
|
||||
logger.error(
|
||||
chalk.red(
|
||||
`Could not find a contract named ${options.name} ${
|
||||
options.contractVersion || ""
|
||||
}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
info(`Open this link to deploy your contract:`);
|
||||
logger.info(chalk.blueBright(url));
|
||||
open(url.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const url = await processProject(options, "deploy");
|
||||
info(`Open this link to deploy your contracts:`);
|
||||
logger.info(chalk.blueBright(url.toString()));
|
||||
open(url.toString());
|
||||
});
|
||||
|
||||
program
|
||||
.command("create")
|
||||
.description(
|
||||
"Create a thirdweb app from any of our official templates. Checkout some examples you can use here: https://github.com/thirdweb-example/",
|
||||
)
|
||||
.option("--app", `Create a thirdweb app.`)
|
||||
.option("--contract", `Create a thirdweb contracts project.`)
|
||||
.option("--ts, --typescript", `Initialize as a TypeScript project.`)
|
||||
.option("--js, --javascript", `Initialize as a JavaScript project.`)
|
||||
.option("--forge", `Initialize as a Forge project.`)
|
||||
.option("--hardhat", `Initialize as a Hardhat project.`)
|
||||
.option("--cra", `Initialize as a Create React App project.`)
|
||||
.option("--next", `Initialize as a Next.js project.`)
|
||||
.option("--vite", `Initialize as a Vite project.`)
|
||||
.option(
|
||||
"--use-npm",
|
||||
`Explicitly tell the CLI to bootstrap the app using npm`,
|
||||
)
|
||||
.option(
|
||||
"--use-pnpm",
|
||||
`Explicitly tell the CLI to bootstrap the app using pnpm`,
|
||||
)
|
||||
.option("--framework [name]", `The preferred framework.`)
|
||||
.option(
|
||||
"-t, --template [name]",
|
||||
`A template to start your project from. You can use an template repository name from the official thirdweb-example org.`,
|
||||
)
|
||||
.action(async (options) => {
|
||||
await twCreate(options);
|
||||
});
|
||||
|
||||
program
|
||||
.command("install-ci")
|
||||
.description(
|
||||
"(alpha) Set up continuous integration for your contracts. This adds a github action to deploy the project on pull requests and pushes to branches. Publishes on push the the main branch.",
|
||||
)
|
||||
.action(async (options) => {
|
||||
await installGithubAction(options);
|
||||
});
|
||||
|
||||
await program.parseAsync();
|
||||
};
|
||||
|
||||
main()
|
||||
.then(() => {
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { spinner } from "../core/helpers/logger";
|
||||
import { IpfsStorage } from "@thirdweb-dev/storage";
|
||||
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
||||
import path, { join } from "path";
|
||||
|
||||
const ghActionHash = "ipfs://QmVMCdg6Jrro4GdySCVhvopwruxKdSgXJmYWA9mH9QjP3F";
|
||||
|
||||
export async function installGithubAction(options: any) {
|
||||
let projectPath = process.cwd();
|
||||
if (options.path) {
|
||||
const resolvedPath = (options.path as string).startsWith("/")
|
||||
? options.path
|
||||
: path.resolve(`${projectPath}/${options.path}`);
|
||||
projectPath = resolvedPath;
|
||||
}
|
||||
const storage = new IpfsStorage();
|
||||
const log = spinner("Installing thirdweb Github Action...");
|
||||
try {
|
||||
const ghActionData = await storage.getRaw(ghActionHash);
|
||||
const dir = join(projectPath, ".github/workflows");
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
writeFileSync(`${dir}/thirdweb.yml`, ghActionData);
|
||||
log.succeed(
|
||||
"thirdweb Github Action installed. Commit and push to the main GitHub branch to activate it.",
|
||||
);
|
||||
} catch (e) {
|
||||
log.fail(`Failed to install Github Action.\n\n${e}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export class UploadError extends Error {
|
||||
/** @internal */
|
||||
constructor(message: string) {
|
||||
super(`UPLOAD_FAILED: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export class DuplicateFileNameError extends Error {
|
||||
/** @internal */
|
||||
constructor(fileName: string) {
|
||||
super(
|
||||
`DUPLICATE_FILE_NAME_ERROR: File name ${fileName} was passed for more than one file.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when data fails to fetch from storage.
|
||||
* @internal
|
||||
*/
|
||||
export class FetchError extends Error {
|
||||
public innerError?: Error;
|
||||
|
||||
/** @internal */
|
||||
constructor(message: string, innerError?: Error) {
|
||||
super(`FETCH_FAILED: ${message}`);
|
||||
this.innerError = innerError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { ALWAYS_SUGGESTED } from "../constants/features";
|
||||
import build from "../core/builder/build";
|
||||
import detect from "../core/detection/detect";
|
||||
import { logger, spinner, warn, info } from "../core/helpers/logger";
|
||||
import { createContractsPrompt } from "../core/helpers/selector";
|
||||
import { ContractFeatures, Feature } from "../core/interfaces/ContractFeatures";
|
||||
import { ContractPayload } from "../core/interfaces/ContractPayload";
|
||||
import { detectFeatures } from "@thirdweb-dev/sdk";
|
||||
import { FeatureWithEnabled } from "@thirdweb-dev/sdk/dist/declarations/src/constants/contract-features";
|
||||
import chalk from "chalk";
|
||||
import ora from "ora";
|
||||
import path from "path";
|
||||
|
||||
const { MultiSelect } = require("enquirer");
|
||||
|
||||
export async function detectExtensions(options: any) {
|
||||
logger.setSettings({
|
||||
minLevel: options.debug ? "debug" : "info",
|
||||
});
|
||||
|
||||
let projectPath = process.cwd();
|
||||
if (options.path) {
|
||||
logger.debug("Overriding project path to " + options.path);
|
||||
|
||||
const resolvedPath = (options.path as string).startsWith("/")
|
||||
? options.path
|
||||
: path.resolve(`${projectPath}/${options.path}`);
|
||||
projectPath = resolvedPath;
|
||||
}
|
||||
|
||||
logger.debug("Processing project at path " + projectPath);
|
||||
|
||||
const projectType = await detect(projectPath, options);
|
||||
|
||||
let compiledResult;
|
||||
const compileLoader = spinner("Compiling project...");
|
||||
try {
|
||||
compiledResult = await build(projectPath, projectType);
|
||||
} catch (e) {
|
||||
compileLoader.fail("Compilation failed");
|
||||
logger.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
compileLoader.succeed("Compilation successful");
|
||||
|
||||
let selectedContracts: ContractPayload[] = [];
|
||||
if (compiledResult.contracts.length == 1) {
|
||||
selectedContracts = [compiledResult.contracts[0]];
|
||||
} else {
|
||||
if (options.all) {
|
||||
selectedContracts = compiledResult.contracts;
|
||||
} else {
|
||||
const choices = compiledResult.contracts.map((c) => ({
|
||||
name: c.name,
|
||||
value: c,
|
||||
}));
|
||||
const prompt = createContractsPrompt(
|
||||
choices,
|
||||
"Choose which contracts to run detection on",
|
||||
);
|
||||
const selection: Record<string, ContractPayload> = await prompt.run();
|
||||
selectedContracts = Object.keys(selection).map((key) => selection[key]);
|
||||
}
|
||||
}
|
||||
|
||||
let contractsWithFeatures: ContractFeatures[] = selectedContracts.map(
|
||||
(contract) => {
|
||||
const abi: Parameters<typeof detectFeatures>[0] = JSON.parse(
|
||||
contract.metadata,
|
||||
)["output"]["abi"];
|
||||
const features = extractFeatures(detectFeatures(abi));
|
||||
|
||||
const enabledFeatures: Feature[] = features.enabledFeatures.map(
|
||||
(feature) => ({
|
||||
name: feature.name,
|
||||
reference: `https://portal.thirdweb.com/contracts/${feature.docLinks.contracts}`,
|
||||
}),
|
||||
);
|
||||
const suggestedFeatures: Feature[] = features.suggestedFeatures.map(
|
||||
(feature) => ({
|
||||
name: feature.name,
|
||||
reference: `https://portal.thirdweb.com/contracts/${feature.docLinks.contracts}`,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
name: contract.name,
|
||||
enabledFeatures,
|
||||
suggestedFeatures,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
contractsWithFeatures.map((contractWithFeatures) => {
|
||||
logger.info(`\n`);
|
||||
if (contractWithFeatures.enabledFeatures.length === 0) {
|
||||
ora(
|
||||
`No extensions detected on ${chalk.blueBright(
|
||||
contractWithFeatures.name,
|
||||
)}`,
|
||||
).stopAndPersist({ symbol: "🔎" });
|
||||
} else {
|
||||
ora(
|
||||
`Detected extension on ${chalk.blueBright(contractWithFeatures.name)}`,
|
||||
).stopAndPersist({ symbol: "🔎" });
|
||||
contractWithFeatures.enabledFeatures.map((feature) => {
|
||||
info(`${chalk.green(feature.name)}`);
|
||||
});
|
||||
}
|
||||
logger.info(``);
|
||||
ora(`Suggested extensions`).info();
|
||||
contractWithFeatures.suggestedFeatures.map((feature) => {
|
||||
logger.info(
|
||||
`${chalk.dim(chalk.gray(`-`))} ${chalk.gray(
|
||||
feature.name,
|
||||
)} - ${chalk.dim(chalk.gray(feature.reference))}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function extractFeatures(
|
||||
input: ReturnType<typeof detectFeatures>,
|
||||
enabledFeatures: FeatureWithEnabled[] = [],
|
||||
suggestedFeatures: FeatureWithEnabled[] = [],
|
||||
parent = "__ROOT__",
|
||||
) {
|
||||
if (!input) {
|
||||
return {
|
||||
enabledFeatures,
|
||||
suggestedFeatures,
|
||||
};
|
||||
}
|
||||
for (const featureKey in input) {
|
||||
const feature = input[featureKey];
|
||||
// if feature is enabled, then add it to enabledFeatures
|
||||
if (feature.enabled) {
|
||||
enabledFeatures.push(feature);
|
||||
}
|
||||
// otherwise if it is disabled, but it's parent is enabled or suggested, then add it to suggestedFeatures
|
||||
else if (
|
||||
enabledFeatures.findIndex((f) => f.name === parent) > -1 ||
|
||||
ALWAYS_SUGGESTED.includes(feature.name)
|
||||
) {
|
||||
suggestedFeatures.push(feature);
|
||||
}
|
||||
// recurse
|
||||
extractFeatures(
|
||||
feature.features,
|
||||
enabledFeatures,
|
||||
suggestedFeatures,
|
||||
feature.name,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
enabledFeatures,
|
||||
suggestedFeatures,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { logger } from "../core/helpers/logger";
|
||||
import { existsSync, readdirSync, statSync } from "fs";
|
||||
import { basename, join } from "path";
|
||||
|
||||
export function findFiles(
|
||||
startPath: string,
|
||||
filter: RegExp,
|
||||
results: string[],
|
||||
) {
|
||||
if (!existsSync(startPath)) {
|
||||
console.log("no dir ", startPath);
|
||||
return;
|
||||
}
|
||||
|
||||
const files = readdirSync(startPath);
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const filename = join(startPath, files[i]);
|
||||
//skip the actual thirdweb contract itself
|
||||
if (basename(filename, ".json") === "ThirdwebContract") {
|
||||
continue;
|
||||
}
|
||||
const stat = statSync(filename);
|
||||
|
||||
// brownie has a "depdendencies" directory *inside* the build directory, if we detect that we should skip it
|
||||
if (stat.isDirectory() && basename(filename) === "dependencies") {
|
||||
logger.debug('skipping "dependencies" directory');
|
||||
continue;
|
||||
}
|
||||
// we never want to look in node_modules
|
||||
else if (stat.isDirectory() && basename(filename) === "node_modules") {
|
||||
logger.debug('skipping "node_modules" directory');
|
||||
continue;
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
findFiles(filename, filter, results);
|
||||
} else if (filter.test(filename)) {
|
||||
results.push(filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { THIRDWEB_URL, cliVersion } from "../constants/urls";
|
||||
import build from "../core/builder/build";
|
||||
import detect from "../core/detection/detect";
|
||||
import { execute } from "../core/helpers/exec";
|
||||
import { error, info, logger, spinner, warn } from "../core/helpers/logger";
|
||||
import { createContractsPrompt } from "../core/helpers/selector";
|
||||
import { ContractPayload } from "../core/interfaces/ContractPayload";
|
||||
import { IpfsStorage } from "@thirdweb-dev/storage";
|
||||
import chalk from "chalk";
|
||||
import { readFileSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
export async function processProject(
|
||||
options: any,
|
||||
command: "deploy" | "release",
|
||||
) {
|
||||
// TODO: allow overriding the default storage
|
||||
const storage = new IpfsStorage();
|
||||
|
||||
logger.setSettings({
|
||||
minLevel: options.debug ? "debug" : "info",
|
||||
});
|
||||
|
||||
let projectPath = process.cwd();
|
||||
if (options.path) {
|
||||
logger.debug("Overriding project path to " + options.path);
|
||||
|
||||
const resolvedPath = (options.path as string).startsWith("/")
|
||||
? options.path
|
||||
: path.resolve(`${projectPath}/${options.path}`);
|
||||
projectPath = resolvedPath;
|
||||
}
|
||||
|
||||
logger.debug("Processing project at path " + projectPath);
|
||||
|
||||
const projectType = await detect(projectPath, options);
|
||||
|
||||
if (options.ci) {
|
||||
logger.info("Installing dependencies...");
|
||||
try {
|
||||
switch (projectType) {
|
||||
case "foundry": {
|
||||
await execute(`npm install`, projectPath);
|
||||
await execute(`forge install`, projectPath);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
await execute(`npm install`, projectPath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("Could not install dependencies", e);
|
||||
}
|
||||
}
|
||||
|
||||
let compiledResult;
|
||||
const compileLoader = spinner("Compiling project...");
|
||||
try {
|
||||
compiledResult = await build(projectPath, projectType);
|
||||
} catch (e) {
|
||||
compileLoader.fail("Compilation failed");
|
||||
logger.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
compileLoader.succeed("Compilation successful");
|
||||
|
||||
if (compiledResult.contracts.length == 0) {
|
||||
logger.error(
|
||||
"No deployable contract detected. Run with the '--debug' option to see what contracts were skipped and why.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let selectedContracts: ContractPayload[] = [];
|
||||
if (compiledResult.contracts.length == 1) {
|
||||
selectedContracts = [compiledResult.contracts[0]];
|
||||
info(
|
||||
`Processing contract: ${chalk.blueBright(
|
||||
selectedContracts.map((c) => `"${c.name}"`).join(", "),
|
||||
)}`,
|
||||
);
|
||||
} else {
|
||||
if (options.ci) {
|
||||
selectedContracts = compiledResult.contracts;
|
||||
} else {
|
||||
const choices = compiledResult.contracts.map((c) => ({
|
||||
name: c.name,
|
||||
value: c,
|
||||
}));
|
||||
const prompt = createContractsPrompt(
|
||||
choices,
|
||||
`Choose which contract(s) to ${command}`,
|
||||
);
|
||||
const selection: Record<string, ContractPayload> = await prompt.run();
|
||||
selectedContracts = Object.keys(selection).map((key) => selection[key]);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedContracts.length === 0) {
|
||||
error(
|
||||
`No contract selected. Please select at least one contract to ${command}.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
info("Dry run, skipping deployment");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const loader = spinner("Uploading contract data...");
|
||||
|
||||
const soliditySDKPackage = "@thirdweb-dev/contracts";
|
||||
let usesSoliditySDK = false;
|
||||
|
||||
try {
|
||||
for (let i = 0; i < selectedContracts.length; i++) {
|
||||
const contract = selectedContracts[i];
|
||||
if (contract.sources) {
|
||||
// upload sources in batches to avoid getting rate limited (needs to be single uploads)
|
||||
const batchSize = 3;
|
||||
for (let j = 0; j < contract.sources.length; j = j + batchSize) {
|
||||
const batch = contract.sources.slice(j, j + batchSize);
|
||||
logger.debug(`Uploading Sources:\n${batch.join("\n")}\n`);
|
||||
await Promise.all(
|
||||
batch.map(async (c) => {
|
||||
const file = readFileSync(c, "utf-8");
|
||||
if (file.includes(soliditySDKPackage)) {
|
||||
usesSoliditySDK = true;
|
||||
}
|
||||
return await storage.uploadSingle(file);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Upload build output metadatas (need to be single uploads)
|
||||
const metadataURIs = await Promise.all(
|
||||
selectedContracts.map(async (c) => {
|
||||
logger.debug(`Uploading ${c.name}...`);
|
||||
const hash = await storage.uploadSingle(c.metadata);
|
||||
return `ipfs://${hash}`;
|
||||
}),
|
||||
);
|
||||
|
||||
// Upload batch all bytecodes
|
||||
const bytecodes = selectedContracts.map((c) => c.bytecode);
|
||||
const { uris: bytecodeURIs } = await storage.uploadBatch(bytecodes);
|
||||
|
||||
const combinedContents = selectedContracts.map((c, i) => {
|
||||
// attach analytics blob to metadata
|
||||
const analytics = {
|
||||
command,
|
||||
contract_name: c.name,
|
||||
cli_version: cliVersion,
|
||||
project_type: projectType,
|
||||
from_ci: options.ci || false,
|
||||
uses_contract_extensions: usesSoliditySDK,
|
||||
};
|
||||
return {
|
||||
name: c.name,
|
||||
metadataUri: metadataURIs[i],
|
||||
bytecodeUri: bytecodeURIs[i],
|
||||
analytics,
|
||||
};
|
||||
});
|
||||
let combinedURIs: string[] = [];
|
||||
if (combinedContents.length == 1) {
|
||||
// use upload single if only one contract to get a clean IPFS hash
|
||||
const metadataUri = await storage.uploadSingle(
|
||||
JSON.stringify(combinedContents[0]),
|
||||
);
|
||||
combinedURIs.push(metadataUri);
|
||||
} else {
|
||||
// otherwise upload batch
|
||||
const { uris } = await storage.uploadMetadataBatch(combinedContents);
|
||||
combinedURIs = uris;
|
||||
}
|
||||
|
||||
loader.succeed("Upload successful");
|
||||
|
||||
return getUrl(combinedURIs, command);
|
||||
} catch (e) {
|
||||
loader.fail("Error uploading metadata");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export function getUrl(hashes: string[], command: string) {
|
||||
let url;
|
||||
if (hashes.length == 1) {
|
||||
url = new URL(
|
||||
THIRDWEB_URL +
|
||||
`/contracts/${command}/` +
|
||||
encodeURIComponent(hashes[0].replace("ipfs://", "")),
|
||||
);
|
||||
} else {
|
||||
url = new URL(THIRDWEB_URL + "/contracts/" + command);
|
||||
for (let hash of hashes) {
|
||||
url.searchParams.append("ipfs", hash.replace("ipfs://", ""));
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
const baseContracts = {
|
||||
ERC721Base: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC721Base.sol";
|
||||
|
||||
contract Contract is ERC721Base {
|
||||
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps
|
||||
)
|
||||
ERC721Base(
|
||||
_name,
|
||||
_symbol,
|
||||
_royaltyRecipient,
|
||||
_royaltyBps
|
||||
)
|
||||
{}
|
||||
|
||||
}`,
|
||||
ERC721Signature: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC721SignatureMint.sol";
|
||||
|
||||
contract Contract is ERC721SignatureMint {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC721SignatureMint(
|
||||
_name,
|
||||
_symbol,
|
||||
_royaltyRecipient,
|
||||
_royaltyBps,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC721LazyMint: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC721LazyMint.sol";
|
||||
|
||||
contract Contract is ERC721LazyMint {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps
|
||||
) ERC721LazyMint(_name, _symbol, _royaltyRecipient, _royaltyBps) {}
|
||||
}`,
|
||||
ERC721DelayedReveal: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC721DelayedReveal.sol";
|
||||
|
||||
contract Contract is ERC721DelayedReveal {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps
|
||||
) ERC721DelayedReveal(_name, _symbol, _royaltyRecipient, _royaltyBps) {}
|
||||
}`,
|
||||
ERC721Drop: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC721Drop.sol";
|
||||
|
||||
contract Contract is ERC721Drop {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC721Drop(
|
||||
_name,
|
||||
_symbol,
|
||||
_royaltyRecipient,
|
||||
_royaltyBps,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC1155Base: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC1155Base.sol";
|
||||
|
||||
contract Contract is ERC1155Base {
|
||||
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps
|
||||
)
|
||||
ERC1155Base(
|
||||
_name,
|
||||
_symbol,
|
||||
_royaltyRecipient,
|
||||
_royaltyBps
|
||||
)
|
||||
{}
|
||||
|
||||
}`,
|
||||
ERC1155Signature: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC1155SignatureMint.sol";
|
||||
|
||||
contract Contract is ERC1155SignatureMint {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC1155SignatureMint(
|
||||
_name,
|
||||
_symbol,
|
||||
_royaltyRecipient,
|
||||
_royaltyBps,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC1155LazyMint: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC1155LazyMint.sol";
|
||||
|
||||
contract Contract is ERC1155LazyMint {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps
|
||||
) ERC1155LazyMint(_name, _symbol, _royaltyRecipient, _royaltyBps) {}
|
||||
}`,
|
||||
ERC1155DelayedReveal: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC1155DelayedReveal.sol";
|
||||
|
||||
contract Contract is ERC1155DelayedReveal {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps
|
||||
) ERC1155DelayedReveal(_name, _symbol, _royaltyRecipient, _royaltyBps) {}
|
||||
}`,
|
||||
ERC1155Drop: `// SPDX-License-Identifier: Apache-2.0
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC1155Drop.sol";
|
||||
|
||||
contract Contract is ERC1155Drop {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _royaltyRecipient,
|
||||
uint128 _royaltyBps,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC1155Drop(
|
||||
_name,
|
||||
_symbol,
|
||||
_royaltyRecipient,
|
||||
_royaltyBps,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC20Base: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC20Base.sol";
|
||||
|
||||
contract Contract is ERC20Base {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol
|
||||
)
|
||||
ERC20Base(
|
||||
_name,
|
||||
_symbol
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC20Vote: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC20Vote.sol";
|
||||
|
||||
contract Contract is ERC20Vote {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol
|
||||
)
|
||||
ERC20Vote(
|
||||
_name,
|
||||
_symbol
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC20SignatureMint: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC20SignatureMint.sol";
|
||||
|
||||
contract Contract is ERC20SignatureMint {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC20SignatureMint(
|
||||
_name,
|
||||
_symbol,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
|
||||
ERC20SignatureMintVote: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC20SignatureMintVote.sol";
|
||||
|
||||
contract Contract is ERC20SignatureMintVote {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC20SignatureMintVote(
|
||||
_name,
|
||||
_symbol,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
|
||||
ERC20Drop: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC20Drop.sol";
|
||||
|
||||
contract Contract is ERC20Drop {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC20Drop(
|
||||
_name,
|
||||
_symbol,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
ERC20DropVote: `// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.0;
|
||||
|
||||
import "@thirdweb-dev/contracts/base/ERC20DropVote.sol";
|
||||
|
||||
contract Contract is ERC20DropVote {
|
||||
constructor(
|
||||
string memory _name,
|
||||
string memory _symbol,
|
||||
address _primarySaleRecipient
|
||||
)
|
||||
ERC20DropVote(
|
||||
_name,
|
||||
_symbol,
|
||||
_primarySaleRecipient
|
||||
)
|
||||
{}
|
||||
}`,
|
||||
};
|
||||
|
||||
export default baseContracts;
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* Features that are always recommended to implement
|
||||
*/
|
||||
export const ALWAYS_SUGGESTED = ["ContractMetadata", "Permissions"];
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export const DEFAULT_IPFS_GATEWAY = "https://cloudflare-ipfs.com/ipfs/";
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export const TW_IPFS_SERVER_URL = "https://upload.nftlabs.co";
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export const PINATA_IPFS_URL = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export const THIRDWEB_URL = `https://thirdweb.com`;
|
||||
|
||||
export const pkg = require("../../package.json");
|
||||
export const cliVersion = pkg.version;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { findFiles } from "../../common/file-helper";
|
||||
import { execute } from "../helpers/exec";
|
||||
import { logger, spinner } from "../helpers/logger";
|
||||
import { CompileOptions } from "../interfaces/Builder";
|
||||
import { ContractPayload } from "../interfaces/ContractPayload";
|
||||
import { BaseBuilder } from "./builder-base";
|
||||
import { existsSync, readFileSync, rmSync } from "fs";
|
||||
import { basename, join } from "path";
|
||||
import { parse } from "yaml";
|
||||
|
||||
export class BrownieBuilder extends BaseBuilder {
|
||||
public async compile(options: CompileOptions): Promise<{
|
||||
contracts: ContractPayload[];
|
||||
}> {
|
||||
const config = parse(
|
||||
readFileSync(join(options.projectPath, "brownie-config.yaml"), "utf-8"),
|
||||
);
|
||||
|
||||
const buildPath = join(
|
||||
options.projectPath,
|
||||
config?.project_structure?.build || "./build",
|
||||
);
|
||||
|
||||
existsSync(buildPath) && rmSync(buildPath, { recursive: true });
|
||||
await execute("brownie compile", options.projectPath);
|
||||
|
||||
const contractsPath = join(buildPath, "contracts/");
|
||||
|
||||
const contracts: ContractPayload[] = [];
|
||||
const files: string[] = [];
|
||||
findFiles(contractsPath, /^.*(?<!dbg)\.json$/, files);
|
||||
|
||||
// TODO find a way to extract compiler metadata from brownie artifacts
|
||||
for (const file of files) {
|
||||
logger.debug("Processing:", file.replace(contractsPath, ""));
|
||||
const contractName = basename(file, ".json");
|
||||
const contractJsonFile = readFileSync(file, "utf-8");
|
||||
|
||||
const contractInfo = JSON.parse(contractJsonFile);
|
||||
const abi = contractInfo.abi;
|
||||
const bytecode = contractInfo.bytecode;
|
||||
|
||||
for (const input of abi) {
|
||||
if (this.isThirdwebContract(input)) {
|
||||
if (contracts.find((c) => c.name === contractName)) {
|
||||
logger.error(
|
||||
`Found multiple contracts with name "${contractName}". Contract names should be unique.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
contracts.push({
|
||||
metadata: {},
|
||||
bytecode,
|
||||
sources: [], // TODO
|
||||
name: contractName,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { contracts };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { ContractPayload } from "../interfaces/ContractPayload";
|
||||
import { ProjectType } from "./../types/ProjectType";
|
||||
import { BrownieBuilder } from "./brownie";
|
||||
import { FoundryBuilder } from "./foundry";
|
||||
import { HardhatBuilder } from "./hardhat";
|
||||
import { SolcBuilder } from "./solc";
|
||||
import { TruffleBuilder } from "./truffle";
|
||||
|
||||
export default async function build(
|
||||
path: string,
|
||||
projectType: ProjectType,
|
||||
): Promise<{
|
||||
contracts: ContractPayload[];
|
||||
}> {
|
||||
let builder;
|
||||
switch (projectType) {
|
||||
case "hardhat": {
|
||||
builder = new HardhatBuilder();
|
||||
break;
|
||||
}
|
||||
case "foundry": {
|
||||
builder = new FoundryBuilder();
|
||||
break;
|
||||
}
|
||||
case "truffle": {
|
||||
builder = new TruffleBuilder();
|
||||
break;
|
||||
}
|
||||
case "brownie": {
|
||||
builder = new BrownieBuilder();
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
builder = new SolcBuilder();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return await builder.compile({
|
||||
name: "",
|
||||
projectPath: path,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { extractIPFSHashFromBytecode } from "../helpers/ipfs";
|
||||
import { logger } from "../helpers/logger";
|
||||
import { CompileOptions, IBuilder } from "../interfaces/Builder";
|
||||
import { ContractPayload } from "../interfaces/ContractPayload";
|
||||
import { existsSync, readdirSync, statSync } from "fs";
|
||||
import { basename, join } from "path";
|
||||
|
||||
export abstract class BaseBuilder implements IBuilder {
|
||||
abstract compile(
|
||||
options: CompileOptions,
|
||||
): Promise<{ contracts: ContractPayload[] }>;
|
||||
|
||||
protected shouldProcessContract(
|
||||
abi: any[],
|
||||
bytecode: string,
|
||||
name: string,
|
||||
): boolean {
|
||||
if (
|
||||
!bytecode ||
|
||||
bytecode === "" ||
|
||||
bytecode === "0x" ||
|
||||
!abi ||
|
||||
abi.length == 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
// TODO as CLI options
|
||||
if (
|
||||
name === "ThirdwebContract" ||
|
||||
name.toLowerCase().includes("test") ||
|
||||
name.toLowerCase().includes("mock")
|
||||
) {
|
||||
logger.debug(`Skipping '${name}'.`);
|
||||
return false;
|
||||
}
|
||||
// ensure that we can extract IPFS hashes from the bytecode
|
||||
let ipfsHash;
|
||||
try {
|
||||
ipfsHash = extractIPFSHashFromBytecode(bytecode);
|
||||
} catch (e) {
|
||||
logger.debug(`Error extracting IPFS hash from '${name}': ${e}`);
|
||||
}
|
||||
|
||||
if (!ipfsHash) {
|
||||
logger.debug(
|
||||
`Cannot resolve build metadata IPFS hash for contract '${name}'. Skipping.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected isThirdwebContract(input: any): boolean {
|
||||
try {
|
||||
if (
|
||||
input.name === "setThirdwebInfo" &&
|
||||
input.inputs[0].internalType === "struct ThirdwebContract.ThirdwebInfo"
|
||||
) {
|
||||
logger.error(
|
||||
"You are using an old version of ThirdwebContract, please update to the latest version: 'npm i @thirdweb-dev/contracts'",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
input.name === "tw_initializeOwner" &&
|
||||
input.inputs[0].internalType === "address"
|
||||
);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { findFiles } from "../../common/file-helper";
|
||||
import { execute } from "../helpers/exec";
|
||||
import { logger } from "../helpers/logger";
|
||||
import { CompileOptions } from "../interfaces/Builder";
|
||||
import { ContractPayload } from "../interfaces/ContractPayload";
|
||||
import { BaseBuilder } from "./builder-base";
|
||||
import { existsSync, readFileSync } from "fs";
|
||||
import { basename, join } from "path";
|
||||
|
||||
export class FoundryBuilder extends BaseBuilder {
|
||||
public async compile(options: CompileOptions): Promise<{
|
||||
contracts: ContractPayload[];
|
||||
}> {
|
||||
await execute("forge clean", options.projectPath);
|
||||
await execute("forge build --extra-output metadata", options.projectPath);
|
||||
|
||||
// get the current config first
|
||||
const foundryConfig = (
|
||||
await execute("forge config --json", options.projectPath)
|
||||
).stdout;
|
||||
|
||||
const actualFoundryConfig = JSON.parse(foundryConfig);
|
||||
|
||||
const outPath = join(options.projectPath, actualFoundryConfig.out);
|
||||
|
||||
const contracts: ContractPayload[] = [];
|
||||
const files: string[] = [];
|
||||
findFiles(outPath, /^.*(?<!metadata)\.json$/, files);
|
||||
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i];
|
||||
const contractName = basename(file, ".json");
|
||||
const contractJsonFile = readFileSync(file, "utf-8");
|
||||
|
||||
const contractInfo = JSON.parse(contractJsonFile);
|
||||
|
||||
if (
|
||||
!contractInfo.bytecode ||
|
||||
!contractInfo.deployedBytecode ||
|
||||
!contractInfo.metadata
|
||||
) {
|
||||
logger.debug("Skipping", contractName, "(no bytecode or metadata)");
|
||||
continue;
|
||||
}
|
||||
|
||||
const target = contractInfo.metadata.settings.compilationTarget;
|
||||
if (
|
||||
Object.keys(target).length === 0 ||
|
||||
Object.keys(target)[0].includes("@") ||
|
||||
this.isTestOrScript(Object.keys(target)[0])
|
||||
) {
|
||||
// skip library contracts
|
||||
logger.debug("Skipping", contractName, "(not a source target)");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (contractName.startsWith("std")) {
|
||||
// skip library contracts
|
||||
logger.debug("Skipping", contractName, "(std library contract)");
|
||||
continue;
|
||||
}
|
||||
|
||||
const bytecode = contractInfo.bytecode.object;
|
||||
const deployedBytecode = contractInfo.deployedBytecode.object;
|
||||
const parsedMetadata = contractInfo.metadata;
|
||||
const metadata =
|
||||
contractInfo.rawMetadata ||
|
||||
this.sanitizeParsedMetadata(parsedMetadata, contractInfo.abi);
|
||||
|
||||
const sources = Object.keys(parsedMetadata.sources)
|
||||
.map((path) => {
|
||||
if (path.startsWith("/") && existsSync(path)) {
|
||||
return path;
|
||||
}
|
||||
const sourcePath = join(options.projectPath, path);
|
||||
if (existsSync(sourcePath)) {
|
||||
return sourcePath;
|
||||
}
|
||||
const nodeModulesPath = join(
|
||||
options.projectPath,
|
||||
"node_modules",
|
||||
path,
|
||||
);
|
||||
if (existsSync(nodeModulesPath)) {
|
||||
return nodeModulesPath;
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((path) => path !== undefined) as string[];
|
||||
|
||||
if (
|
||||
this.shouldProcessContract(
|
||||
contractInfo.abi,
|
||||
deployedBytecode,
|
||||
contractName,
|
||||
)
|
||||
) {
|
||||
contracts.push({
|
||||
name: contractName,
|
||||
metadata,
|
||||
bytecode,
|
||||
sources,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { contracts };
|
||||
}
|
||||
|
||||
private isTestOrScript(target: string) {
|
||||
return target.endsWith(".s.sol") || target.endsWith(".t.sol");
|
||||
}
|
||||
|
||||
private sort(object: any) {
|
||||
if (typeof object != "object" || object instanceof Array)
|
||||
// Not to sort the array
|
||||
return object;
|
||||
var keys = Object.keys(object);
|
||||
keys.sort();
|
||||
var newObject: any = {};
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
newObject[keys[i]] = this.sort(object[keys[i]]);
|
||||
}
|
||||
return newObject;
|
||||
}
|
||||
|
||||
private sanitizeParsedMetadata(
|
||||
parsedMetadata: Record<string, any>,
|
||||
abi: any,
|
||||
) {
|
||||
// replace the abi with the actual abi
|
||||
parsedMetadata.output.abi = abi;
|
||||
// need to re-add libraries if not present since forge stripts it out
|
||||
if (!parsedMetadata.settings.libraries) {
|
||||
parsedMetadata.settings.libraries = {};
|
||||
}
|
||||
// evm version can be omitted, add a default if not present
|
||||
if (!parsedMetadata.settings.evmVersion) {
|
||||
parsedMetadata.settings.evmVersion = "london";
|
||||
}
|
||||
// delete `outputSelection` from the metadata which has nothing to do here, bug in forge
|
||||
delete parsedMetadata.settings.outputSelection;
|
||||
// sort the metadata ALPHABETICALLY, since forge shuffles the keys in their parsing
|
||||
const meta: any = this.sort(parsedMetadata);
|
||||
return JSON.stringify(meta);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { findFiles } from "../../common/file-helper";
|
||||
import { execute } from "../helpers/exec";
|
||||
import { logger, spinner } from "../helpers/logger";
|
||||
import { CompileOptions } from "../interfaces/Builder";
|
||||
import { ContractPayload } from "../interfaces/ContractPayload";
|
||||
import { BaseBuilder } from "./builder-base";
|
||||
import { existsSync, readFileSync } from "fs";
|
||||
import { HardhatConfig } from "hardhat/types";
|
||||
import { join, resolve } from "path";
|
||||
|
||||
export class HardhatBuilder extends BaseBuilder {
|
||||
public async compile(options: CompileOptions): Promise<{
|
||||
contracts: ContractPayload[];
|
||||
}> {
|
||||
await execute("npx hardhat clean", options.projectPath);
|
||||
await execute("npx hardhat compile", options.projectPath);
|
||||
//we get our very own extractor script from the dir that we're in during execution
|
||||
// this is `./dist/cli` (for all purposes of the CLI)
|
||||
// then we look up the hardhat config extractor file path from there
|
||||
const configExtractorScriptPath = resolve(
|
||||
__dirname,
|
||||
"../helpers/hardhat-config-extractor.js",
|
||||
);
|
||||
|
||||
//the hardhat extractor **logs out** the runtime config of hardhat, we take that stdout and parse it
|
||||
const stringifiedConfig = (
|
||||
await execute(
|
||||
`npx hardhat run ${configExtractorScriptPath} --no-compile`,
|
||||
options.projectPath,
|
||||
)
|
||||
).stdout;
|
||||
//voila the hardhat config
|
||||
|
||||
const actualHardhatConfig = JSON.parse(
|
||||
stringifiedConfig.split("__tw__")[1],
|
||||
) as HardhatConfig;
|
||||
|
||||
logger.debug("successfully extracted hardhat config", actualHardhatConfig);
|
||||
|
||||
const solcConfigs = actualHardhatConfig.solidity.compilers;
|
||||
if (solcConfigs) {
|
||||
for (const solcConfig of solcConfigs) {
|
||||
const byteCodeHash = solcConfig.settings?.metadata?.bytecodeHash;
|
||||
if (byteCodeHash && byteCodeHash !== "ipfs") {
|
||||
throw new Error(
|
||||
`Deploying requires "bytecodeHash: 'ipfs'" in your hardhat.config.js file, but it's currently set as "bytecodeHash: '${byteCodeHash}'". Please change it to 'ipfs' and try again.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const artifactsPath = actualHardhatConfig.paths.artifacts;
|
||||
const sourcesDir = actualHardhatConfig.paths.sources.replace(
|
||||
options.projectPath,
|
||||
"",
|
||||
);
|
||||
const contractsPath = join(artifactsPath, sourcesDir);
|
||||
|
||||
const contracts: ContractPayload[] = [];
|
||||
const files: string[] = [];
|
||||
findFiles(contractsPath, /^.*(?<!dbg)\.json$/, files);
|
||||
|
||||
const buildOutputPath = join(artifactsPath, "build-info");
|
||||
const buildFiles: string[] = [];
|
||||
findFiles(buildOutputPath, /^.*(?<!dbg)\.json$/, buildFiles);
|
||||
|
||||
for (const buildFile of buildFiles) {
|
||||
const buildJsonFile = readFileSync(buildFile, "utf-8");
|
||||
const buildJson = JSON.parse(buildJsonFile);
|
||||
|
||||
const contractBuildOutputs = buildJson.output.contracts;
|
||||
|
||||
for (const [contractPath, contractInfos] of Object.entries(
|
||||
contractBuildOutputs,
|
||||
)) {
|
||||
if (contractPath.includes("@")) {
|
||||
// skip library contracts
|
||||
logger.debug("Skipping", contractPath, "(not a source target)");
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const [contractName, contractInfo] of Object.entries(
|
||||
contractInfos as any,
|
||||
)) {
|
||||
const info = contractInfo as any;
|
||||
|
||||
if (
|
||||
!info.evm ||
|
||||
!info.evm.bytecode ||
|
||||
!info.evm.bytecode.object ||
|
||||
!info.metadata ||
|
||||
!info.abi
|
||||
) {
|
||||
logger.debug("Skipping", contractPath, "(no bytecode or metadata)");
|
||||
continue;
|
||||
}
|
||||
|
||||
const bytecode = info.evm.bytecode.object;
|
||||
const deployedBytecode = info.evm.deployedBytecode.object;
|
||||
const metadata = info.metadata;
|
||||
const abi = info.abi;
|
||||
|
||||
const meta = JSON.parse(metadata);
|
||||
const sources = Object.keys(meta.sources)
|
||||
.map((path) => {
|
||||
const directPath = join(options.projectPath, path);
|
||||
if (existsSync(directPath)) {
|
||||
return directPath;
|
||||
}
|
||||
const sourcePath = join(options.projectPath, sourcesDir, path);
|
||||
if (existsSync(sourcePath)) {
|
||||
return sourcePath;
|
||||
}
|
||||
const nodeModulesPath = join(
|
||||
options.projectPath,
|
||||
"node_modules",
|
||||
path,
|
||||
);
|
||||
if (existsSync(nodeModulesPath)) {
|
||||
return nodeModulesPath;
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((path) => path !== undefined) as string[];
|
||||
|
||||
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
||||
contracts.push({
|
||||
metadata,
|
||||
bytecode,
|
||||
name: contractName,
|
||||
sources,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
contracts,
|
||||
};
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user