Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
564b17e760 | ||
|
|
b4507db963 | ||
|
|
f451da6395 | ||
|
|
ee47840767 | ||
|
|
bef97f72f4 | ||
|
|
3e87dd3ccb | ||
|
|
def42511ff | ||
|
|
c42545a647 | ||
|
|
6e20d1f21a | ||
|
|
e684d7e1ca | ||
|
|
f545a67e9f | ||
|
|
034a257442 | ||
|
|
1bfb91dbf3 | ||
|
|
5d95cbcdb2 | ||
|
|
639e535ed5 | ||
|
|
af3acc6b10 | ||
|
|
eca47763cd | ||
|
|
37b5bec897 | ||
|
|
48d91e4431 | ||
|
|
a20be881e3 | ||
|
|
47f8945325 | ||
|
|
1b0bf99da7 | ||
|
|
f03be398e0 | ||
|
|
27996cb4bc | ||
|
|
2eaa67acbe | ||
|
|
aafd7968df | ||
|
|
48797c7cf0 | ||
|
|
4edcb37100 | ||
|
|
83dcaf7058 | ||
|
|
b4e005be7f | ||
|
|
ccb7db4873 | ||
|
|
9151aa7dc8 | ||
|
|
5a01c537e3 | ||
|
|
f09c153ff7 | ||
|
|
15431621fd | ||
|
|
887af24450 | ||
|
|
15514f190a | ||
|
|
72589ec234 | ||
|
|
f8bceec10c | ||
|
|
7c0744a006 | ||
|
|
846022e2cf | ||
|
|
96bd92e724 |
@@ -13,6 +13,6 @@ runs:
|
|||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
shell: bash
|
shell: bash
|
||||||
run: yarn install
|
run: yarn install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"
|
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"
|
||||||
|
|||||||
@@ -28,7 +28,6 @@
|
|||||||
| [/storage](./packages/storage) | Best in class decentralized storage SDK for Browser and Node | <a href="https://www.npmjs.com/package/@thirdweb-dev/storage"><img src="https://img.shields.io/npm/v/@thirdweb-dev/storage?color=red&label=npm&logo=npm" alt="npm version"/></a> |
|
| [/storage](./packages/storage) | Best in class decentralized storage SDK for Browser and Node | <a href="https://www.npmjs.com/package/@thirdweb-dev/storage"><img src="https://img.shields.io/npm/v/@thirdweb-dev/storage?color=red&label=npm&logo=npm" alt="npm version"/></a> |
|
||||||
| [/cli](./packages/cli) | Publish and deploy smart contracts without dealing with private keys | <a href="https://www.npmjs.com/package/thirdweb"><img src="https://img.shields.io/npm/v/thirdweb?color=red&label=npm&logo=npm" alt="npm version"/></a> |
|
| [/cli](./packages/cli) | Publish and deploy smart contracts without dealing with private keys | <a href="https://www.npmjs.com/package/thirdweb"><img src="https://img.shields.io/npm/v/thirdweb?color=red&label=npm&logo=npm" alt="npm version"/></a> |
|
||||||
|
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
Visit [https://portal.thirdweb.com/](https://portal.thirdweb.com/) to view the full documentation.
|
Visit [https://portal.thirdweb.com/](https://portal.thirdweb.com/) to view the full documentation.
|
||||||
|
|||||||
@@ -1,5 +1,21 @@
|
|||||||
# @thirdweb-dev/auth
|
# @thirdweb-dev/auth
|
||||||
|
|
||||||
|
## 2.0.34
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#425](https://github.com/thirdweb-dev/js/pull/425) [`f545a67`](https://github.com/thirdweb-dev/js/commit/f545a67e9fb597d27bb39ca515d24d306fbb121a) Thanks [@adam-maj](https://github.com/adam-maj)! - Add sameSite none and include credentials
|
||||||
|
|
||||||
|
## 2.0.33
|
||||||
|
|
||||||
|
## 2.0.32
|
||||||
|
|
||||||
|
## 2.0.31
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#397](https://github.com/thirdweb-dev/js/pull/397) [`72589ec`](https://github.com/thirdweb-dev/js/commit/72589ec234d86939b67b0ca8b3b789f2e9c54cc2) Thanks [@adam-maj](https://github.com/adam-maj)! - Call user callback in getUser
|
||||||
|
|
||||||
## 2.0.30
|
## 2.0.30
|
||||||
|
|
||||||
## 2.0.29
|
## 2.0.29
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@thirdweb-dev/auth",
|
"name": "@thirdweb-dev/auth",
|
||||||
"version": "2.0.30",
|
"version": "2.0.34",
|
||||||
"exports": {
|
"exports": {
|
||||||
"./next": {
|
"./next": {
|
||||||
"module": "./next/dist/thirdweb-dev-auth-next.esm.js",
|
"module": "./next/dist/thirdweb-dev-auth-next.esm.js",
|
||||||
@@ -73,7 +73,7 @@
|
|||||||
"eslint-plugin-inclusive-language": "^2.2.0",
|
"eslint-plugin-inclusive-language": "^2.2.0",
|
||||||
"eslint-plugin-prettier": "^4.2.1",
|
"eslint-plugin-prettier": "^4.2.1",
|
||||||
"eslint-plugin-tsdoc": "^0.2.16",
|
"eslint-plugin-tsdoc": "^0.2.16",
|
||||||
"ethers": "^5.7.1",
|
"ethers": "^5.7.2",
|
||||||
"express": "^4.18.1",
|
"express": "^4.18.1",
|
||||||
"next": "^12.2.0",
|
"next": "^12.2.0",
|
||||||
"next-auth": "^4.10.3",
|
"next-auth": "^4.10.3",
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export default async function handler(
|
|||||||
path: "/",
|
path: "/",
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
secure: true,
|
||||||
sameSite: "strict",
|
sameSite: "none",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -40,11 +40,11 @@ export function ThirdwebNextAuth(cfg: ThirdwebNextAuthConfig) {
|
|||||||
path: "/",
|
path: "/",
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
secure: true,
|
||||||
sameSite: "strict",
|
sameSite: "none",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
return { address };
|
return { id: address, address };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,7 +70,13 @@ export function ThirdwebAuth(cfg: ThirdwebAuthConfig) {
|
|||||||
if (token) {
|
if (token) {
|
||||||
try {
|
try {
|
||||||
const address = await sdk.auth.authenticate(domain, token);
|
const address = await sdk.auth.authenticate(domain, token);
|
||||||
user = { address };
|
|
||||||
|
let data = {};
|
||||||
|
if (ctx.callbacks?.user) {
|
||||||
|
data = await ctx.callbacks.user(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
user = { ...data, address };
|
||||||
} catch {
|
} catch {
|
||||||
// No-op
|
// No-op
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export default async function handler(
|
|||||||
path: "/",
|
path: "/",
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
secure: true,
|
||||||
sameSite: "strict",
|
sameSite: "none",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -70,7 +70,13 @@ export function ThirdwebAuth(cfg: ThirdwebAuthConfig) {
|
|||||||
if (token) {
|
if (token) {
|
||||||
try {
|
try {
|
||||||
const address = await sdk.auth.authenticate(domain, token);
|
const address = await sdk.auth.authenticate(domain, token);
|
||||||
user = { address };
|
|
||||||
|
let data = {};
|
||||||
|
if (ctx.callbacks?.user) {
|
||||||
|
data = await ctx.callbacks.user(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
user = { ...data, address };
|
||||||
} catch {
|
} catch {
|
||||||
// No-op
|
// No-op
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export default async function handler(
|
|||||||
path: "/",
|
path: "/",
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
secure: true,
|
||||||
sameSite: "strict",
|
sameSite: "none",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,57 @@
|
|||||||
# thirdweb
|
# thirdweb
|
||||||
|
|
||||||
|
## 0.9.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#430](https://github.com/thirdweb-dev/js/pull/430) [`e684d7e`](https://github.com/thirdweb-dev/js/commit/e684d7e1ca16f633bce8698529d16bf60c264aa4) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix uploading contracts with special characters in the comments
|
||||||
|
|
||||||
|
- [#435](https://github.com/thirdweb-dev/js/pull/435) [`bef97f7`](https://github.com/thirdweb-dev/js/commit/bef97f72f4860596b7b70b05e67fcadf2c9a012e) Thanks [@adam-maj](https://github.com/adam-maj)! - Make solc default backup compilation
|
||||||
|
|
||||||
|
- [#432](https://github.com/thirdweb-dev/js/pull/432) [`3e87dd3`](https://github.com/thirdweb-dev/js/commit/3e87dd3ccb04a2b73437357c939a251e83b783b2) Thanks [@adam-maj](https://github.com/adam-maj)! - Display file name on duplicate contract names
|
||||||
|
|
||||||
|
- [#431](https://github.com/thirdweb-dev/js/pull/431) [`c42545a`](https://github.com/thirdweb-dev/js/commit/c42545a64725492136025fa1dcdb4d46ba674a30) Thanks [@adam-maj](https://github.com/adam-maj)! - Add changeset
|
||||||
|
|
||||||
|
- [#428](https://github.com/thirdweb-dev/js/pull/428) [`6e20d1f`](https://github.com/thirdweb-dev/js/commit/6e20d1f21a622f102e94b956f700d0871c0dc779) Thanks [@adam-maj](https://github.com/adam-maj)! - Update CLI to enable create contract inside contracts project
|
||||||
|
|
||||||
|
- Updated dependencies [[`f451da6`](https://github.com/thirdweb-dev/js/commit/f451da6395689a5f89800ee63f34b6175b61f703), [`af3acc6`](https://github.com/thirdweb-dev/js/commit/af3acc6b10751b840e56aef6400da5eea6040df2), [`1bfb91d`](https://github.com/thirdweb-dev/js/commit/1bfb91dbf3a39160c987a425813ac5dbb84703ad), [`ee47840`](https://github.com/thirdweb-dev/js/commit/ee478407673b0416e0c1cfe2be11bd6963395348), [`def4251`](https://github.com/thirdweb-dev/js/commit/def42511ff5a20d83f9094164dafb87e412571b5), [`034a257`](https://github.com/thirdweb-dev/js/commit/034a257442314c67729f7bafcbe3740cff33fa32), [`eca4776`](https://github.com/thirdweb-dev/js/commit/eca47763cd89cc3b7aa57b542971837987540b55), [`639e535`](https://github.com/thirdweb-dev/js/commit/639e535ed55280ad9d081001aab3f5af72bb3e45)]:
|
||||||
|
- @thirdweb-dev/sdk@3.6.4
|
||||||
|
|
||||||
|
## 0.9.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#415](https://github.com/thirdweb-dev/js/pull/415) [`48d91e4`](https://github.com/thirdweb-dev/js/commit/48d91e4431a3740d0f98f730ed5abf5b287f92c1) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Fix mappings for prebuilts redirect on deploy
|
||||||
|
|
||||||
|
## 0.9.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#403](https://github.com/thirdweb-dev/js/pull/403) [`27996cb`](https://github.com/thirdweb-dev/js/commit/27996cb4bc6f054f45b0a66b0a3aca732e0ef610) Thanks [@avneesh0612](https://github.com/avneesh0612)! - Add CLI Support for solana with --solana flag on create command
|
||||||
|
|
||||||
|
- [#283](https://github.com/thirdweb-dev/js/pull/283) [`2eaa67a`](https://github.com/thirdweb-dev/js/commit/2eaa67acbe21464e7715d0b696afdc024460a44d) Thanks [@adam-maj](https://github.com/adam-maj)! - add capability to deploy apps
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#413](https://github.com/thirdweb-dev/js/pull/413) [`1b0bf99`](https://github.com/thirdweb-dev/js/commit/1b0bf99da796df88ff307dd004cdaf239fb2b1ba) Thanks [@furqanrydhan](https://github.com/furqanrydhan)! - small interface tweaks
|
||||||
|
|
||||||
|
- Updated dependencies [[`48797c7`](https://github.com/thirdweb-dev/js/commit/48797c7cf0695965e33eb6bf602be4652f7085a8), [`83dcaf7`](https://github.com/thirdweb-dev/js/commit/83dcaf70584af8c5cdf0427f9fc1ba82d89f0887), [`f03be39`](https://github.com/thirdweb-dev/js/commit/f03be398e0d7b75c9c5b4fb643f35903e89a17e7), [`2eaa67a`](https://github.com/thirdweb-dev/js/commit/2eaa67acbe21464e7715d0b696afdc024460a44d), [`47f8945`](https://github.com/thirdweb-dev/js/commit/47f8945325447874b1ace0359919c1d54fd55436)]:
|
||||||
|
- @thirdweb-dev/sdk@3.6.3
|
||||||
|
|
||||||
|
## 0.8.18
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`ccb7db4`](https://github.com/thirdweb-dev/js/commit/ccb7db48739b8dddcb2c032b3b6e3e5200485715), [`9151aa7`](https://github.com/thirdweb-dev/js/commit/9151aa7dc80754a7aa4fd3f6ce0207bccbb6451f), [`5a01c53`](https://github.com/thirdweb-dev/js/commit/5a01c537e30bd7ef562aad1012413990de6faedf)]:
|
||||||
|
- @thirdweb-dev/sdk@3.6.2
|
||||||
|
|
||||||
|
## 0.8.17
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`15514f1`](https://github.com/thirdweb-dev/js/commit/15514f190a844d809ae5b1edb580aab46a682485), [`7c0744a`](https://github.com/thirdweb-dev/js/commit/7c0744a006e78987ad8b271b2c64f4bac7759510), [`f8bceec`](https://github.com/thirdweb-dev/js/commit/f8bceec10c60b30dc3d6f45926e2a9e018202578), [`887af24`](https://github.com/thirdweb-dev/js/commit/887af24450e316c2ea390cd49c0563cebe793c0f), [`96bd92e`](https://github.com/thirdweb-dev/js/commit/96bd92e724ec7d880d23348071b26ab8c21dd868)]:
|
||||||
|
- @thirdweb-dev/sdk@3.6.1
|
||||||
|
|
||||||
## 0.8.16
|
## 0.8.16
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
export const CREATE_MESSAGES = {
|
export const CREATE_MESSAGES = {
|
||||||
typeOfProject: "What type of project do you want to create?",
|
typeOfProject: "What type of project do you want to create?",
|
||||||
projectName: "What is your project named?",
|
projectName: "What is your project named?",
|
||||||
|
contractName: "What will be the name of your new smart contract?",
|
||||||
|
chain: "Which blockchain do you want to use?",
|
||||||
framework: "What framework do you want to use?",
|
framework: "What framework do you want to use?",
|
||||||
language: "What language do you want to use?",
|
language: "What language do you want to use?",
|
||||||
contract: "What type of contract do you want to start from?",
|
contract: "What type of contract do you want to start from?",
|
||||||
@@ -9,5 +11,5 @@ export const CREATE_MESSAGES = {
|
|||||||
|
|
||||||
export const ERROR_MESSAGES = {
|
export const ERROR_MESSAGES = {
|
||||||
noConfiguration:
|
noConfiguration:
|
||||||
"Failed to find a supported project configuration file in current directory",
|
"No contract project configuration file found in current directory",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { CREATE_MESSAGES } from "../constants/constants";
|
|||||||
import { prepareEnvironment } from "@gmrchk/cli-testing-library";
|
import { prepareEnvironment } from "@gmrchk/cli-testing-library";
|
||||||
|
|
||||||
// this creates an app, can take some time that's fine
|
// this creates an app, can take some time that's fine
|
||||||
jest.setTimeout(120_000);
|
jest.setTimeout(150_000);
|
||||||
|
|
||||||
describe("npx thirdweb create", () => {
|
describe("npx thirdweb create", () => {
|
||||||
it("should create app (CRA) successfully", async () => {
|
it("should create app (CRA) successfully", async () => {
|
||||||
@@ -16,6 +16,8 @@ describe("npx thirdweb create", () => {
|
|||||||
await pressKey("enter");
|
await pressKey("enter");
|
||||||
await waitForText(CREATE_MESSAGES.projectName);
|
await waitForText(CREATE_MESSAGES.projectName);
|
||||||
await pressKey("enter");
|
await pressKey("enter");
|
||||||
|
await waitForText(CREATE_MESSAGES.chain);
|
||||||
|
await pressKey("enter");
|
||||||
await waitForText(CREATE_MESSAGES.framework);
|
await waitForText(CREATE_MESSAGES.framework);
|
||||||
// select CRA
|
// select CRA
|
||||||
await pressKey("arrowDown");
|
await pressKey("arrowDown");
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ describe("npx thirdweb deploy", () => {
|
|||||||
`${path}/BasicContract.sol`,
|
`${path}/BasicContract.sol`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const { waitForText, waitForFinish, getExitCode, writeText, getStdout } =
|
const { waitForText, waitForFinish, getExitCode, writeText, getStderr } =
|
||||||
await spawn("node", "./dist/cli/index.js deploy");
|
await spawn("node", "./dist/cli/index.js deploy --contract");
|
||||||
|
|
||||||
expect(await exists("BasicContract.sol")).toEqual(true);
|
expect(await exists("BasicContract.sol")).toEqual(true);
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ describe("npx thirdweb deploy", () => {
|
|||||||
// wait for program to finish
|
// wait for program to finish
|
||||||
await waitForFinish();
|
await waitForFinish();
|
||||||
|
|
||||||
expect(getStdout().at(-1)).toContain(
|
expect(getStderr().at(-1)).toContain(
|
||||||
"https://thirdweb.com/contracts/deploy/",
|
"https://thirdweb.com/contracts/deploy/",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ describe("npx thirdweb detect", () => {
|
|||||||
await create.waitForText(CREATE_MESSAGES.framework);
|
await create.waitForText(CREATE_MESSAGES.framework);
|
||||||
// select hardhat
|
// select hardhat
|
||||||
await create.pressKey("enter");
|
await create.pressKey("enter");
|
||||||
|
await create.waitForText(CREATE_MESSAGES.contractName);
|
||||||
|
// set contract name
|
||||||
|
await create.writeText("Contract");
|
||||||
|
await create.pressKey("enter");
|
||||||
await create.waitForText(CREATE_MESSAGES.contract);
|
await create.waitForText(CREATE_MESSAGES.contract);
|
||||||
// select ERC721
|
// select ERC721
|
||||||
await create.pressKey("arrowDown");
|
await create.pressKey("arrowDown");
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ describe("npx thirdweb release", () => {
|
|||||||
`${path}/BasicContract.sol`,
|
`${path}/BasicContract.sol`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const { waitForText, waitForFinish, getExitCode, writeText, getStdout } =
|
const { waitForText, waitForFinish, getExitCode, writeText, getStderr } =
|
||||||
await spawn("node", "./dist/cli/index.js release");
|
await spawn("node", "./dist/cli/index.js release");
|
||||||
|
|
||||||
expect(await exists("BasicContract.sol")).toEqual(true);
|
expect(await exists("BasicContract.sol")).toEqual(true);
|
||||||
@@ -26,7 +26,7 @@ describe("npx thirdweb release", () => {
|
|||||||
// wait for program to finish
|
// wait for program to finish
|
||||||
await waitForFinish();
|
await waitForFinish();
|
||||||
|
|
||||||
expect(getStdout().at(-1)).toContain(
|
expect(getStderr().at(-1)).toContain(
|
||||||
"https://thirdweb.com/contracts/release/",
|
"https://thirdweb.com/contracts/release/",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "thirdweb",
|
"name": "thirdweb",
|
||||||
"main": "dist/cli/index.js",
|
"main": "dist/cli/index.js",
|
||||||
"version": "0.8.16",
|
"version": "0.9.2",
|
||||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
|
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
|
||||||
"author": "thirdweb eng <[email protected]>",
|
"author": "thirdweb eng <[email protected]>",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gmrchk/cli-testing-library": "^0.1.2",
|
"@gmrchk/cli-testing-library": "^0.1.2",
|
||||||
"@types/async-retry": "1.3.0",
|
"@types/async-retry": "^1.3.0",
|
||||||
"@types/cross-spawn": "^6.0.2",
|
"@types/cross-spawn": "^6.0.2",
|
||||||
"@types/inquirer": "^8.2.1",
|
"@types/inquirer": "^8.2.1",
|
||||||
"@types/jest": "^29.0.0",
|
"@types/jest": "^29.0.0",
|
||||||
@@ -33,13 +33,13 @@
|
|||||||
"async-retry": "^1.3.3",
|
"async-retry": "^1.3.3",
|
||||||
"commander": "^9.1.0",
|
"commander": "^9.1.0",
|
||||||
"enquirer": "^2.3.6",
|
"enquirer": "^2.3.6",
|
||||||
"ethers": "^5.7.0",
|
"ethers": "^5.7.2",
|
||||||
"got": "11.8.5",
|
"got": "11.8.5",
|
||||||
"inquirer": "^8.2.3",
|
"inquirer": "^8.2.3",
|
||||||
"open": "^8.4.0",
|
"open": "^8.4.0",
|
||||||
"prompts": "^2.4.2",
|
"prompts": "^2.4.2",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"solc": "0.8.13",
|
"solc": "0.8.17",
|
||||||
"tar": "^6.1.11",
|
"tar": "^6.1.11",
|
||||||
"tslog": "^3.3.3",
|
"tslog": "^3.3.3",
|
||||||
"update-notifier": "^6.0.2",
|
"update-notifier": "^6.0.2",
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { processProject } from "../common/processor";
|
|||||||
import { cliVersion, pkg } from "../constants/urls";
|
import { cliVersion, pkg } from "../constants/urls";
|
||||||
import { info, logger } from "../core/helpers/logger";
|
import { info, logger } from "../core/helpers/logger";
|
||||||
import { twCreate } from "../create/command";
|
import { twCreate } from "../create/command";
|
||||||
import generateDashboardUrl from "../helpers/generate-dashboard-url";
|
import { deploy } from "../deploy";
|
||||||
import { upload } from "../storage/command";
|
import { upload } from "../storage/command";
|
||||||
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
@@ -40,34 +40,40 @@ $$$$$$\\ $$$$$$$\\ $$\\ $$$$$$\\ $$$$$$$ |$$\\ $$\\ $$\\ $$$$$$\\ $$$$
|
|||||||
.version(cliVersion, "-v, --version");
|
.version(cliVersion, "-v, --version");
|
||||||
|
|
||||||
program
|
program
|
||||||
.command("create [projectPath]")
|
.command("create [projectType] [projectPath]")
|
||||||
.description(
|
.description(
|
||||||
"Create a web3 app from any of our official templates: https://github.com/thirdweb-example/",
|
"Create a web3 app from any of our official templates: https://github.com/thirdweb-example/",
|
||||||
)
|
)
|
||||||
.option("--app", `Create a web3 app.`)
|
.option("--app", "Create a web3 app.")
|
||||||
.option("--contract", `Create a web3 contract project`)
|
.option("--contract", "Create a web3 contract project")
|
||||||
.option("--ts, --typescript", `Initialize as a TypeScript project.`)
|
.option("--ts, --typescript", "Initialize as a TypeScript project.")
|
||||||
.option("--js, --javascript", `Initialize as a JavaScript project.`)
|
.option("--js, --javascript", "Initialize as a JavaScript project.")
|
||||||
.option("--forge", `Initialize as a Forge project.`)
|
.option("--forge", "Initialize as a Forge project.")
|
||||||
.option("--hardhat", `Initialize as a Hardhat project.`)
|
.option("--hardhat", "Initialize as a Hardhat project.")
|
||||||
.option("--cra", `Initialize as a Create React App project.`)
|
.option("--cra", "Initialize as a Create React App project.")
|
||||||
.option("--next", `Initialize as a Next.js project.`)
|
.option("--next", "Initialize as a Next.js project.")
|
||||||
.option("--vite", `Initialize as a Vite project.`)
|
.option("--vite", "Initialize as a Vite project.")
|
||||||
.option(
|
.option(
|
||||||
"--use-npm",
|
"--use-npm",
|
||||||
`Explicitly tell the CLI to bootstrap the app using npm`,
|
"Explicitly tell the CLI to bootstrap the app using npm",
|
||||||
)
|
)
|
||||||
.option(
|
.option(
|
||||||
"--use-pnpm",
|
"--use-pnpm",
|
||||||
`Explicitly tell the CLI to bootstrap the app using pnpm`,
|
"Explicitly tell the CLI to bootstrap the app using pnpm",
|
||||||
)
|
)
|
||||||
.option("--framework [name]", `The preferred framework.`)
|
.option("--framework [name]", "The preferred framework.")
|
||||||
|
.option("--solana", "Initialize as a Solana project.")
|
||||||
|
.option("--evm", "Initialize as an Ethereum project.")
|
||||||
.option(
|
.option(
|
||||||
"-t, --template [name]",
|
"-t, --template [name]",
|
||||||
`A template to start your project from. You can use an template repository name from the official thirdweb-example org.`,
|
"A template to start your project from. You can use an template repository name from the official thirdweb-example org.",
|
||||||
)
|
)
|
||||||
.action(async (path, options) => {
|
.option(
|
||||||
await twCreate(path, options);
|
"-c, --contract-name [name]",
|
||||||
|
"Name of the new smart contract to create",
|
||||||
|
)
|
||||||
|
.action(async (type, path, options) => {
|
||||||
|
await twCreate(type, path, options);
|
||||||
});
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
@@ -87,39 +93,33 @@ $$$$$$\\ $$$$$$$\\ $$\\ $$$$$$\\ $$$$$$$ |$$\\ $$\\ $$\\ $$$$$$\\ $$$$
|
|||||||
.option("--dry-run", "dry run (skip actually publishing)")
|
.option("--dry-run", "dry run (skip actually publishing)")
|
||||||
.option("-d, --debug", "show debug logs")
|
.option("-d, --debug", "show debug logs")
|
||||||
.option("--ci", "Continuous Integration mode")
|
.option("--ci", "Continuous Integration mode")
|
||||||
|
.option(
|
||||||
|
"--dist-path [distPath]",
|
||||||
|
"Path to the dist folder where the HTML based App is",
|
||||||
|
)
|
||||||
.option(
|
.option(
|
||||||
"-n, --name [name]",
|
"-n, --name [name]",
|
||||||
"Name of the pre-built or released contract (such as nft-drop)",
|
"Name of the pre-built or released contract (such as nft-drop)",
|
||||||
)
|
)
|
||||||
|
.option(
|
||||||
|
"-f, --file [name]",
|
||||||
|
"Filter for contract files that contain this file name",
|
||||||
|
)
|
||||||
|
.option(
|
||||||
|
"-cn, --contract-name [name]",
|
||||||
|
"Filter for contracts that contain this contract name",
|
||||||
|
)
|
||||||
.option(
|
.option(
|
||||||
"-cv, --contract-version [version]",
|
"-cv, --contract-version [version]",
|
||||||
"Version of the released contract",
|
"Version of the released contract",
|
||||||
)
|
)
|
||||||
|
.option("--app", "Deploy a web app to decentralized storage")
|
||||||
|
.option("--contract", "Deploy a smart contract to blockchains")
|
||||||
.action(async (options) => {
|
.action(async (options) => {
|
||||||
if (options.name) {
|
const url = await deploy(options);
|
||||||
const url = generateDashboardUrl(options.name, options.contractVersion);
|
if (url) {
|
||||||
|
open(url);
|
||||||
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
|
program
|
||||||
@@ -128,13 +128,24 @@ $$$$$$\\ $$$$$$$\\ $$\\ $$$$$$\\ $$$$$$$ |$$\\ $$\\ $$\\ $$$$$$\\ $$$$
|
|||||||
"Release your protocol so other devs can deploy them and unlock SDKs, Dashboards and Analytics",
|
"Release your protocol so other devs can deploy them and unlock SDKs, Dashboards and Analytics",
|
||||||
)
|
)
|
||||||
.option("-p, --path <project-path>", "path to project", ".")
|
.option("-p, --path <project-path>", "path to project", ".")
|
||||||
|
.option(
|
||||||
|
"-f, --file [name]",
|
||||||
|
"Filter for contract files that contain the file name",
|
||||||
|
)
|
||||||
|
.option(
|
||||||
|
"-cn, --contract-name [name]",
|
||||||
|
"Filter for contracts that contain this contract name",
|
||||||
|
)
|
||||||
.option("--dry-run", "dry run (skip actually publishing)")
|
.option("--dry-run", "dry run (skip actually publishing)")
|
||||||
.option("-d, --debug", "show debug logs")
|
.option("-d, --debug", "show debug logs")
|
||||||
.option("--ci", "Continuous Integration mode")
|
.option("--ci", "Continuous Integration mode")
|
||||||
.action(async (options) => {
|
.action(async (options) => {
|
||||||
const url = await processProject(options, "release");
|
const url = await processProject(options, "release");
|
||||||
info(`Open this link to release your contracts:`);
|
info(
|
||||||
logger.info(chalk.blueBright(url.toString()));
|
`Open this link to release your contracts: ${chalk.blueBright(
|
||||||
|
url.toString(),
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
open(url.toString());
|
open(url.toString());
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -144,13 +155,35 @@ $$$$$$\\ $$$$$$$\\ $$\\ $$$$$$\\ $$$$$$$ |$$\\ $$\\ $$\\ $$$$$$\\ $$$$
|
|||||||
.argument("[upload]", "path to file or directory to upload")
|
.argument("[upload]", "path to file or directory to upload")
|
||||||
.action(async (path) => {
|
.action(async (path) => {
|
||||||
const storage = new ThirdwebStorage();
|
const storage = new ThirdwebStorage();
|
||||||
const uri = await upload(storage, path);
|
try {
|
||||||
info(`Files stored at the following IPFS URI:`);
|
const uri = await upload(storage, path);
|
||||||
logger.info(chalk.blueBright(uri.toString()));
|
info(
|
||||||
|
`Files stored at the following IPFS URI: ${chalk.blueBright(
|
||||||
|
uri.toString(),
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
|
|
||||||
const url = storage.resolveScheme(uri);
|
const url = storage.resolveScheme(uri);
|
||||||
info(`Open this link to view your upload:`);
|
info(
|
||||||
logger.info(chalk.blueBright(url.toString()));
|
`Open this link to view your upload: ${chalk.blueBright(
|
||||||
|
url.toString(),
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
if (
|
||||||
|
err.toString() === "No files detected in specified directory" ||
|
||||||
|
err.toString() === "Invalid path provided" ||
|
||||||
|
err.toString() === "No path provided"
|
||||||
|
) {
|
||||||
|
logger.error(
|
||||||
|
chalk.redBright(
|
||||||
|
"Please specify a valid file or directory to upload",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
logger.error(chalk.redBright("Failed to upload files"), err);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export async function processProject(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let compiledResult;
|
let compiledResult: { contracts: ContractPayload[] };
|
||||||
const compileLoader = spinner("Compiling project...");
|
const compileLoader = spinner("Compiling project...");
|
||||||
try {
|
try {
|
||||||
compiledResult = await build(projectPath, projectType);
|
compiledResult = await build(projectPath, projectType);
|
||||||
@@ -106,10 +106,47 @@ export async function processProject(
|
|||||||
if (options.ci) {
|
if (options.ci) {
|
||||||
selectedContracts = compiledResult.contracts;
|
selectedContracts = compiledResult.contracts;
|
||||||
} else {
|
} else {
|
||||||
const choices = compiledResult.contracts.map((c) => ({
|
const filtered = compiledResult.contracts
|
||||||
name: c.name,
|
.filter((c) => {
|
||||||
value: c,
|
if (typeof options.file === "string" && options.file.length > 0) {
|
||||||
}));
|
return c.fileName.includes(options.file);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.filter((c) => {
|
||||||
|
if (
|
||||||
|
typeof options.contractName === "string" &&
|
||||||
|
options.contractName.length > 0
|
||||||
|
) {
|
||||||
|
return c.name.includes(options.contractName);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (filtered.length === 0) {
|
||||||
|
logger.error(`No contracts found matching the specified filters.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const choices = filtered.map((c) => {
|
||||||
|
if (
|
||||||
|
compiledResult.contracts.filter(
|
||||||
|
(other: ContractPayload) => other.name === c.name,
|
||||||
|
).length > 1
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
name: `${c.name} - ${chalk.gray(c.fileName)}`,
|
||||||
|
value: c,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: c.name,
|
||||||
|
value: c,
|
||||||
|
};
|
||||||
|
});
|
||||||
const prompt = createContractsPrompt(
|
const prompt = createContractsPrompt(
|
||||||
choices,
|
choices,
|
||||||
`Choose which contract(s) to ${command}`,
|
`Choose which contract(s) to ${command}`,
|
||||||
@@ -164,7 +201,7 @@ export async function processProject(
|
|||||||
const metadataURIs = await Promise.all(
|
const metadataURIs = await Promise.all(
|
||||||
selectedContracts.map(async (c) => {
|
selectedContracts.map(async (c) => {
|
||||||
logger.debug(`Uploading ${c.name}...`);
|
logger.debug(`Uploading ${c.name}...`);
|
||||||
return await storage.upload(JSON.parse(c.metadata), {
|
return await storage.upload(JSON.parse(JSON.stringify(c.metadata)), {
|
||||||
uploadWithoutDirectory: true,
|
uploadWithoutDirectory: true,
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ export class BrownieBuilder extends BaseBuilder {
|
|||||||
metadata: {},
|
metadata: {},
|
||||||
bytecode,
|
bytecode,
|
||||||
sources: [], // TODO
|
sources: [], // TODO
|
||||||
|
fileName: "", // TODO
|
||||||
name: contractName,
|
name: contractName,
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -88,6 +88,11 @@ export class FoundryBuilder extends BaseBuilder {
|
|||||||
})
|
})
|
||||||
.filter((path) => path !== undefined) as string[];
|
.filter((path) => path !== undefined) as string[];
|
||||||
|
|
||||||
|
const fileNames = Object.keys(
|
||||||
|
parsedMetadata?.settings?.compilationTarget || {},
|
||||||
|
);
|
||||||
|
const fileName = fileNames.length > 0 ? fileNames[0] : "";
|
||||||
|
|
||||||
if (
|
if (
|
||||||
this.shouldProcessContract(
|
this.shouldProcessContract(
|
||||||
contractInfo.abi,
|
contractInfo.abi,
|
||||||
@@ -99,6 +104,7 @@ export class FoundryBuilder extends BaseBuilder {
|
|||||||
name: contractName,
|
name: contractName,
|
||||||
metadata,
|
metadata,
|
||||||
bytecode,
|
bytecode,
|
||||||
|
fileName,
|
||||||
sources,
|
sources,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export class HardhatBuilder extends BaseBuilder {
|
|||||||
//the hardhat extractor **logs out** the runtime config of hardhat, we take that stdout and parse it
|
//the hardhat extractor **logs out** the runtime config of hardhat, we take that stdout and parse it
|
||||||
const stringifiedConfig = (
|
const stringifiedConfig = (
|
||||||
await execute(
|
await execute(
|
||||||
`npx hardhat run ${configExtractorScriptPath} --no-compile`,
|
`npx hardhat run "${configExtractorScriptPath}" --no-compile`,
|
||||||
options.projectPath,
|
options.projectPath,
|
||||||
)
|
)
|
||||||
).stdout;
|
).stdout;
|
||||||
@@ -123,11 +123,17 @@ export class HardhatBuilder extends BaseBuilder {
|
|||||||
})
|
})
|
||||||
.filter((path) => path !== undefined) as string[];
|
.filter((path) => path !== undefined) as string[];
|
||||||
|
|
||||||
|
const fileNames = Object.keys(
|
||||||
|
meta?.settings?.compilationTarget || {},
|
||||||
|
);
|
||||||
|
const fileName = fileNames.length > 0 ? fileNames[0] : "";
|
||||||
|
|
||||||
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
||||||
contracts.push({
|
contracts.push({
|
||||||
metadata,
|
metadata,
|
||||||
bytecode,
|
bytecode,
|
||||||
name: contractName,
|
name: contractName,
|
||||||
|
fileName,
|
||||||
sources,
|
sources,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,11 +140,17 @@ export class SolcBuilder extends BaseBuilder {
|
|||||||
})
|
})
|
||||||
.filter((path) => path !== undefined) as string[];
|
.filter((path) => path !== undefined) as string[];
|
||||||
|
|
||||||
|
const fileNames = Object.keys(
|
||||||
|
parsedMetadata?.settings?.compilationTarget || {},
|
||||||
|
);
|
||||||
|
const fileName = fileNames.length > 0 ? fileNames[0] : "";
|
||||||
|
|
||||||
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
||||||
contracts.push({
|
contracts.push({
|
||||||
metadata,
|
metadata,
|
||||||
bytecode,
|
bytecode,
|
||||||
name: contractName,
|
name: contractName,
|
||||||
|
fileName,
|
||||||
sources: _sources,
|
sources: _sources,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,11 +72,18 @@ export class TruffleBuilder extends BaseBuilder {
|
|||||||
return undefined;
|
return undefined;
|
||||||
})
|
})
|
||||||
.filter((path) => path !== undefined) as string[];
|
.filter((path) => path !== undefined) as string[];
|
||||||
|
|
||||||
|
const fileNames = Object.keys(
|
||||||
|
parsedMetadata?.settings?.compilationTarget || {},
|
||||||
|
);
|
||||||
|
const fileName = fileNames.length > 0 ? fileNames[0] : "";
|
||||||
|
|
||||||
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
|
||||||
contracts.push({
|
contracts.push({
|
||||||
metadata,
|
metadata,
|
||||||
bytecode,
|
bytecode,
|
||||||
name: contractName,
|
name: contractName,
|
||||||
|
fileName,
|
||||||
sources,
|
sources,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ export default async function detect(
|
|||||||
name: "continue",
|
name: "continue",
|
||||||
message:
|
message:
|
||||||
"Do you want to continue and compile this project with solc instead?",
|
"Do you want to continue and compile this project with solc instead?",
|
||||||
|
initial: true,
|
||||||
});
|
});
|
||||||
const shouldCompile = await prompt.run();
|
const shouldCompile = await prompt.run();
|
||||||
if (!shouldCompile) {
|
if (!shouldCompile) {
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { ProjectType } from "../types/ProjectType";
|
||||||
|
import { Detector } from "./detector";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export default class NPMDetector implements Detector {
|
||||||
|
public projectType: ProjectType = "npm";
|
||||||
|
|
||||||
|
public matches(path: string): boolean {
|
||||||
|
return existsSync(path + "/package-lock.json");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { ProjectType } from "../types/ProjectType";
|
||||||
|
import { Detector } from "./detector";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export default class ViteDetector implements Detector {
|
||||||
|
public projectType: ProjectType = "vite";
|
||||||
|
|
||||||
|
public matches(path: string): boolean {
|
||||||
|
return (
|
||||||
|
existsSync(path + "/vite.config.js") ||
|
||||||
|
existsSync(path + "/vite.config.ts")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { ProjectType } from "../types/ProjectType";
|
||||||
|
import { Detector } from "./detector";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
|
||||||
|
export default class YarnDetector implements Detector {
|
||||||
|
public projectType: ProjectType = "yarn";
|
||||||
|
|
||||||
|
public matches(path: string): boolean {
|
||||||
|
return existsSync(path + "/yarn.lock");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,11 @@ export interface ContractPayload {
|
|||||||
*/
|
*/
|
||||||
metadata: any;
|
metadata: any;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The file name of the original compiled file
|
||||||
|
*/
|
||||||
|
fileName: string;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The source file paths
|
* The source file paths
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,4 +4,10 @@ export type ProjectType =
|
|||||||
| "hardhat"
|
| "hardhat"
|
||||||
| "truffle"
|
| "truffle"
|
||||||
| "solc"
|
| "solc"
|
||||||
|
| "vite"
|
||||||
|
| "next"
|
||||||
|
| "cra"
|
||||||
|
| "spa-webapp"
|
||||||
|
| "yarn"
|
||||||
|
| "npm"
|
||||||
| "none";
|
| "none";
|
||||||
|
|||||||
+262
-131
@@ -2,60 +2,82 @@
|
|||||||
|
|
||||||
/* eslint-disable import/no-extraneous-dependencies */
|
/* eslint-disable import/no-extraneous-dependencies */
|
||||||
import { CREATE_MESSAGES } from "../../constants/constants";
|
import { CREATE_MESSAGES } from "../../constants/constants";
|
||||||
|
import detect from "../core/detection/detect";
|
||||||
import { DownloadError, createApp } from "./helpers/create-app";
|
import { DownloadError, createApp } from "./helpers/create-app";
|
||||||
import { createContract } from "./helpers/create-contract";
|
import { createContractProject } from "./helpers/create-contract";
|
||||||
import { getPkgManager } from "./helpers/get-pkg-manager";
|
import { getPkgManager } from "./helpers/get-pkg-manager";
|
||||||
import { validateNpmName } from "./helpers/validate-pkg";
|
import { validateNpmName } from "./helpers/validate-pkg";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
|
import fs from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import prompts from "prompts";
|
import prompts from "prompts";
|
||||||
|
|
||||||
let projectType: string = "";
|
let contractName: string = "";
|
||||||
let projectPath: string = "";
|
let projectPath: string = "";
|
||||||
|
let projectType: string = "";
|
||||||
let framework: string = "";
|
let framework: string = "";
|
||||||
let language: string = "";
|
let language: string = "";
|
||||||
let baseContract: string = "";
|
let baseContract: string = "";
|
||||||
|
let chain: string = "";
|
||||||
/* let createType: string = "app"; */
|
/* let createType: string = "app"; */
|
||||||
|
|
||||||
export async function twCreate(pPath: string = "", options: any) {
|
export async function twCreate(
|
||||||
|
pType: string,
|
||||||
|
pPath: string = "",
|
||||||
|
options: any,
|
||||||
|
) {
|
||||||
if (typeof pPath === "string") {
|
if (typeof pPath === "string") {
|
||||||
projectPath = pPath;
|
projectPath = pPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.app) {
|
if (typeof options.contractName === "string") {
|
||||||
projectType = "app";
|
contractName = options.contractName;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.contract) {
|
if (pType === "app" || options.app) {
|
||||||
|
projectType = "app";
|
||||||
|
} else if (pType === "contract" || options.contract) {
|
||||||
projectType = "contract";
|
projectType = "contract";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.typescript) {
|
if (projectType === "app") {
|
||||||
language = "typescript";
|
if (options.typescript) {
|
||||||
|
language = "typescript";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.javascript) {
|
||||||
|
language = "javascript";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.next) {
|
||||||
|
framework = "next";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.cra) {
|
||||||
|
framework = "cra";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.vite) {
|
||||||
|
framework = "vite";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.solana) {
|
||||||
|
chain = "solana";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.evm) {
|
||||||
|
chain = "evm";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.javascript) {
|
if (projectType === "contract") {
|
||||||
language = "javascript";
|
if (options.forge) {
|
||||||
}
|
framework = "forge";
|
||||||
|
}
|
||||||
|
|
||||||
if (options.next) {
|
if (options.hardhat) {
|
||||||
framework = "next";
|
framework = "hardhat";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.cra) {
|
|
||||||
framework = "cra";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.vite) {
|
|
||||||
framework = "vite";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.forge) {
|
|
||||||
framework = "forge";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.hardhat) {
|
|
||||||
framework = "hardhat";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.framework) {
|
if (options.framework) {
|
||||||
@@ -76,103 +98,216 @@ export async function twCreate(pPath: string = "", options: any) {
|
|||||||
if (typeof res.projectType === "string") {
|
if (typeof res.projectType === "string") {
|
||||||
projectType = res.projectType.trim();
|
projectType = res.projectType.trim();
|
||||||
}
|
}
|
||||||
} else if (!projectType && options.template) {
|
} else if (!projectType || options.template) {
|
||||||
// If no project type is specified, but a template is, we assume the user wants to create an app.
|
// If no project type is specified, but a template is, we assume the user wants to create an app.
|
||||||
// We do this so old users can still use the --template flag to create an app.
|
// We do this so old users can still use the --template flag to create an app.
|
||||||
projectType = "app";
|
projectType = "app";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!projectPath) {
|
// Whether to only create a new contract without the project
|
||||||
const defaultName =
|
let onlyContract = false;
|
||||||
projectType === "contract" ? "thirdweb-contracts" : "thirdweb-app";
|
if (projectType === "contract") {
|
||||||
const res = await prompts({
|
const resolvedProjectPath = path.resolve(projectPath);
|
||||||
type: "text",
|
const contractProjectType = await detect(resolvedProjectPath, {});
|
||||||
name: "path",
|
|
||||||
message: CREATE_MESSAGES.projectName,
|
|
||||||
initial: options.template || defaultName,
|
|
||||||
format: (name: string) => name.toLowerCase(),
|
|
||||||
validate: (name: string) => {
|
|
||||||
const validation = validateNpmName(
|
|
||||||
path.basename(path.resolve(name.toLowerCase())),
|
|
||||||
);
|
|
||||||
if (validation.valid) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return "Invalid project name: " + validation.problems?.[0];
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (typeof res.path === "string") {
|
|
||||||
projectPath = res.path.trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!projectPath) {
|
|
||||||
console.log(
|
|
||||||
"\nPlease specify the project directory:\n" +
|
|
||||||
` ${chalk.cyan("npx thirdweb create")} ${chalk.green(
|
|
||||||
"<project-directory>",
|
|
||||||
)}\n` +
|
|
||||||
"For example:\n" +
|
|
||||||
` ${chalk.cyan("npx thirdweb create")} ${chalk.green(
|
|
||||||
"my-thirdweb-app",
|
|
||||||
)}\n\n` +
|
|
||||||
`Run ${chalk.cyan("npx thirdweb --help")} to see all options.`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!options.template) {
|
|
||||||
if (projectType === "app" && !framework) {
|
|
||||||
const res = await prompts({
|
|
||||||
type: "select",
|
|
||||||
name: "framework",
|
|
||||||
message: CREATE_MESSAGES.framework,
|
|
||||||
choices: [
|
|
||||||
{ title: "Next.js", value: "next" },
|
|
||||||
{ title: "Create React App", value: "cra" },
|
|
||||||
{ title: "Vite", value: "vite" },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (typeof res.framework === "string") {
|
|
||||||
framework = res.framework.trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (projectType === "app" && !language) {
|
|
||||||
const res = await prompts({
|
|
||||||
type: "select",
|
|
||||||
name: "language",
|
|
||||||
message: CREATE_MESSAGES.language,
|
|
||||||
choices: [
|
|
||||||
{ title: "JavaScript", value: "javascript" },
|
|
||||||
{ title: "TypeScript", value: "typescript" },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
if (typeof res.language === "string") {
|
|
||||||
language = res.language.trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
projectType === "contract" &&
|
contractProjectType === "foundry" &&
|
||||||
framework !== "forge" &&
|
fs.existsSync(path.join(resolvedProjectPath, "src"))
|
||||||
framework !== "hardhat"
|
|
||||||
) {
|
) {
|
||||||
|
onlyContract = true;
|
||||||
|
projectPath = path.join(projectPath, "src");
|
||||||
|
} else if (contractProjectType === "hardhat") {
|
||||||
|
if (fs.existsSync(path.join(resolvedProjectPath, "contracts"))) {
|
||||||
|
onlyContract = true;
|
||||||
|
projectPath = path.join(projectPath, "contracts");
|
||||||
|
} else {
|
||||||
|
// If there's no expected contracts folder, check for a directory that has .sol files
|
||||||
|
const directories = fs
|
||||||
|
.readdirSync(resolvedProjectPath)
|
||||||
|
.filter((file) =>
|
||||||
|
fs.lstatSync(path.join(resolvedProjectPath, file)).isDirectory(),
|
||||||
|
);
|
||||||
|
for (const directory of directories) {
|
||||||
|
const files = fs.readdirSync(path.join(projectPath, directory));
|
||||||
|
if (files.some((file) => file.endsWith(".sol"))) {
|
||||||
|
onlyContract = true;
|
||||||
|
projectPath = path.join(projectPath, directory);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!onlyContract) {
|
||||||
|
if (!projectPath) {
|
||||||
|
const defaultName =
|
||||||
|
projectType === "contract" ? "thirdweb-contracts" : "thirdweb-app";
|
||||||
const res = await prompts({
|
const res = await prompts({
|
||||||
type: "select",
|
type: "text",
|
||||||
name: "framework",
|
name: "path",
|
||||||
message: CREATE_MESSAGES.framework,
|
message: CREATE_MESSAGES.projectName,
|
||||||
choices: [
|
initial: options.template || defaultName,
|
||||||
{ title: "Hardhat", value: "hardhat" },
|
format: (name: string) => name.toLowerCase(),
|
||||||
{ title: "Forge", value: "forge" },
|
validate: (name: string) => {
|
||||||
],
|
const validation = validateNpmName(
|
||||||
|
path.basename(path.resolve(name.toLowerCase())),
|
||||||
|
);
|
||||||
|
if (validation.valid) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return "Invalid project name: " + validation.problems?.[0];
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (typeof res.framework === "string") {
|
if (typeof res.path === "string") {
|
||||||
framework = res.framework.trim();
|
projectPath = path.join(projectPath, res.path.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!projectPath) {
|
||||||
|
console.log(
|
||||||
|
"\nPlease specify the project directory:\n" +
|
||||||
|
` ${chalk.cyan("npx thirdweb create")} ${chalk.green(
|
||||||
|
"<project-directory>",
|
||||||
|
)}\n` +
|
||||||
|
"For example:\n" +
|
||||||
|
` ${chalk.cyan("npx thirdweb create")} ${chalk.green(
|
||||||
|
"my-thirdweb-app",
|
||||||
|
)}\n\n` +
|
||||||
|
`Run ${chalk.cyan("npx thirdweb --help")} to see all options.`,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!options.template) {
|
||||||
|
if (projectType === "app" && !chain) {
|
||||||
|
const res = await prompts({
|
||||||
|
type: "select",
|
||||||
|
name: "chain",
|
||||||
|
message: CREATE_MESSAGES.chain,
|
||||||
|
choices: [
|
||||||
|
{ title: "EVM", value: "evm" },
|
||||||
|
{ title: "Solana", value: "solana" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.chain === "solana") {
|
||||||
|
chain = "solana";
|
||||||
|
} else {
|
||||||
|
chain = "evm";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (projectType === "app" && !framework) {
|
||||||
|
const res = await prompts({
|
||||||
|
type: "select",
|
||||||
|
name: "framework",
|
||||||
|
message: CREATE_MESSAGES.framework,
|
||||||
|
choices:
|
||||||
|
// Solana doesn't support Vite just yet:
|
||||||
|
chain === "solana"
|
||||||
|
? [
|
||||||
|
{ title: "Next.js", value: "next" },
|
||||||
|
{ title: "Create React App", value: "cra" },
|
||||||
|
// { title: "Vite", value: "vite" },
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{ title: "Next.js", value: "next" },
|
||||||
|
{ title: "Create React App", value: "cra" },
|
||||||
|
{ title: "Vite", value: "vite" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typeof res.framework === "string") {
|
||||||
|
framework = res.framework.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (projectType === "app" && !language) {
|
||||||
|
const res = await prompts({
|
||||||
|
type: "select",
|
||||||
|
name: "language",
|
||||||
|
message: CREATE_MESSAGES.language,
|
||||||
|
choices: [
|
||||||
|
{ title: "JavaScript", value: "javascript" },
|
||||||
|
{ title: "TypeScript", value: "typescript" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typeof res.language === "string") {
|
||||||
|
language = res.language.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
projectType === "contract" &&
|
||||||
|
framework !== "forge" &&
|
||||||
|
framework !== "hardhat"
|
||||||
|
) {
|
||||||
|
const res = await prompts({
|
||||||
|
type: "select",
|
||||||
|
name: "framework",
|
||||||
|
message: CREATE_MESSAGES.framework,
|
||||||
|
choices: [
|
||||||
|
{ title: "Hardhat", value: "hardhat" },
|
||||||
|
{ title: "Forge", value: "forge" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typeof res.framework === "string") {
|
||||||
|
framework = res.framework.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!framework) {
|
||||||
|
console.log("Please specify a framework");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!language) {
|
||||||
|
// Default = JavaScript
|
||||||
|
language = "javascript";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (projectType === "contract") {
|
||||||
|
// Select contract name
|
||||||
|
if (!contractName) {
|
||||||
|
const defaultName = "MyContract";
|
||||||
|
const res = await prompts({
|
||||||
|
type: "text",
|
||||||
|
name: "path",
|
||||||
|
message: CREATE_MESSAGES.contractName,
|
||||||
|
initial: defaultName,
|
||||||
|
validate: (name: string) => {
|
||||||
|
const isValid = /(^[a-z0-9A-Z]+$)|(^[a-z0-9A-Z]+\.sol$)/.test(name);
|
||||||
|
if (isValid) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `Invalid contract name 'contractName' (only alphanumeric characters allowed)`;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typeof res.path === "string") {
|
||||||
|
contractName = res.path.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!contractName) {
|
||||||
|
console.log(
|
||||||
|
"\nPlease specify the contract name:\n" +
|
||||||
|
` ${chalk.cyan(
|
||||||
|
"npx thirdweb create --contract --name",
|
||||||
|
)} ${chalk.green("<contract-name>")}\n` +
|
||||||
|
"For example:\n" +
|
||||||
|
` ${chalk.cyan(
|
||||||
|
"npx thirdweb create --contract --name",
|
||||||
|
)} ${chalk.green("MyContract")}\n\n` +
|
||||||
|
`Run ${chalk.cyan("npx thirdweb --help")} to see all options.`,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +319,9 @@ export async function twCreate(pPath: string = "", options: any) {
|
|||||||
name: "standard",
|
name: "standard",
|
||||||
message: CREATE_MESSAGES.contract,
|
message: CREATE_MESSAGES.contract,
|
||||||
choices: [
|
choices: [
|
||||||
{ title: "Empty Contract", value: "none" },
|
...(!onlyContract
|
||||||
|
? [{ title: "Empty Contract", value: "none" }]
|
||||||
|
: []),
|
||||||
{ title: "ERC721", value: "erc721" },
|
{ title: "ERC721", value: "erc721" },
|
||||||
{ title: "ERC20", value: "erc20" },
|
{ title: "ERC20", value: "erc20" },
|
||||||
{ title: "ERC1155", value: "erc1155" },
|
{ title: "ERC1155", value: "erc1155" },
|
||||||
@@ -238,20 +375,11 @@ export async function twCreate(pPath: string = "", options: any) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!framework) {
|
|
||||||
console.log("Please specify a framework");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!language) {
|
|
||||||
// Default = JavaScript
|
|
||||||
language = "javascript";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedProjectPath = path.resolve(projectPath);
|
// Resolve project path
|
||||||
const projectName = path.basename(resolvedProjectPath);
|
projectPath = path.resolve(projectPath);
|
||||||
|
const projectName = path.basename(projectPath);
|
||||||
|
|
||||||
const { valid, problems } = validateNpmName(projectName);
|
const { valid, problems } = validateNpmName(projectName);
|
||||||
if (!valid) {
|
if (!valid) {
|
||||||
@@ -283,18 +411,21 @@ export async function twCreate(pPath: string = "", options: any) {
|
|||||||
try {
|
try {
|
||||||
if (projectType === "app") {
|
if (projectType === "app") {
|
||||||
await createApp({
|
await createApp({
|
||||||
appPath: resolvedProjectPath,
|
appPath: projectPath,
|
||||||
packageManager,
|
packageManager,
|
||||||
framework,
|
framework,
|
||||||
language,
|
language,
|
||||||
template,
|
template,
|
||||||
|
chain,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await createContract({
|
await createContractProject({
|
||||||
contractPath: resolvedProjectPath,
|
contractPath: projectPath,
|
||||||
packageManager,
|
packageManager,
|
||||||
framework,
|
framework,
|
||||||
|
contractName,
|
||||||
baseContract,
|
baseContract,
|
||||||
|
onlyContract,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
|
|||||||
@@ -22,12 +22,14 @@ export async function createApp({
|
|||||||
framework,
|
framework,
|
||||||
language,
|
language,
|
||||||
template,
|
template,
|
||||||
|
chain,
|
||||||
}: {
|
}: {
|
||||||
appPath: string;
|
appPath: string;
|
||||||
packageManager: PackageManager;
|
packageManager: PackageManager;
|
||||||
framework?: string;
|
framework?: string;
|
||||||
language?: string;
|
language?: string;
|
||||||
template?: string;
|
template?: string;
|
||||||
|
chain?: string;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
let frameworkPath = "";
|
let frameworkPath = "";
|
||||||
|
|
||||||
@@ -43,7 +45,9 @@ export async function createApp({
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
} else if (framework) {
|
} else if (framework) {
|
||||||
frameworkPath = `${framework}-${language || "javascript"}-starter`;
|
frameworkPath = `${framework}-${language || "javascript"}-${
|
||||||
|
chain === "solana" ? "solana-" : ""
|
||||||
|
}starter`;
|
||||||
const found = await hasTemplate(frameworkPath);
|
const found = await hasTemplate(frameworkPath);
|
||||||
|
|
||||||
if (!found) {
|
if (!found) {
|
||||||
|
|||||||
@@ -11,22 +11,28 @@ import { submodules } from "./submodules";
|
|||||||
import { downloadAndExtractRepo } from "./templates";
|
import { downloadAndExtractRepo } from "./templates";
|
||||||
import retry from "async-retry";
|
import retry from "async-retry";
|
||||||
import chalk from "chalk";
|
import chalk from "chalk";
|
||||||
|
import fs from "fs";
|
||||||
import { writeFile } from "fs/promises";
|
import { writeFile } from "fs/promises";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
|
|
||||||
interface ICreateContract {
|
interface ICreateContractProject {
|
||||||
contractPath: string;
|
contractPath: string;
|
||||||
packageManager: PackageManager;
|
packageManager: PackageManager;
|
||||||
|
contractName: string;
|
||||||
framework?: string;
|
framework?: string;
|
||||||
baseContract?: string;
|
baseContract?: string;
|
||||||
|
onlyContract: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createContract({
|
export async function createContractProject({
|
||||||
contractPath,
|
contractPath,
|
||||||
packageManager,
|
packageManager,
|
||||||
framework,
|
framework,
|
||||||
|
contractName,
|
||||||
baseContract,
|
baseContract,
|
||||||
}: ICreateContract) {
|
onlyContract,
|
||||||
|
}: ICreateContractProject) {
|
||||||
|
// Check that the selected base contract is valid
|
||||||
if (baseContract) {
|
if (baseContract) {
|
||||||
const found = hasBaseContract(baseContract);
|
const found = hasBaseContract(baseContract);
|
||||||
|
|
||||||
@@ -40,8 +46,8 @@ export async function createContract({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check that we have write permission for the specified directory
|
||||||
const root = path.resolve(contractPath);
|
const root = path.resolve(contractPath);
|
||||||
|
|
||||||
if (!(await isWriteable(path.dirname(root)))) {
|
if (!(await isWriteable(path.dirname(root)))) {
|
||||||
console.error(
|
console.error(
|
||||||
"The application path is not writable, please check folder permissions and try again.",
|
"The application path is not writable, please check folder permissions and try again.",
|
||||||
@@ -52,117 +58,165 @@ export async function createContract({
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const projectName = path.basename(root);
|
// Check that the contract name is valid
|
||||||
|
if (!/(^[a-z0-9A-Z]+$)|(^[a-z0-9A-Z]+\.sol$)/.test(contractName)) {
|
||||||
await makeDir(root);
|
console.error(
|
||||||
if (!isFolderEmpty(root, projectName)) {
|
`Contract name ${chalk.red(
|
||||||
|
`"${contractName}"`,
|
||||||
|
)} is not valid (only alphanumeric characters are allowed).`,
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clean the contract name
|
||||||
|
contractName = contractName.replace(/\.sol$/, "") + ".sol";
|
||||||
|
|
||||||
const useYarn = packageManager === "yarn";
|
const useYarn = packageManager === "yarn";
|
||||||
const isOnline = !useYarn || (await getOnline());
|
|
||||||
const originalDirectory = process.cwd();
|
|
||||||
|
|
||||||
console.log(
|
if (onlyContract) {
|
||||||
`Creating a new thirdweb contracts project in ${chalk.green(root)}.`,
|
// If we are already in a contracts project, just create a new contract
|
||||||
);
|
if (fs.existsSync(path.join(root, contractName))) {
|
||||||
console.log();
|
console.error(
|
||||||
|
`A contract with the name ${chalk.red(
|
||||||
process.chdir(root);
|
`"${contractName}"`,
|
||||||
|
)} already exists in specified directory.`,
|
||||||
function isErrorLike(err: unknown): err is { message: string } {
|
);
|
||||||
return (
|
|
||||||
typeof err === "object" &&
|
|
||||||
err !== null &&
|
|
||||||
typeof (err as { message?: unknown }).message === "string"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log(`Downloading files. This might take a moment.`);
|
|
||||||
|
|
||||||
let starter = "";
|
|
||||||
if (framework === "hardhat") {
|
|
||||||
starter = "hardhat-javascript-starter";
|
|
||||||
} else if (framework === "forge") {
|
|
||||||
starter = "forge-starter";
|
|
||||||
} else {
|
|
||||||
console.error("Please provide a valid contracts framework.");
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
await retry(
|
|
||||||
() => downloadAndExtractRepo(root, { name: starter, filePath: "" }),
|
|
||||||
{
|
|
||||||
retries: 3,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// Modify the /contracts/MyContract.sol contents to match the base contract
|
|
||||||
if (baseContract && baseContract.length > 0) {
|
if (baseContract && baseContract.length > 0) {
|
||||||
const baseContractText = readBaseContract(baseContract);
|
const baseContractText = readBaseContract(baseContract);
|
||||||
|
|
||||||
// Set the contents of the Contract.sol file to the base contract
|
// Set the contents of the Contract.sol file to the base contract
|
||||||
let contractFile = "";
|
let contractFile = "";
|
||||||
if (framework === "hardhat") {
|
contractFile = path.join(root, contractName);
|
||||||
contractFile = path.join(root, "contracts", "Contract.sol");
|
|
||||||
}
|
|
||||||
if (framework === "forge") {
|
|
||||||
contractFile = path.join(root, "src", "Contract.sol");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write the base contract to the MyContract.sol file
|
// Write the base contract to the MyContract.sol file
|
||||||
await writeFile(contractFile, baseContractText);
|
await writeFile(contractFile, baseContractText);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`${chalk.green("Success!")} Created ${contractName} at ${contractPath}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (reason) {
|
} else {
|
||||||
throw new DownloadError(
|
// Otherwise, create a new contracts project
|
||||||
isErrorLike(reason) ? reason.message : String(reason),
|
const projectName = path.basename(root);
|
||||||
|
|
||||||
|
await makeDir(root);
|
||||||
|
if (!isFolderEmpty(root, projectName)) {
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isOnline = !useYarn || (await getOnline());
|
||||||
|
const originalDirectory = process.cwd();
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Creating a new thirdweb contracts project in ${chalk.green(root)}.`,
|
||||||
);
|
);
|
||||||
}
|
console.log();
|
||||||
|
|
||||||
console.log("Installing packages. This might take a couple of minutes.");
|
process.chdir(root);
|
||||||
console.log();
|
|
||||||
|
|
||||||
await install(root, null, { packageManager, isOnline });
|
function isErrorLike(err: unknown): err is { message: string } {
|
||||||
console.log();
|
return (
|
||||||
|
typeof err === "object" &&
|
||||||
|
err !== null &&
|
||||||
|
typeof (err as { message?: unknown }).message === "string"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (tryGitInit(root)) {
|
try {
|
||||||
console.log("Initialized a git repository.");
|
console.log(`Downloading files. This might take a moment.`);
|
||||||
|
|
||||||
|
let starter = "";
|
||||||
|
if (framework === "hardhat") {
|
||||||
|
starter = "hardhat-javascript-starter";
|
||||||
|
} else if (framework === "forge") {
|
||||||
|
starter = "forge-starter";
|
||||||
|
} else {
|
||||||
|
console.error("Please provide a valid contracts framework.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
await retry(
|
||||||
|
() => downloadAndExtractRepo(root, { name: starter, filePath: "" }),
|
||||||
|
{
|
||||||
|
retries: 3,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add in a new contracts file with specific base contract
|
||||||
|
if (baseContract && baseContract.length > 0) {
|
||||||
|
const baseContractText = readBaseContract(baseContract);
|
||||||
|
|
||||||
|
// Set the filename of the new file and delete the dummy Contract.sol file
|
||||||
|
let contractFile = "";
|
||||||
|
if (framework === "hardhat") {
|
||||||
|
fs.unlinkSync(path.join(root, "contracts", "Contract.sol"));
|
||||||
|
contractFile = path.join(root, "contracts", contractName);
|
||||||
|
}
|
||||||
|
if (framework === "forge") {
|
||||||
|
fs.unlinkSync(path.join(root, "src", "Contract.sol"));
|
||||||
|
contractFile = path.join(root, "src", contractName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the base contract to the new file
|
||||||
|
await writeFile(contractFile, baseContractText);
|
||||||
|
}
|
||||||
|
} catch (reason) {
|
||||||
|
throw new DownloadError(
|
||||||
|
isErrorLike(reason) ? reason.message : String(reason),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Installing packages. This might take a couple of minutes.");
|
||||||
|
console.log();
|
||||||
|
|
||||||
|
await install(root, null, { packageManager, isOnline });
|
||||||
|
console.log();
|
||||||
|
|
||||||
|
if (tryGitInit(root)) {
|
||||||
|
console.log("Initialized a git repository.");
|
||||||
|
console.log();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (framework === "forge") {
|
||||||
|
await submodules();
|
||||||
|
}
|
||||||
|
|
||||||
|
let cdpath: string;
|
||||||
|
if (path.join(originalDirectory, projectName) === contractPath) {
|
||||||
|
cdpath = projectName;
|
||||||
|
} else {
|
||||||
|
cdpath = contractPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`${chalk.green("Success!")} Created ${projectName} at ${contractPath}`,
|
||||||
|
);
|
||||||
|
console.log();
|
||||||
|
console.log("Inside that directory, you can run several commands:");
|
||||||
|
console.log();
|
||||||
|
console.log(
|
||||||
|
chalk.cyan(` ${packageManager}${useYarn ? "" : " run"} build`),
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
" Compiles your contracts and detects thirdweb extensions implemented on them.",
|
||||||
|
);
|
||||||
|
console.log();
|
||||||
|
console.log(
|
||||||
|
chalk.cyan(` ${packageManager}${useYarn ? "" : " run"} deploy`),
|
||||||
|
);
|
||||||
|
console.log(" Deploys your contracts with the thirdweb deploy flow.");
|
||||||
|
console.log();
|
||||||
|
console.log(
|
||||||
|
chalk.cyan(` ${packageManager}${useYarn ? "" : " run"} release`),
|
||||||
|
);
|
||||||
|
console.log(" Releases your contracts with the thirdweb release flow.");
|
||||||
|
console.log();
|
||||||
|
console.log("We suggest that you begin by typing:");
|
||||||
|
console.log();
|
||||||
|
console.log(chalk.cyan(" cd"), cdpath);
|
||||||
console.log();
|
console.log();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (framework === "forge") {
|
|
||||||
await submodules();
|
|
||||||
}
|
|
||||||
|
|
||||||
let cdpath: string;
|
|
||||||
if (path.join(originalDirectory, projectName) === contractPath) {
|
|
||||||
cdpath = projectName;
|
|
||||||
} else {
|
|
||||||
cdpath = contractPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`${chalk.green("Success!")} Created ${projectName} at ${contractPath}`,
|
|
||||||
);
|
|
||||||
console.log();
|
|
||||||
console.log("Inside that directory, you can run several commands:");
|
|
||||||
console.log();
|
|
||||||
console.log(chalk.cyan(` ${packageManager}${useYarn ? "" : " run"} build`));
|
|
||||||
console.log(
|
|
||||||
" Compiles your contracts and detects thirdweb extensions implemented on them.",
|
|
||||||
);
|
|
||||||
console.log();
|
|
||||||
console.log(chalk.cyan(` ${packageManager}${useYarn ? "" : " run"} deploy`));
|
|
||||||
console.log(" Deploys your contracts with the thirdweb deploy flow.");
|
|
||||||
console.log();
|
|
||||||
console.log(
|
|
||||||
chalk.cyan(` ${packageManager}${useYarn ? "" : " run"} release`),
|
|
||||||
);
|
|
||||||
console.log(" Releases your contracts with the thirdweb release flow.");
|
|
||||||
console.log();
|
|
||||||
console.log("We suggest that you begin by typing:");
|
|
||||||
console.log();
|
|
||||||
console.log(chalk.cyan(" cd"), cdpath);
|
|
||||||
console.log();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,26 @@
|
|||||||
import spawn from "cross-spawn";
|
import spawn from "cross-spawn";
|
||||||
|
|
||||||
export async function runCommand(command: string, args: string[]) {
|
export async function runCommand(
|
||||||
|
command: string,
|
||||||
|
args: string[],
|
||||||
|
logging: boolean = false,
|
||||||
|
) {
|
||||||
return new Promise<void>((resolve, reject) => {
|
return new Promise<void>((resolve, reject) => {
|
||||||
/**
|
/**
|
||||||
* Spawn the installation process.
|
* Spawn the installation process.
|
||||||
*/
|
*/
|
||||||
const child = spawn(command, args);
|
const child = spawn(command, args);
|
||||||
|
child.stdout?.on("data", (data) => {
|
||||||
|
if (logging) {
|
||||||
|
console.log(data.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stderr?.on("error", (err) => {
|
||||||
|
if (logging) {
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
child.on("close", (code) => {
|
child.on("close", (code) => {
|
||||||
if (code !== 0) {
|
if (code !== 0) {
|
||||||
reject({ command: `${command}` });
|
reject({ command: `${command}` });
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import NPMDetector from "../core/detection/npm";
|
||||||
|
import ViteDetector from "../core/detection/vite";
|
||||||
|
import YarnDetector from "../core/detection/yarn";
|
||||||
|
import { runCommand } from "../create/helpers/run-command";
|
||||||
|
import { upload } from "../storage/command";
|
||||||
|
import { DEFAULT_IPFS_GATEWAY } from "@thirdweb-dev/sdk";
|
||||||
|
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
||||||
|
|
||||||
|
export async function deployApp(distPath = "dist", projectPath = ".") {
|
||||||
|
const storage = new ThirdwebStorage();
|
||||||
|
const supportedFrameworks = [new ViteDetector()];
|
||||||
|
|
||||||
|
const possibleProjects = supportedFrameworks
|
||||||
|
.filter((detector) => detector.matches(projectPath))
|
||||||
|
.map((detector) => detector.projectType);
|
||||||
|
|
||||||
|
const hasYarn = new YarnDetector().matches(".");
|
||||||
|
const hasNPM = new NPMDetector().matches(".");
|
||||||
|
|
||||||
|
if (possibleProjects.length === 0) {
|
||||||
|
throw new Error("No supported project detected");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (hasYarn) {
|
||||||
|
await runCommand("yarn", ["build"]);
|
||||||
|
} else if (hasNPM) {
|
||||||
|
await runCommand("npm", ["build"]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Can't build project");
|
||||||
|
return Promise.reject("Can't build project");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let url = await upload(storage, distPath);
|
||||||
|
url = url.replace("ipfs://", DEFAULT_IPFS_GATEWAY);
|
||||||
|
return `${url}/index.html`;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Can't upload project");
|
||||||
|
return Promise.reject("Can't upload project");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { processProject } from "../common/processor";
|
||||||
|
import { info, logger } from "../core/helpers/logger";
|
||||||
|
import generateDashboardUrl from "../helpers/generate-dashboard-url";
|
||||||
|
import { deployApp } from "./app";
|
||||||
|
import chalk from "chalk";
|
||||||
|
|
||||||
|
type DeployOptions = {
|
||||||
|
name: string;
|
||||||
|
contractVersion: string;
|
||||||
|
app: boolean;
|
||||||
|
path?: string;
|
||||||
|
distPath?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function deploy(options: DeployOptions) {
|
||||||
|
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: ${chalk.blueBright(url)}`);
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.app) {
|
||||||
|
try {
|
||||||
|
let url = await deployApp(options.distPath, options.path);
|
||||||
|
info(`Here is the link to your app: ${chalk.blueBright(url.toString())}`);
|
||||||
|
return url.toString();
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("Failed to deploy app, No compatible project found", err);
|
||||||
|
return Promise.reject(
|
||||||
|
"failed to deploy app, no compatible project found",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = await processProject(options, "deploy");
|
||||||
|
info(
|
||||||
|
`Open this link to deploy your contracts: ${chalk.blueBright(
|
||||||
|
url.toString(),
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
@@ -13,18 +13,18 @@ export default function generateDashboardUrl(
|
|||||||
// Pre-built contract
|
// Pre-built contract
|
||||||
else {
|
else {
|
||||||
const mapping = {
|
const mapping = {
|
||||||
"signature-drop": "drop/signature-drop",
|
"signature-drop": "SignatureDrop",
|
||||||
"nft-drop": "drop/nft-drop",
|
"nft-drop": "DropERC721",
|
||||||
"edition-drop": "drop/edition-drop",
|
"edition-drop": "DropERC1155",
|
||||||
"nft-collection": "token/nft-collection",
|
"nft-collection": "TokenERC721",
|
||||||
edition: "token/edition",
|
edition: "TokenERC1155",
|
||||||
"token-drop": "drop/token-drop",
|
"token-drop": "DropERC20",
|
||||||
token: "token/token",
|
token: "TokenERC20",
|
||||||
marketplace: "marketplace/marketplace",
|
marketplace: "Marketplace",
|
||||||
split: "governance/split",
|
split: "Split",
|
||||||
vote: "governance/vote",
|
vote: "VoteERC20",
|
||||||
pack: "token/pack",
|
pack: "Pack",
|
||||||
multiwrap: "token/multiwrap",
|
multiwrap: "Multiwrap",
|
||||||
};
|
};
|
||||||
|
|
||||||
const foundMapping = mapping[name as keyof typeof mapping];
|
const foundMapping = mapping[name as keyof typeof mapping];
|
||||||
@@ -33,6 +33,6 @@ export default function generateDashboardUrl(
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `https://thirdweb.com/contracts/new/pre-built/${foundMapping}`;
|
return `https://thirdweb.com/thirdweb.eth/${foundMapping}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { logger } from "../core/helpers/logger";
|
|
||||||
import { spinner } from "../core/helpers/logger";
|
import { spinner } from "../core/helpers/logger";
|
||||||
import { BufferOrStringWithName, ThirdwebStorage } from "@thirdweb-dev/storage";
|
import { BufferOrStringWithName, ThirdwebStorage } from "@thirdweb-dev/storage";
|
||||||
import chalk from "chalk";
|
|
||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
|
|
||||||
@@ -33,22 +31,12 @@ export async function upload(
|
|||||||
uploadPath: string,
|
uploadPath: string,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
if (!uploadPath) {
|
if (!uploadPath) {
|
||||||
logger.error(
|
return Promise.reject("No path provided");
|
||||||
`Please pass a path to a file or directory to upload with the following format:\n ${chalk.blueBright(
|
|
||||||
`npx thirdweb@latest upload path/to/file.jpg`,
|
|
||||||
)}\n`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const pathExists = fs.existsSync(uploadPath);
|
const pathExists = fs.existsSync(uploadPath);
|
||||||
if (!pathExists) {
|
if (!pathExists) {
|
||||||
logger.error(
|
return Promise.reject("Invalid path provided");
|
||||||
`Invalid path ${chalk.blueBright(
|
|
||||||
uploadPath,
|
|
||||||
)} provided. Please provide a valid path to a file or directory to upload."`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let uri = "";
|
let uri = "";
|
||||||
@@ -57,12 +45,7 @@ export async function upload(
|
|||||||
const files = recurseFiles(uploadPath, uploadPath);
|
const files = recurseFiles(uploadPath, uploadPath);
|
||||||
|
|
||||||
if (files.length === 0) {
|
if (files.length === 0) {
|
||||||
logger.error(
|
return Promise.reject("No files detected in specified directory");
|
||||||
`No files detected in specified directory ${chalk.blueBright(
|
|
||||||
uploadPath,
|
|
||||||
)} to upload.`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const spin = spinner(
|
const spin = spinner(
|
||||||
@@ -82,12 +65,7 @@ export async function upload(
|
|||||||
uri = await storage.upload(file, { uploadWithoutDirectory: true });
|
uri = await storage.upload(file, { uploadWithoutDirectory: true });
|
||||||
spin.succeed("Succesfully uploaded file to IPFS.");
|
spin.succeed("Succesfully uploaded file to IPFS.");
|
||||||
} else {
|
} else {
|
||||||
logger.error(
|
return Promise.reject("Invalid path provided");
|
||||||
`Path ${chalk.blueBright(
|
|
||||||
uploadPath,
|
|
||||||
)} does not point to a valid file or directory. Please provide a valid path to a file or directory to upload`,
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return uri;
|
return uri;
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
# @thirdweb-dev/contracts-js
|
# @thirdweb-dev/contracts-js
|
||||||
|
|
||||||
|
## 1.2.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#438](https://github.com/thirdweb-dev/js/pull/438) [`f451da6`](https://github.com/thirdweb-dev/js/commit/f451da6395689a5f89800ee63f34b6175b61f703) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix SigMint detection for OSRF NFT Collection contracts
|
||||||
|
|
||||||
## 1.2.1
|
## 1.2.1
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
{
|
{
|
||||||
"name": "@thirdweb-dev/contracts-js",
|
"name": "@thirdweb-dev/contracts-js",
|
||||||
"version": "1.2.1",
|
"version": "1.2.2",
|
||||||
"main": "dist/thirdweb-dev-contracts-js.cjs.js",
|
"main": "dist/thirdweb-dev-contracts-js.cjs.js",
|
||||||
"module": "dist/thirdweb-dev-contracts-js.esm.js",
|
"module": "dist/thirdweb-dev-contracts-js.esm.js",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/contracts-js",
|
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/contracts-js",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@thirdweb-dev/contracts": "^3.2.2"
|
"@thirdweb-dev/contracts": "3.2.8-0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/preset-env": "^7.18.10",
|
"@babel/preset-env": "^7.18.10",
|
||||||
"@babel/preset-typescript": "^7.18.6",
|
"@babel/preset-typescript": "^7.18.6",
|
||||||
"@preconstruct/cli": "^2.2.1",
|
"@preconstruct/cli": "^2.2.1",
|
||||||
"@typechain/ethers-v5": "10.0.0",
|
"@typechain/ethers-v5": "10.0.0",
|
||||||
"ethers": "^5.7.0",
|
"ethers": "^5.7.2",
|
||||||
"typechain": "^8.1.0",
|
"typechain": "^8.1.0",
|
||||||
"typescript": "^4.7.4"
|
"typescript": "^4.7.4"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
||||||
"@typescript-eslint/parser": "^5.33.0",
|
"@typescript-eslint/parser": "^5.33.0",
|
||||||
"eslint-config-next": "^12.0.8",
|
"eslint-config-next": "12.3.1",
|
||||||
"eslint-config-prettier": "^8.3.0",
|
"eslint-config-prettier": "^8.3.0",
|
||||||
"eslint-config-turbo": "latest",
|
"eslint-config-turbo": "latest",
|
||||||
"eslint-plugin-react": "^7.28.0"
|
"eslint-plugin-react": "^7.28.0"
|
||||||
|
|||||||
@@ -1,5 +1,29 @@
|
|||||||
# @thirdweb-dev/react
|
# @thirdweb-dev/react
|
||||||
|
|
||||||
|
## 3.6.4
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#425](https://github.com/thirdweb-dev/js/pull/425) [`f545a67`](https://github.com/thirdweb-dev/js/commit/f545a67e9fb597d27bb39ca515d24d306fbb121a) Thanks [@adam-maj](https://github.com/adam-maj)! - Add sameSite none and include credentials
|
||||||
|
|
||||||
|
- [#420](https://github.com/thirdweb-dev/js/pull/420) [`639e535`](https://github.com/thirdweb-dev/js/commit/639e535ed55280ad9d081001aab3f5af72bb3e45) Thanks [@jnsdls](https://github.com/jnsdls)! - update deps
|
||||||
|
|
||||||
|
## 3.6.3
|
||||||
|
|
||||||
|
## 3.6.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#405](https://github.com/thirdweb-dev/js/pull/405) [`ccb7db4`](https://github.com/thirdweb-dev/js/commit/ccb7db48739b8dddcb2c032b3b6e3e5200485715) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add updateAll param to creators and royalty update hooks for Solana
|
||||||
|
|
||||||
|
## 3.6.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#392](https://github.com/thirdweb-dev/js/pull/392) [`846022e`](https://github.com/thirdweb-dev/js/commit/846022e2cfb12b846aae029b85899fb72fd2c9ad) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Fix unlimited price for useActiveClaimConditionForWallet
|
||||||
|
|
||||||
|
- [#388](https://github.com/thirdweb-dev/js/pull/388) [`7c0744a`](https://github.com/thirdweb-dev/js/commit/7c0744a006e78987ad8b271b2c64f4bac7759510) Thanks [@adam-maj](https://github.com/adam-maj)! - Add support for total supply and pagination on get all
|
||||||
|
|
||||||
## 3.6.0
|
## 3.6.0
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@thirdweb-dev/react",
|
"name": "@thirdweb-dev/react",
|
||||||
"version": "3.6.0",
|
"version": "3.6.4",
|
||||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
|
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
|
||||||
"author": "thirdweb eng <[email protected]>",
|
"author": "thirdweb eng <[email protected]>",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
@@ -62,7 +62,7 @@
|
|||||||
},
|
},
|
||||||
"sideEffects:": false,
|
"sideEffects:": false,
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.18.10",
|
"@babel/core": "^7.19.3",
|
||||||
"@babel/preset-env": "^7.18.10",
|
"@babel/preset-env": "^7.18.10",
|
||||||
"@babel/preset-react": "^7.18.6",
|
"@babel/preset-react": "^7.18.6",
|
||||||
"@babel/preset-typescript": "^7.18.6",
|
"@babel/preset-typescript": "^7.18.6",
|
||||||
@@ -73,6 +73,7 @@
|
|||||||
"@preconstruct/cli": "^2.2.1",
|
"@preconstruct/cli": "^2.2.1",
|
||||||
"@solana/wallet-adapter-base": "^0.9.17",
|
"@solana/wallet-adapter-base": "^0.9.17",
|
||||||
"@solana/wallet-adapter-react": "^0.15.19",
|
"@solana/wallet-adapter-react": "^0.15.19",
|
||||||
|
"@solana/wallet-adapter-wallets": "^0.19.0",
|
||||||
"@solana/web3.js": "^1.62.0",
|
"@solana/web3.js": "^1.62.0",
|
||||||
"@thirdweb-dev/sdk": "*",
|
"@thirdweb-dev/sdk": "*",
|
||||||
"@types/color": "^3.0.3",
|
"@types/color": "^3.0.3",
|
||||||
@@ -87,7 +88,7 @@
|
|||||||
"eslint-plugin-inclusive-language": "^2.2.0",
|
"eslint-plugin-inclusive-language": "^2.2.0",
|
||||||
"eslint-plugin-prettier": "^4.2.1",
|
"eslint-plugin-prettier": "^4.2.1",
|
||||||
"eslint-plugin-tsdoc": "^0.2.16",
|
"eslint-plugin-tsdoc": "^0.2.16",
|
||||||
"ethers": "^5.7.1",
|
"ethers": "^5.7.2",
|
||||||
"prettier": "^2.7.1",
|
"prettier": "^2.7.1",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
|
|||||||
@@ -14,19 +14,19 @@ export const SupportedNetworkSelect: React.FC<SupportedNetworkSelectProps> = ({
|
|||||||
const deprecatedNetworks = useMemo(() => {
|
const deprecatedNetworks = useMemo(() => {
|
||||||
return SUPPORTED_CHAIN_IDS.map((supportedChain) => {
|
return SUPPORTED_CHAIN_IDS.map((supportedChain) => {
|
||||||
return getChainFromChainId(supportedChain);
|
return getChainFromChainId(supportedChain);
|
||||||
}).filter((n) => !!n.deprecated);
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const testnets = useMemo(() => {
|
const testnets = useMemo(() => {
|
||||||
return SUPPORTED_CHAIN_IDS.map((supportedChain) => {
|
return SUPPORTED_CHAIN_IDS.map((supportedChain) => {
|
||||||
return getChainFromChainId(supportedChain);
|
return getChainFromChainId(supportedChain);
|
||||||
}).filter((n) => n.testnet && !n.deprecated);
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const mainnets = useMemo(() => {
|
const mainnets = useMemo(() => {
|
||||||
return SUPPORTED_CHAIN_IDS.map((supportedChain) => {
|
return SUPPORTED_CHAIN_IDS.map((supportedChain) => {
|
||||||
return getChainFromChainId(supportedChain);
|
return getChainFromChainId(supportedChain);
|
||||||
}).filter((n) => !n.testnet && !n.deprecated);
|
});
|
||||||
}, []);
|
}, []);
|
||||||
return (
|
return (
|
||||||
<Select {...selectProps}>
|
<Select {...selectProps}>
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export interface ThirdwebNftMediaProps extends SharedMediaProps {
|
|||||||
/**
|
/**
|
||||||
* This component can be used to render NFTs from the thirdweb SDK.
|
* This component can be used to render NFTs from the thirdweb SDK.
|
||||||
* Props: {@link ThirdwebNftMediaProps}
|
* Props: {@link ThirdwebNftMediaProps}
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* ```jsx
|
* ```jsx
|
||||||
* import { ThirdwebNftMedia, useContract, useNFT } from "@thirdweb-dev/react";
|
* import { ThirdwebNftMedia, useContract, useNFT } from "@thirdweb-dev/react";
|
||||||
|
|||||||
@@ -103,7 +103,10 @@ export class GnosisSafeConnector extends Connector {
|
|||||||
import("@gnosis.pm/safe-ethers-lib"),
|
import("@gnosis.pm/safe-ethers-lib"),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const ethAdapter = new safeEthersLib.default({ ethers, signer });
|
const ethAdapter = new safeEthersLib.default({
|
||||||
|
ethers,
|
||||||
|
signerOrProvider: signer,
|
||||||
|
});
|
||||||
|
|
||||||
const safe = await safeCoreSdk.default.create({
|
const safe = await safeCoreSdk.default.create({
|
||||||
ethAdapter: ethAdapter as any,
|
ethAdapter: ethAdapter as any,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { NATIVE_TOKENS, SUPPORTED_CHAIN_ID } from "@thirdweb-dev/sdk";
|
|||||||
import { ChainId } from "@thirdweb-dev/sdk";
|
import { ChainId } from "@thirdweb-dev/sdk";
|
||||||
import type { Chain as WagmiChain } from "wagmi";
|
import type { Chain as WagmiChain } from "wagmi";
|
||||||
|
|
||||||
export type Chain = WagmiChain & { deprecated?: boolean };
|
export type Chain = WagmiChain;
|
||||||
const chain: Record<string, Chain> = {
|
const chain: Record<string, Chain> = {
|
||||||
mainnet: {
|
mainnet: {
|
||||||
id: ChainId.Mainnet,
|
id: ChainId.Mainnet,
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
convertToReadableQuantity,
|
convertToReadableQuantity,
|
||||||
fetchCurrencyMetadata,
|
fetchCurrencyMetadata,
|
||||||
} from "@thirdweb-dev/sdk";
|
} from "@thirdweb-dev/sdk";
|
||||||
import { BigNumberish, utils } from "ethers";
|
import { BigNumberish, constants, utils } from "ethers";
|
||||||
import invariant from "tiny-invariant";
|
import invariant from "tiny-invariant";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -411,7 +411,9 @@ export function useActiveClaimConditionForWallet(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const normalizedPrize = price
|
const normalizedPrize = price
|
||||||
? utils.parseUnits(price, currencyMetadata.decimals)
|
? price === "unlimited"
|
||||||
|
? constants.MaxUint256
|
||||||
|
: utils.parseUnits(price, currencyMetadata.decimals)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const priceWithOverride =
|
const priceWithOverride =
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ export function useUnclaimedNFTSupply(contract: RequiredParam<DropContract>) {
|
|||||||
invariant(erc721, "No ERC721 Contract instance provided");
|
invariant(erc721, "No ERC721 Contract instance provided");
|
||||||
return erc721.totalUnclaimedSupply();
|
return erc721.totalUnclaimedSupply();
|
||||||
}
|
}
|
||||||
invariant(false, "Contract is not an instance of ERC721")
|
invariant(false, "Contract is not an instance of ERC721");
|
||||||
},
|
},
|
||||||
{ enabled: !!erc721 },
|
{ enabled: !!erc721 },
|
||||||
);
|
);
|
||||||
@@ -129,7 +129,7 @@ export function useClaimedNFTSupply(contract: RequiredParam<DropContract>) {
|
|||||||
if (erc721) {
|
if (erc721) {
|
||||||
return erc721.totalClaimedSupply();
|
return erc721.totalClaimedSupply();
|
||||||
}
|
}
|
||||||
invariant(false, "Contract is not an instance of ERC721")
|
invariant(false, "Contract is not an instance of ERC721");
|
||||||
},
|
},
|
||||||
{ enabled: !!erc721 },
|
{ enabled: !!erc721 },
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -24,7 +24,9 @@ export function useUser() {
|
|||||||
authConfig,
|
authConfig,
|
||||||
"Please specify an authConfig in the ThirdwebProvider",
|
"Please specify an authConfig in the ThirdwebProvider",
|
||||||
);
|
);
|
||||||
const res = await fetch(`${authConfig.authUrl}/user`);
|
const res = await fetch(`${authConfig.authUrl}/user`, {
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
return (await res.json()) as ThirdwebAuthUser;
|
return (await res.json()) as ThirdwebAuthUser;
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -24,7 +24,9 @@ export function useUser() {
|
|||||||
authConfig,
|
authConfig,
|
||||||
"Please specify an authConfig in the ThirdwebProvider",
|
"Please specify an authConfig in the ThirdwebProvider",
|
||||||
);
|
);
|
||||||
const res = await fetch(`${authConfig.authUrl}/user`);
|
const res = await fetch(`${authConfig.authUrl}/user`, {
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
return (await res.json()) as ThirdwebAuthUser;
|
return (await res.json()) as ThirdwebAuthUser;
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -4,17 +4,22 @@ import {
|
|||||||
RequiredParam,
|
RequiredParam,
|
||||||
} from "../../../core/query-utils/required-param";
|
} from "../../../core/query-utils/required-param";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { QueryAllParams } from "@thirdweb-dev/sdk";
|
||||||
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
|
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
|
||||||
|
|
||||||
export function nftGetAllQuery(
|
export function nftGetAllQuery(
|
||||||
program: RequiredParam<NFTCollection | NFTDrop>,
|
program: RequiredParam<NFTCollection | NFTDrop>,
|
||||||
|
queryParams?: QueryAllParams,
|
||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
queryKey: createSOLProgramQueryKey(program, ["getAll"] as const),
|
queryKey: createSOLProgramQueryKey(program, [
|
||||||
|
"getAll",
|
||||||
|
queryParams,
|
||||||
|
] as const),
|
||||||
|
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
requiredParamInvariant(program, "program is required");
|
requiredParamInvariant(program, "program is required");
|
||||||
return await program.getAll();
|
return program.getAll(queryParams);
|
||||||
},
|
},
|
||||||
enabled: !!program,
|
enabled: !!program,
|
||||||
};
|
};
|
||||||
@@ -40,6 +45,9 @@ export function nftGetAllQuery(
|
|||||||
*
|
*
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export function useNFTs(program: RequiredParam<NFTCollection | NFTDrop>) {
|
export function useNFTs(
|
||||||
return useQuery(nftGetAllQuery(program));
|
program: RequiredParam<NFTCollection | NFTDrop>,
|
||||||
|
queryParams?: QueryAllParams,
|
||||||
|
) {
|
||||||
|
return useQuery(nftGetAllQuery(program, queryParams));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ export function nftRoyaltyQuery(
|
|||||||
*
|
*
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export function useRoyaltySettings(program: RequiredParam<NFTCollection | NFTDrop>) {
|
export function useRoyaltySettings(
|
||||||
|
program: RequiredParam<NFTCollection | NFTDrop>,
|
||||||
|
) {
|
||||||
return useQuery(nftRoyaltyQuery(program));
|
return useQuery(nftRoyaltyQuery(program));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { createSOLProgramQueryKey } from "../../../core/query-utils/query-key";
|
||||||
|
import {
|
||||||
|
requiredParamInvariant,
|
||||||
|
RequiredParam,
|
||||||
|
} from "../../../core/query-utils/required-param";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
|
||||||
|
|
||||||
|
export function nftTotalSupplyQuery(
|
||||||
|
program: RequiredParam<NFTCollection | NFTDrop>,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
queryKey: createSOLProgramQueryKey(program, ["supply"] as const),
|
||||||
|
|
||||||
|
queryFn: async () => {
|
||||||
|
requiredParamInvariant(program, "program is required");
|
||||||
|
return program.totalSupply();
|
||||||
|
},
|
||||||
|
enabled: !!program,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the totaly supply of NFTs on the program
|
||||||
|
* @param program - The NFT program to get the total supply of
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```jsx
|
||||||
|
* import { useProgram, useTotalSupply } from "@thirdweb-dev/react/solana";
|
||||||
|
*
|
||||||
|
* export default function Component() {
|
||||||
|
* const { program } = useProgram("{{program_address}}");
|
||||||
|
* const { data: supply, isLoading } = useTotalSupply(program);
|
||||||
|
*
|
||||||
|
* return (
|
||||||
|
* <pre>{JSON.stringify(supply)}</pre>
|
||||||
|
* )
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export function useTotalSupply(
|
||||||
|
program: RequiredParam<NFTCollection | NFTDrop>,
|
||||||
|
) {
|
||||||
|
return useQuery(nftTotalSupplyQuery(program));
|
||||||
|
}
|
||||||
@@ -4,7 +4,11 @@ import {
|
|||||||
RequiredParam,
|
RequiredParam,
|
||||||
} from "../../../core/query-utils/required-param";
|
} from "../../../core/query-utils/required-param";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import type { CreatorInput, NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
|
import type {
|
||||||
|
NFTCollection,
|
||||||
|
NFTDrop,
|
||||||
|
UpdateCreatorInput,
|
||||||
|
} from "@thirdweb-dev/sdk/solana";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the creators for an NFT program
|
* Update the creators for an NFT program
|
||||||
@@ -35,9 +39,9 @@ export function useUpdateCreators(
|
|||||||
) {
|
) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation(
|
return useMutation(
|
||||||
async (creators: CreatorInput[]) => {
|
async ({ creators, updateAll }: UpdateCreatorInput) => {
|
||||||
requiredParamInvariant(program, "program is required");
|
requiredParamInvariant(program, "program is required");
|
||||||
return await program.updateCreators(creators);
|
return await program.updateCreators(creators, updateAll);
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
onSettled: () =>
|
onSettled: () =>
|
||||||
|
|||||||
@@ -4,7 +4,11 @@ import {
|
|||||||
RequiredParam,
|
RequiredParam,
|
||||||
} from "../../../core/query-utils/required-param";
|
} from "../../../core/query-utils/required-param";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
|
import type {
|
||||||
|
NFTCollection,
|
||||||
|
NFTDrop,
|
||||||
|
UpdateRoyaltySettingsInput,
|
||||||
|
} from "@thirdweb-dev/sdk/solana";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the royalty for an NFT program
|
* Update the royalty for an NFT program
|
||||||
@@ -35,9 +39,9 @@ export function useUpdateRoyaltySettings(
|
|||||||
) {
|
) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation(
|
return useMutation(
|
||||||
async (sellerFeeBasisPoints: number) => {
|
async ({ sellerFeeBasisPoints, updateAll }: UpdateRoyaltySettingsInput) => {
|
||||||
requiredParamInvariant(program, "program is required");
|
requiredParamInvariant(program, "program is required");
|
||||||
return await program.updateRoyalty(sellerFeeBasisPoints);
|
return await program.updateRoyalty(sellerFeeBasisPoints, updateAll);
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
onSettled: () =>
|
onSettled: () =>
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export * from "./hooks/nft/useRoyaltySettings";
|
|||||||
export * from "./hooks/nft/useUpdateRoyaltySettings";
|
export * from "./hooks/nft/useUpdateRoyaltySettings";
|
||||||
export * from "./hooks/nft/useCreators";
|
export * from "./hooks/nft/useCreators";
|
||||||
export * from "./hooks/nft/useUpdateCreators";
|
export * from "./hooks/nft/useUpdateCreators";
|
||||||
|
export * from "./hooks/nft/useTotalSupply";
|
||||||
|
|
||||||
// NFT Collection
|
// NFT Collection
|
||||||
export * from "./hooks/nft/collection/useMintNFT";
|
export * from "./hooks/nft/collection/useMintNFT";
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,5 +1,66 @@
|
|||||||
# @thirdweb-dev/sdk
|
# @thirdweb-dev/sdk
|
||||||
|
|
||||||
|
## 3.6.4
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#438](https://github.com/thirdweb-dev/js/pull/438) [`f451da6`](https://github.com/thirdweb-dev/js/commit/f451da6395689a5f89800ee63f34b6175b61f703) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix SigMint detection for OSRF NFT Collection contracts
|
||||||
|
|
||||||
|
- [#416](https://github.com/thirdweb-dev/js/pull/416) [`af3acc6`](https://github.com/thirdweb-dev/js/commit/af3acc6b10751b840e56aef6400da5eea6040df2) Thanks [@adam-maj](https://github.com/adam-maj)! - Add support for AWS KMS
|
||||||
|
|
||||||
|
- [#424](https://github.com/thirdweb-dev/js/pull/424) [`1bfb91d`](https://github.com/thirdweb-dev/js/commit/1bfb91dbf3a39160c987a425813ac5dbb84703ad) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Improve error parsing for other wallets
|
||||||
|
|
||||||
|
- [#436](https://github.com/thirdweb-dev/js/pull/436) [`ee47840`](https://github.com/thirdweb-dev/js/commit/ee478407673b0416e0c1cfe2be11bd6963395348) Thanks [@jnsdls](https://github.com/jnsdls)! - fix #429
|
||||||
|
|
||||||
|
- [#434](https://github.com/thirdweb-dev/js/pull/434) [`def4251`](https://github.com/thirdweb-dev/js/commit/def42511ff5a20d83f9094164dafb87e412571b5) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - [SOL] Remove workaround to fetch NFT owners
|
||||||
|
|
||||||
|
- [#429](https://github.com/thirdweb-dev/js/pull/429) [`034a257`](https://github.com/thirdweb-dev/js/commit/034a257442314c67729f7bafcbe3740cff33fa32) Thanks [@jakeloo](https://github.com/jakeloo)! - Extract more minimal proxy impl address
|
||||||
|
|
||||||
|
- [#418](https://github.com/thirdweb-dev/js/pull/418) [`eca4776`](https://github.com/thirdweb-dev/js/commit/eca47763cd89cc3b7aa57b542971837987540b55) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Increase gas limit for opening packs
|
||||||
|
|
||||||
|
- [#420](https://github.com/thirdweb-dev/js/pull/420) [`639e535`](https://github.com/thirdweb-dev/js/commit/639e535ed55280ad9d081001aab3f5af72bb3e45) Thanks [@jnsdls](https://github.com/jnsdls)! - update deps
|
||||||
|
|
||||||
|
- Updated dependencies [[`f451da6`](https://github.com/thirdweb-dev/js/commit/f451da6395689a5f89800ee63f34b6175b61f703)]:
|
||||||
|
- @thirdweb-dev/contracts-js@1.2.2
|
||||||
|
|
||||||
|
## 3.6.3
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#408](https://github.com/thirdweb-dev/js/pull/408) [`48797c7`](https://github.com/thirdweb-dev/js/commit/48797c7cf0695965e33eb6bf602be4652f7085a8) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - add `Gasless` as a possible extension to feature-detect
|
||||||
|
|
||||||
|
- [#402](https://github.com/thirdweb-dev/js/pull/402) [`83dcaf7`](https://github.com/thirdweb-dev/js/commit/83dcaf70584af8c5cdf0427f9fc1ba82d89f0887) Thanks [@adam-maj](https://github.com/adam-maj)! - Expose sdk.fromWallet and wallet classes
|
||||||
|
|
||||||
|
- [#412](https://github.com/thirdweb-dev/js/pull/412) [`f03be39`](https://github.com/thirdweb-dev/js/commit/f03be398e0d7b75c9c5b4fb643f35903e89a17e7) Thanks [@easonchai](https://github.com/easonchai)! - Correctly handle contracts using the SignatureMintERC1155 ContractKit extension
|
||||||
|
|
||||||
|
- [#283](https://github.com/thirdweb-dev/js/pull/283) [`2eaa67a`](https://github.com/thirdweb-dev/js/commit/2eaa67acbe21464e7715d0b696afdc024460a44d) Thanks [@adam-maj](https://github.com/adam-maj)! - AppURI detection now enabled
|
||||||
|
|
||||||
|
- [#414](https://github.com/thirdweb-dev/js/pull/414) [`47f8945`](https://github.com/thirdweb-dev/js/commit/47f8945325447874b1ace0359919c1d54fd55436) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Improve error parsing
|
||||||
|
|
||||||
|
## 3.6.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#405](https://github.com/thirdweb-dev/js/pull/405) [`ccb7db4`](https://github.com/thirdweb-dev/js/commit/ccb7db48739b8dddcb2c032b3b6e3e5200485715) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add updateAll param to creators and royalty update hooks for Solana
|
||||||
|
|
||||||
|
- [#404](https://github.com/thirdweb-dev/js/pull/404) [`9151aa7`](https://github.com/thirdweb-dev/js/commit/9151aa7dc80754a7aa4fd3f6ce0207bccbb6451f) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - expose `getDefaultTrustedForwarders` helper function
|
||||||
|
|
||||||
|
- [#305](https://github.com/thirdweb-dev/js/pull/305) [`5a01c53`](https://github.com/thirdweb-dev/js/commit/5a01c537e30bd7ef562aad1012413990de6faedf) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Update to Metaplex 0.17
|
||||||
|
|
||||||
|
## 3.6.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#398](https://github.com/thirdweb-dev/js/pull/398) [`15514f1`](https://github.com/thirdweb-dev/js/commit/15514f190a844d809ae5b1edb580aab46a682485) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - add `defaultValue` to constructorParams schema for releases
|
||||||
|
|
||||||
|
- [#388](https://github.com/thirdweb-dev/js/pull/388) [`7c0744a`](https://github.com/thirdweb-dev/js/commit/7c0744a006e78987ad8b271b2c64f4bac7759510) Thanks [@adam-maj](https://github.com/adam-maj)! - Add support for total supply and pagination on get all
|
||||||
|
|
||||||
|
- [#395](https://github.com/thirdweb-dev/js/pull/395) [`f8bceec`](https://github.com/thirdweb-dev/js/commit/f8bceec10c60b30dc3d6f45926e2a9e018202578) Thanks [@jnsdls](https://github.com/jnsdls)! - [Solana] - fix claim condition reset to native token from custom
|
||||||
|
|
||||||
|
- [#399](https://github.com/thirdweb-dev/js/pull/399) [`887af24`](https://github.com/thirdweb-dev/js/commit/887af24450e316c2ea390cd49c0563cebe793c0f) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - fix custom error handling for null-ish error values
|
||||||
|
|
||||||
|
- [#390](https://github.com/thirdweb-dev/js/pull/390) [`96bd92e`](https://github.com/thirdweb-dev/js/commit/96bd92e724ec7d880d23348071b26ab8c21dd868) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - [SDK] Expose `getAllDetectedFeatures(ABI)` helper function
|
||||||
|
|
||||||
## 3.6.0
|
## 3.6.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"main": "dist/thirdweb-dev-sdk-evm-wallets.cjs.js",
|
||||||
|
"module": "dist/thirdweb-dev-sdk-evm-wallets.esm.js"
|
||||||
|
}
|
||||||
+33
-15
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@thirdweb-dev/sdk",
|
"name": "@thirdweb-dev/sdk",
|
||||||
"version": "3.6.0",
|
"version": "3.6.4",
|
||||||
"description": "The main thirdweb SDK.",
|
"description": "The main thirdweb SDK.",
|
||||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
|
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
@@ -19,6 +19,10 @@
|
|||||||
"module": "./solana/dist/thirdweb-dev-sdk-solana.esm.js",
|
"module": "./solana/dist/thirdweb-dev-sdk-solana.esm.js",
|
||||||
"default": "./solana/dist/thirdweb-dev-sdk-solana.cjs.js"
|
"default": "./solana/dist/thirdweb-dev-sdk-solana.cjs.js"
|
||||||
},
|
},
|
||||||
|
"./evm/wallets": {
|
||||||
|
"module": "./evm/wallets/dist/thirdweb-dev-sdk-evm-wallets.esm.js",
|
||||||
|
"default": "./evm/wallets/dist/thirdweb-dev-sdk-evm-wallets.cjs.js"
|
||||||
|
},
|
||||||
"./solana/server": {
|
"./solana/server": {
|
||||||
"module": "./solana/server/dist/thirdweb-dev-sdk-solana-server.esm.js",
|
"module": "./solana/server/dist/thirdweb-dev-sdk-solana-server.esm.js",
|
||||||
"default": "./solana/server/dist/thirdweb-dev-sdk-solana-server.cjs.js"
|
"default": "./solana/server/dist/thirdweb-dev-sdk-solana-server.cjs.js"
|
||||||
@@ -28,6 +32,7 @@
|
|||||||
"files": [
|
"files": [
|
||||||
"dist/",
|
"dist/",
|
||||||
"evm/",
|
"evm/",
|
||||||
|
"wallets/",
|
||||||
"solana/",
|
"solana/",
|
||||||
"server/"
|
"server/"
|
||||||
],
|
],
|
||||||
@@ -35,6 +40,7 @@
|
|||||||
"entrypoints": [
|
"entrypoints": [
|
||||||
"index.ts",
|
"index.ts",
|
||||||
"evm/index.ts",
|
"evm/index.ts",
|
||||||
|
"evm/wallets/index.ts",
|
||||||
"solana/index.ts",
|
"solana/index.ts",
|
||||||
"solana/server/index.ts"
|
"solana/server/index.ts"
|
||||||
],
|
],
|
||||||
@@ -57,7 +63,7 @@
|
|||||||
"test:evm:all": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/evm/.mocharc.json' --timeout 30000 --parallel './test/evm/**/*.test.ts'",
|
"test:evm:all": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/evm/.mocharc.json' --timeout 30000 --parallel './test/evm/**/*.test.ts'",
|
||||||
"test:evm": "make test-evm",
|
"test:evm": "make test-evm",
|
||||||
"test:evm:single": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/evm/.mocharc.json' --timeout 30000",
|
"test:evm:single": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/evm/.mocharc.json' --timeout 30000",
|
||||||
"node:solana:start": "DEBUG='amman:(info|error|debug)' amman start",
|
"node:solana:start": "DEBUG='amman:(info|error|debug)' amman start --forceClone",
|
||||||
"node:solana:stop": "amman stop",
|
"node:solana:stop": "amman stop",
|
||||||
"test:solana:all": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/solana/.mocharc.json' --timeout 30000 --parallel './test/solana/**/*.test.ts'",
|
"test:solana:all": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/solana/.mocharc.json' --timeout 30000 --parallel './test/solana/**/*.test.ts'",
|
||||||
"test:solana": "make test-sol",
|
"test:solana": "make test-sol",
|
||||||
@@ -65,18 +71,19 @@
|
|||||||
"push": "yalc push"
|
"push": "yalc push"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@metaplex-foundation/amman": "0.10.0",
|
"@aws-sdk/client-secrets-manager": "^3.216.0",
|
||||||
"@metaplex-foundation/amman-client": "0.2.1",
|
"@metaplex-foundation/amman": "^0.12.0",
|
||||||
|
"@metaplex-foundation/amman-client": "^0.2.1",
|
||||||
"@microsoft/api-documenter": "^7.19.4",
|
"@microsoft/api-documenter": "^7.19.4",
|
||||||
"@microsoft/api-extractor": "^7.29.2",
|
"@microsoft/api-extractor": "^7.29.2",
|
||||||
"@microsoft/tsdoc": "^0.14.1",
|
"@microsoft/tsdoc": "^0.14.1",
|
||||||
"@nomiclabs/hardhat-ethers": "2.0.5",
|
"@nomiclabs/hardhat-ethers": "^2.0.5",
|
||||||
"@preconstruct/cli": "^2.2.1",
|
"@preconstruct/cli": "^2.2.1",
|
||||||
"@swc-node/register": "^1.5.1",
|
"@swc-node/register": "^1.5.1",
|
||||||
"@swc/core": "^1.2.177",
|
"@swc/core": "^1.2.177",
|
||||||
"@types/chai": "^4.3.3",
|
"@types/chai": "^4.3.3",
|
||||||
"@types/deep-equal-in-any-order": "^1.0.1",
|
"@types/deep-equal-in-any-order": "^1.0.1",
|
||||||
"@types/mocha": "^9.1.1",
|
"@types/mocha": "^10.0.0",
|
||||||
"@types/node": "^18.0.0",
|
"@types/node": "^18.0.0",
|
||||||
"@types/uuid": "^8.3.3",
|
"@types/uuid": "^8.3.3",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
||||||
@@ -89,27 +96,38 @@
|
|||||||
"eslint-plugin-inclusive-language": "^2.2.0",
|
"eslint-plugin-inclusive-language": "^2.2.0",
|
||||||
"eslint-plugin-prettier": "^4.2.1",
|
"eslint-plugin-prettier": "^4.2.1",
|
||||||
"eslint-plugin-tsdoc": "^0.2.16",
|
"eslint-plugin-tsdoc": "^0.2.16",
|
||||||
"ethers": "^5.7.0",
|
"ethers": "^5.7.2",
|
||||||
|
"ethers-aws-kms-signer": "^1.3.2",
|
||||||
"hardhat": "^2.9.3",
|
"hardhat": "^2.9.3",
|
||||||
"mocha": "^10.0.0",
|
"mocha": "^10.0.0",
|
||||||
"prettier": "^2.7.1",
|
"prettier": "^2.7.1",
|
||||||
"typescript": "^4.7.4"
|
"typescript": "^4.7.4"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"ethers": "^5"
|
"@aws-sdk/client-secrets-manager": "^3.215.0",
|
||||||
|
"ethers": "^5",
|
||||||
|
"ethers-aws-kms-signer": "^1.3.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@aws-sdk/client-secrets-manager": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"ethers-aws-kms-signer": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@metaplex-foundation/js": "0.15.0",
|
"@metaplex-foundation/js": "^0.17.6",
|
||||||
"@metaplex-foundation/mpl-token-metadata": "2.2.2",
|
"@metaplex-foundation/mpl-token-metadata": "^2.3.3",
|
||||||
"@project-serum/anchor": "0.25.0",
|
"@project-serum/anchor": "^0.25.0",
|
||||||
"@solana/spl-token": "0.2.0",
|
"@solana/spl-token": "^0.3.5",
|
||||||
"@solana/web3.js": "1.62.0",
|
"@solana/web3.js": "^1.62.0",
|
||||||
"@thirdweb-dev/contracts-js": "*",
|
"@thirdweb-dev/contracts-js": "*",
|
||||||
"@thirdweb-dev/storage": "*",
|
"@thirdweb-dev/storage": "*",
|
||||||
"bn.js": "^5.2.1",
|
"bn.js": "^5.2.1",
|
||||||
"bs58": "^5.0.0",
|
"bs58": "^5.0.0",
|
||||||
"cross-fetch": "^3.1.5",
|
"cross-fetch": "^3.1.5",
|
||||||
"eventemitter3": "^4.0.7",
|
"eventemitter3": "^5.0.0",
|
||||||
"fast-deep-equal": "^3.1.3",
|
"fast-deep-equal": "^3.1.3",
|
||||||
"merkletreejs": "^0.2.24",
|
"merkletreejs": "^0.2.24",
|
||||||
"tiny-invariant": "^1.2.0",
|
"tiny-invariant": "^1.2.0",
|
||||||
@@ -128,4 +146,4 @@
|
|||||||
"url": "https://github.com/thirdweb-dev/js/issues"
|
"url": "https://github.com/thirdweb-dev/js/issues"
|
||||||
},
|
},
|
||||||
"author": "thirdweb eng <[email protected]>"
|
"author": "thirdweb eng <[email protected]>"
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,25 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
export const DEFAULT_QUERY_ALL_COUNT = 100;
|
export const DEFAULT_QUERY_ALL_COUNT = 100;
|
||||||
|
|
||||||
|
export const QueryAllParamsSchema = z
|
||||||
|
.object({
|
||||||
|
start: z.number().default(0),
|
||||||
|
count: z.number().default(DEFAULT_QUERY_ALL_COUNT),
|
||||||
|
})
|
||||||
|
.default({
|
||||||
|
start: 0,
|
||||||
|
count: DEFAULT_QUERY_ALL_COUNT,
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pagination Parameters
|
* Pagination Parameters
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export interface QueryAllParams {
|
export type QueryAllParams = Exclude<
|
||||||
/**
|
z.input<typeof QueryAllParamsSchema>,
|
||||||
* the index to start from (default: 0)
|
undefined
|
||||||
*/
|
>;
|
||||||
start?: number;
|
|
||||||
/**
|
|
||||||
* how many items to return (default: 100)
|
|
||||||
*/
|
|
||||||
count?: number;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -394,20 +394,16 @@ export async function convertToTWError(
|
|||||||
contractInterface: ethers.utils.Interface,
|
contractInterface: ethers.utils.Interface,
|
||||||
): Promise<TransactionError> {
|
): Promise<TransactionError> {
|
||||||
let raw: string;
|
let raw: string;
|
||||||
if (error.data) {
|
if (typeof error === "object") {
|
||||||
// metamask errors comes as objects, apply parsing on data object
|
// metamask errors comes as objects, apply parsing on data object
|
||||||
// TODO test errors from other wallets
|
raw = JSON.stringify(error);
|
||||||
raw = JSON.stringify(error.data);
|
|
||||||
} else if (error instanceof Error) {
|
|
||||||
// regular ethers.js error
|
|
||||||
raw = error.message;
|
|
||||||
} else {
|
} else {
|
||||||
// not sure what this is, just throw it back
|
// not sure what this is, just throw it back
|
||||||
raw = error.toString();
|
raw = error.toString();
|
||||||
}
|
}
|
||||||
const reason =
|
const reason =
|
||||||
error.reason ||
|
parseMessageParts(/.*?"message[^a-zA-Z0-9]*([^"\\]*).*?/, raw) ||
|
||||||
parseMessageParts(/.*?"message[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
parseMessageParts(/.*?"reason[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
||||||
const data = parseMessageParts(/.*?"data[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
const data = parseMessageParts(/.*?"data[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
||||||
const rpcUrl = parseMessageParts(/.*?"url[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
const rpcUrl = parseMessageParts(/.*?"url[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
||||||
let from = parseMessageParts(/.*?"from[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
let from = parseMessageParts(/.*?"from[^a-zA-Z0-9]*([^"\\]*).*?/, raw);
|
||||||
@@ -459,9 +455,12 @@ function parseMessageParts(regex: RegExp, raw: string): string {
|
|||||||
* @param message
|
* @param message
|
||||||
*/
|
*/
|
||||||
export function includesErrorMessage(err: any, message: string): boolean {
|
export function includesErrorMessage(err: any, message: string): boolean {
|
||||||
|
if (!err) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
(err && err.toString().includes(message)) ||
|
(err && err.toString().includes(message)) ||
|
||||||
(err.message && err.message.toString().includes(message)) ||
|
(err && err.message && err.message.toString().includes(message)) ||
|
||||||
(err.error && err.error.toString().includes(message))
|
(err && err.error && err.error.toString().includes(message))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -266,6 +266,42 @@ function toJSType(
|
|||||||
return jsType;
|
return jsType;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @internal
|
||||||
|
* @param bytecode
|
||||||
|
*/
|
||||||
|
export function extractMinimalProxyImplementationAddress(
|
||||||
|
bytecode: string,
|
||||||
|
): string | undefined {
|
||||||
|
// EIP-1167 clone minimal proxy - https://eips.ethereum.org/EIPS/eip-1167
|
||||||
|
if (bytecode.startsWith("0x363d3d373d3d3d363d73")) {
|
||||||
|
const implementationAddress = bytecode.slice(22, 62);
|
||||||
|
return `0x${implementationAddress}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimal Proxy with receive() from 0xSplits - https://github.com/0xSplits/splits-contracts/blob/c7b741926ec9746182d0d1e2c4c2046102e5d337/contracts/libraries/Clones.sol
|
||||||
|
if (bytecode.startsWith("0x36603057343d5230")) {
|
||||||
|
// +40 = size of addr
|
||||||
|
const implementationAddress = bytecode.slice(122, 122 + 40);
|
||||||
|
return `0x${implementationAddress}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0age's minimal proxy - https://medium.com/coinmonks/the-more-minimal-proxy-5756ae08ee48
|
||||||
|
if (bytecode.startsWith("0x3d3d3d3d363d3d37363d73")) {
|
||||||
|
// +40 = size of addr
|
||||||
|
const implementationAddress = bytecode.slice(24, 24 + 40);
|
||||||
|
return `0x${implementationAddress}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// vyper's minimal proxy (uniswap v1) - https://etherscan.io/address/0x09cabec1ead1c0ba254b09efb3ee13841712be14#code
|
||||||
|
if (bytecode.startsWith("0x366000600037611000600036600073")) {
|
||||||
|
const implementationAddress = bytecode.slice(32, 32 + 40);
|
||||||
|
return `0x${implementationAddress}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
* @param address
|
* @param address
|
||||||
@@ -282,14 +318,20 @@ export async function resolveContractUriFromAddress(
|
|||||||
`Contract at ${address} does not exist on chain '${chain.name}' (chainId: ${chain.chainId})`,
|
`Contract at ${address} does not exist on chain '${chain.name}' (chainId: ${chain.chainId})`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// EIP-1167 clone proxy - https://eips.ethereum.org/EIPS/eip-1167
|
|
||||||
if (bytecode.startsWith("0x363d3d373d3d3d363d")) {
|
try {
|
||||||
const implementationAddress = bytecode.slice(22, 62);
|
const implementationAddress =
|
||||||
return await resolveContractUriFromAddress(
|
extractMinimalProxyImplementationAddress(bytecode);
|
||||||
`0x${implementationAddress}`,
|
if (implementationAddress) {
|
||||||
provider,
|
return await resolveContractUriFromAddress(
|
||||||
);
|
implementationAddress,
|
||||||
|
provider,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
// EIP-1967 proxy storage slots - https://eips.ethereum.org/EIPS/eip-1967
|
// EIP-1967 proxy storage slots - https://eips.ethereum.org/EIPS/eip-1967
|
||||||
try {
|
try {
|
||||||
const proxyStorage = await provider.getStorageAt(
|
const proxyStorage = await provider.getStorageAt(
|
||||||
@@ -438,8 +480,8 @@ export async function fetchSourceFilesFromMetadata(
|
|||||||
async ([path, info]) => {
|
async ([path, info]) => {
|
||||||
const urls = (info as any).urls as string[];
|
const urls = (info as any).urls as string[];
|
||||||
const ipfsLink = urls
|
const ipfsLink = urls
|
||||||
? urls.find((url) => url.includes("ipfs"))
|
? urls.find((url) => url.includes("ipfs"))
|
||||||
: undefined;
|
: undefined;
|
||||||
if (ipfsLink) {
|
if (ipfsLink) {
|
||||||
const ipfsHash = ipfsLink.split("ipfs/")[1];
|
const ipfsHash = ipfsLink.split("ipfs/")[1];
|
||||||
// 5 sec timeout for sources that haven't been uploaded to ipfs
|
// 5 sec timeout for sources that haven't been uploaded to ipfs
|
||||||
@@ -458,8 +500,8 @@ export async function fetchSourceFilesFromMetadata(
|
|||||||
return {
|
return {
|
||||||
filename: path,
|
filename: path,
|
||||||
source:
|
source:
|
||||||
(info as any).content ||
|
(info as any).content ||
|
||||||
"Could not find source for this contract",
|
"Could not find source for this contract",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -525,7 +567,7 @@ export async function fetchExtendedReleaseMetadata(
|
|||||||
* @returns the nested struct of all features and whether they're detected in the abi
|
* @returns the nested struct of all features and whether they're detected in the abi
|
||||||
*/
|
*/
|
||||||
export function detectFeatures(
|
export function detectFeatures(
|
||||||
abi: z.input<typeof AbiSchema>,
|
abi: Abi,
|
||||||
features: Record<string, Feature> = SUPPORTED_FEATURES,
|
features: Record<string, Feature> = SUPPORTED_FEATURES,
|
||||||
): Record<string, FeatureWithEnabled> {
|
): Record<string, FeatureWithEnabled> {
|
||||||
const results: Record<string, FeatureWithEnabled> = {};
|
const results: Record<string, FeatureWithEnabled> = {};
|
||||||
@@ -542,6 +584,48 @@ export function detectFeatures(
|
|||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractFeatures(
|
||||||
|
input: Record<string, FeatureWithEnabled>,
|
||||||
|
enabledExtensions: FeatureWithEnabled[],
|
||||||
|
) {
|
||||||
|
if (!input) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const extensionKey in input) {
|
||||||
|
const extension = input[extensionKey];
|
||||||
|
// if extension is enabled, then add it to enabledFeatures
|
||||||
|
if (extension.enabled) {
|
||||||
|
enabledExtensions.push(extension);
|
||||||
|
}
|
||||||
|
// recurse
|
||||||
|
extractFeatures(extension.features, enabledExtensions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return all the detected features in the abi
|
||||||
|
* @param abi - parsed array of abi entries
|
||||||
|
* @returns array of all detected extensions with full information on each feature
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export function getAllDetectedFeatures(abi: Abi): FeatureWithEnabled[] {
|
||||||
|
const features: FeatureWithEnabled[] = [];
|
||||||
|
extractFeatures(detectFeatures(abi), features);
|
||||||
|
return features;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return all the detected features names in the abi
|
||||||
|
* @param abi - parsed array of abi entries
|
||||||
|
* @returns array of all detected features names
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export function getAllDetectedFeatureNames(abi: Abi): string[] {
|
||||||
|
const features: FeatureWithEnabled[] = [];
|
||||||
|
extractFeatures(detectFeatures(abi), features);
|
||||||
|
return features.map((f) => f.name);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks whether the given ABI supports a given feature
|
* Checks whether the given ABI supports a given feature
|
||||||
* @internal
|
* @internal
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { PrebuiltContractType } from "../core/types";
|
import { PrebuiltContractType } from "../core/types";
|
||||||
import { ChainId, SUPPORTED_CHAIN_ID } from "./chains";
|
import { ChainId, SUPPORTED_CHAIN_ID, SUPPORTED_CHAIN_IDS } from "./chains";
|
||||||
import { constants } from "ethers";
|
import { constants } from "ethers";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -290,3 +290,24 @@ export function getContractPublisherAddress() {
|
|||||||
return ContractPublisher_address;
|
return ContractPublisher_address;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param chainId - chain id
|
||||||
|
* @returns the array of trusted forwarders for the given chain id
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
export function getDefaultTrustedForwarders(
|
||||||
|
chainId: SUPPORTED_CHAIN_ID,
|
||||||
|
): string[] {
|
||||||
|
const chainEnum = SUPPORTED_CHAIN_IDS.find((c) => c === chainId);
|
||||||
|
const biconomyForwarder = chainEnum
|
||||||
|
? CONTRACT_ADDRESSES[chainEnum].biconomyForwarder
|
||||||
|
: constants.AddressZero;
|
||||||
|
const openzeppelinForwarder = chainEnum
|
||||||
|
? CONTRACT_ADDRESSES[chainEnum].openzeppelinForwarder
|
||||||
|
: constants.AddressZero;
|
||||||
|
return biconomyForwarder !== constants.AddressZero
|
||||||
|
? [openzeppelinForwarder, biconomyForwarder]
|
||||||
|
: [openzeppelinForwarder];
|
||||||
|
}
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import {
|
|||||||
FEATURE_PRIMARY_SALE,
|
FEATURE_PRIMARY_SALE,
|
||||||
FEATURE_ROYALTY,
|
FEATURE_ROYALTY,
|
||||||
FEATURE_APPURI,
|
FEATURE_APPURI,
|
||||||
|
FEATURE_GASLESS,
|
||||||
} from "./thirdweb-features";
|
} from "./thirdweb-features";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -104,7 +105,8 @@ export type Feature =
|
|||||||
| typeof FEATURE_PERMISSIONS_ENUMERABLE
|
| typeof FEATURE_PERMISSIONS_ENUMERABLE
|
||||||
| typeof FEATURE_METADATA
|
| typeof FEATURE_METADATA
|
||||||
| typeof FEATURE_APPURI
|
| typeof FEATURE_APPURI
|
||||||
| typeof FEATURE_OWNER;
|
| typeof FEATURE_OWNER
|
||||||
|
| typeof FEATURE_GASLESS;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
@@ -132,4 +134,5 @@ export const SUPPORTED_FEATURES: Record<string, Feature> = {
|
|||||||
[FEATURE_METADATA.name]: FEATURE_METADATA,
|
[FEATURE_METADATA.name]: FEATURE_METADATA,
|
||||||
[FEATURE_APPURI.name]: FEATURE_APPURI,
|
[FEATURE_APPURI.name]: FEATURE_APPURI,
|
||||||
[FEATURE_OWNER.name]: FEATURE_OWNER,
|
[FEATURE_OWNER.name]: FEATURE_OWNER,
|
||||||
|
[FEATURE_GASLESS.name]: FEATURE_GASLESS,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ import ILazyMintAbi from "@thirdweb-dev/contracts-js/dist/abis/ILazyMint.json";
|
|||||||
import IMintableERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/IMintableERC721.json";
|
import IMintableERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/IMintableERC721.json";
|
||||||
import MulticallAbi from "@thirdweb-dev/contracts-js/dist/abis/IMulticall.json";
|
import MulticallAbi from "@thirdweb-dev/contracts-js/dist/abis/IMulticall.json";
|
||||||
import SignatureMintERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721.json";
|
import SignatureMintERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721.json";
|
||||||
|
import SignatureMintERC721_V1Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721_V1.json";
|
||||||
import TieredDropAbi from "@thirdweb-dev/contracts-js/dist/abis/LazyMintWithTier.json";
|
import TieredDropAbi from "@thirdweb-dev/contracts-js/dist/abis/LazyMintWithTier.json";
|
||||||
import TokenERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/TokenERC721.json";
|
|
||||||
|
|
||||||
export const FEATURE_NFT_BURNABLE = {
|
export const FEATURE_NFT_BURNABLE = {
|
||||||
name: "ERC721Burnable",
|
name: "ERC721Burnable",
|
||||||
@@ -163,7 +163,7 @@ export const FEATURE_NFT_SIGNATURE_MINTABLE_V1 = {
|
|||||||
sdk: "sdk.erc721signaturemint",
|
sdk: "sdk.erc721signaturemint",
|
||||||
contracts: "ISignatureMintERC721",
|
contracts: "ISignatureMintERC721",
|
||||||
},
|
},
|
||||||
abis: [TokenERC721Abi],
|
abis: [SignatureMintERC721_V1Abi],
|
||||||
features: {},
|
features: {},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import IERC2771ContextAbi from "@thirdweb-dev/contracts-js/dist/abis/ERC2771Context.json";
|
||||||
import IAppURI from "@thirdweb-dev/contracts-js/dist/abis/IAppURI.json";
|
import IAppURI from "@thirdweb-dev/contracts-js/dist/abis/IAppURI.json";
|
||||||
import IContractMetadataAbi from "@thirdweb-dev/contracts-js/dist/abis/IContractMetadata.json";
|
import IContractMetadataAbi from "@thirdweb-dev/contracts-js/dist/abis/IContractMetadata.json";
|
||||||
import IPermissionsAbi from "@thirdweb-dev/contracts-js/dist/abis/IPermissions.json";
|
import IPermissionsAbi from "@thirdweb-dev/contracts-js/dist/abis/IPermissions.json";
|
||||||
@@ -96,3 +97,15 @@ export const FEATURE_OWNER = {
|
|||||||
abis: [IOwnableAbi],
|
abis: [IOwnableAbi],
|
||||||
features: {},
|
features: {},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
export const FEATURE_GASLESS = {
|
||||||
|
name: "Gasless",
|
||||||
|
namespace: "gasless",
|
||||||
|
docLinks: {
|
||||||
|
sdk: "sdk.gaslesstransaction",
|
||||||
|
// TODO add the correct name for this once it's added to portal
|
||||||
|
contracts: "",
|
||||||
|
},
|
||||||
|
abis: [IERC2771ContextAbi],
|
||||||
|
features: {},
|
||||||
|
} as const;
|
||||||
|
|||||||
@@ -536,10 +536,14 @@ export class Pack extends StandardErc1155<PackContract> {
|
|||||||
tokenId: BigNumberish,
|
tokenId: BigNumberish,
|
||||||
amount: BigNumberish = 1,
|
amount: BigNumberish = 1,
|
||||||
): Promise<PackRewards> {
|
): Promise<PackRewards> {
|
||||||
const receipt = await this.contractWrapper.sendTransaction("openPack", [
|
const receipt = await this.contractWrapper.sendTransaction(
|
||||||
tokenId,
|
"openPack",
|
||||||
amount,
|
[tokenId, amount],
|
||||||
]);
|
{
|
||||||
|
// Higher gas limit for opening packs
|
||||||
|
gasLimit: 500000,
|
||||||
|
},
|
||||||
|
);
|
||||||
const event = this.contractWrapper.parseLogs<PackOpenedEvent>(
|
const event = this.contractWrapper.parseLogs<PackOpenedEvent>(
|
||||||
"PackOpened",
|
"PackOpened",
|
||||||
receipt?.logs,
|
receipt?.logs,
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { FEATURE_TOKEN } from "../constants/erc20-features";
|
|||||||
import { FEATURE_NFT } from "../constants/erc721-features";
|
import { FEATURE_NFT } from "../constants/erc721-features";
|
||||||
import { FEATURE_EDITION } from "../constants/erc1155-features";
|
import { FEATURE_EDITION } from "../constants/erc1155-features";
|
||||||
import {
|
import {
|
||||||
FEATURE_APPURI,
|
|
||||||
FEATURE_OWNER,
|
FEATURE_OWNER,
|
||||||
FEATURE_PERMISSIONS,
|
FEATURE_PERMISSIONS,
|
||||||
FEATURE_PLATFORM_FEE,
|
FEATURE_PLATFORM_FEE,
|
||||||
@@ -39,7 +38,6 @@ import type {
|
|||||||
IPrimarySale,
|
IPrimarySale,
|
||||||
IRoyalty,
|
IRoyalty,
|
||||||
Ownable,
|
Ownable,
|
||||||
AppURI,
|
|
||||||
} from "@thirdweb-dev/contracts-js";
|
} from "@thirdweb-dev/contracts-js";
|
||||||
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
||||||
import { BaseContract, CallOverrides, ContractInterface } from "ethers";
|
import { BaseContract, CallOverrides, ContractInterface } from "ethers";
|
||||||
@@ -84,6 +82,7 @@ export class SmartContract<TContract extends BaseContract = BaseContract>
|
|||||||
public publishedMetadata: ContractPublishedMetadata<TContract>;
|
public publishedMetadata: ContractPublishedMetadata<TContract>;
|
||||||
public abi: ContractInterface;
|
public abi: ContractInterface;
|
||||||
public metadata: ContractMetadata<BaseContract, any>;
|
public metadata: ContractMetadata<BaseContract, any>;
|
||||||
|
public appURI: ContractAppURI<BaseContract>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle royalties
|
* Handle royalties
|
||||||
@@ -120,13 +119,6 @@ export class SmartContract<TContract extends BaseContract = BaseContract>
|
|||||||
return assertEnabled(this.detectOwnable(), FEATURE_OWNER);
|
return assertEnabled(this.detectOwnable(), FEATURE_OWNER);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Set and get the appuri of the contract
|
|
||||||
*/
|
|
||||||
get appURI(): ContractAppURI<AppURI> {
|
|
||||||
return assertEnabled(this.detectAppURI(), FEATURE_APPURI);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto-detects ERC20 standard functions.
|
* Auto-detects ERC20 standard functions.
|
||||||
*/
|
*/
|
||||||
@@ -186,6 +178,8 @@ export class SmartContract<TContract extends BaseContract = BaseContract>
|
|||||||
CustomContractSchema,
|
CustomContractSchema,
|
||||||
this.storage,
|
this.storage,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.appURI = new ContractAppURI(this.contractWrapper, this.metadata);
|
||||||
}
|
}
|
||||||
|
|
||||||
onNetworkUpdated(network: NetworkOrSignerOrProvider): void {
|
onNetworkUpdated(network: NetworkOrSignerOrProvider): void {
|
||||||
@@ -290,12 +284,6 @@ export class SmartContract<TContract extends BaseContract = BaseContract>
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
private detectAppURI() {
|
|
||||||
if (detectContractFeature<AppURI>(this.contractWrapper, "AppURI")) {
|
|
||||||
return new ContractAppURI(this.contractWrapper);
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
private detectOwnable() {
|
private detectOwnable() {
|
||||||
if (detectContractFeature<Ownable>(this.contractWrapper, "Ownable")) {
|
if (detectContractFeature<Ownable>(this.contractWrapper, "Ownable")) {
|
||||||
return new ContractOwner(this.contractWrapper);
|
return new ContractOwner(this.contractWrapper);
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
import { detectContractFeature } from "../../common";
|
||||||
import { FEATURE_APPURI } from "../../constants/thirdweb-features";
|
import { FEATURE_APPURI } from "../../constants/thirdweb-features";
|
||||||
import { DetectableFeature } from "../interfaces/DetectableFeature";
|
import { DetectableFeature } from "../interfaces/DetectableFeature";
|
||||||
import { TransactionResult } from "../types";
|
import { TransactionResult } from "../types";
|
||||||
|
import { ContractMetadata } from "./contract-metadata";
|
||||||
import { ContractWrapper } from "./contract-wrapper";
|
import { ContractWrapper } from "./contract-wrapper";
|
||||||
import type { AppURI } from "@thirdweb-dev/contracts-js";
|
import type { AppURI } from "@thirdweb-dev/contracts-js";
|
||||||
|
import { BaseContract } from "ethers";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Have an official Application URI for this contract.
|
* Have an official Application URI for this contract.
|
||||||
@@ -17,14 +20,19 @@ import type { AppURI } from "@thirdweb-dev/contracts-js";
|
|||||||
* ```
|
* ```
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export class ContractAppURI<TContract extends AppURI>
|
export class ContractAppURI<TContract extends BaseContract>
|
||||||
implements DetectableFeature
|
implements DetectableFeature
|
||||||
{
|
{
|
||||||
featureName = FEATURE_APPURI.name;
|
featureName = FEATURE_APPURI.name;
|
||||||
private contractWrapper;
|
private contractWrapper;
|
||||||
|
metadata: ContractMetadata<BaseContract, any>;
|
||||||
|
|
||||||
constructor(contractWrapper: ContractWrapper<TContract>) {
|
constructor(
|
||||||
|
contractWrapper: ContractWrapper<TContract>,
|
||||||
|
metadata: ContractMetadata<BaseContract, any>,
|
||||||
|
) {
|
||||||
this.contractWrapper = contractWrapper;
|
this.contractWrapper = contractWrapper;
|
||||||
|
this.metadata = metadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,7 +40,11 @@ export class ContractAppURI<TContract extends AppURI>
|
|||||||
* @returns the appURI object
|
* @returns the appURI object
|
||||||
*/
|
*/
|
||||||
public async get() {
|
public async get() {
|
||||||
return await this.contractWrapper.readContract.appURI();
|
if (detectContractFeature<AppURI>(this.contractWrapper, "AppURI")) {
|
||||||
|
return await this.contractWrapper.readContract.appURI();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (await this.metadata.get()).appURI || "";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,10 +52,14 @@ export class ContractAppURI<TContract extends AppURI>
|
|||||||
* @param appURI - the uri to set (typically an IPFS hash)
|
* @param appURI - the uri to set (typically an IPFS hash)
|
||||||
*/
|
*/
|
||||||
public async set(appURI: string): Promise<TransactionResult> {
|
public async set(appURI: string): Promise<TransactionResult> {
|
||||||
return {
|
if (detectContractFeature<AppURI>(this.contractWrapper, "AppURI")) {
|
||||||
receipt: await this.contractWrapper.sendTransaction("setAppURI", [
|
return {
|
||||||
appURI,
|
receipt: await this.contractWrapper.sendTransaction("setAppURI", [
|
||||||
]),
|
appURI,
|
||||||
};
|
]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.metadata.update({ appURI });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { ContractEvent, EventQueryOptions } from "../../types/index";
|
|||||||
import { ContractWrapper } from "./contract-wrapper";
|
import { ContractWrapper } from "./contract-wrapper";
|
||||||
import { EventFragment } from "@ethersproject/abi";
|
import { EventFragment } from "@ethersproject/abi";
|
||||||
import { BaseContract, Event, providers } from "ethers";
|
import { BaseContract, Event, providers } from "ethers";
|
||||||
import { ListenerFn } from "eventemitter3";
|
import type { EventEmitter } from "eventemitter3";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Listen to Contract events in real time
|
* Listen to Contract events in real time
|
||||||
@@ -28,7 +28,7 @@ export class ContractEvents<TContract extends BaseContract> {
|
|||||||
* @param listener - the callback function that will be called on every transaction
|
* @param listener - the callback function that will be called on every transaction
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
public addTransactionListener(listener: ListenerFn) {
|
public addTransactionListener(listener: EventEmitter.ListenerFn) {
|
||||||
this.contractWrapper.addListener(EventType.Transaction, listener);
|
this.contractWrapper.addListener(EventType.Transaction, listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ export class ContractEvents<TContract extends BaseContract> {
|
|||||||
* @param listener - the callback function to remove
|
* @param listener - the callback function to remove
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
public removeTransactionListener(listener: ListenerFn) {
|
public removeTransactionListener(listener: EventEmitter.ListenerFn) {
|
||||||
this.contractWrapper.off(EventType.Transaction, listener);
|
this.contractWrapper.off(EventType.Transaction, listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export class ContractOwner<TContract extends Ownable>
|
|||||||
* Return the current owner of the contract
|
* Return the current owner of the contract
|
||||||
* @returns the owner address
|
* @returns the owner address
|
||||||
*/
|
*/
|
||||||
public async get(): Promise<string> {
|
public async get(): Promise<string> {
|
||||||
return this.contractWrapper.readContract.owner();
|
return this.contractWrapper.readContract.owner();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,13 +31,13 @@ export class ContractOwner<TContract extends Ownable>
|
|||||||
* @remarks Can only be called by the current owner.
|
* @remarks Can only be called by the current owner.
|
||||||
*
|
*
|
||||||
* @param address - the address of the new owner
|
* @param address - the address of the new owner
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* ```javascript
|
* ```javascript
|
||||||
* await contract.owner.set("0x1234567890123456789012345678901234567890");
|
* await contract.owner.set("0x1234567890123456789012345678901234567890");
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
public async set(address: string): Promise<TransactionResult> {
|
public async set(address: string): Promise<TransactionResult> {
|
||||||
return {
|
return {
|
||||||
receipt: await this.contractWrapper.sendTransaction("setOwner", [
|
receipt: await this.contractWrapper.sendTransaction("setOwner", [
|
||||||
address,
|
address,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { normalizePriceValue, setErc20Allowance } from "../../common/currency";
|
import { normalizePriceValue, setErc20Allowance } from "../../common/currency";
|
||||||
|
import { getPrebuiltInfo } from "../../common/legacy";
|
||||||
import { uploadOrExtractURIs } from "../../common/nft";
|
import { uploadOrExtractURIs } from "../../common/nft";
|
||||||
import { FEATURE_EDITION_SIGNATURE_MINTABLE } from "../../constants/erc1155-features";
|
import { FEATURE_EDITION_SIGNATURE_MINTABLE } from "../../constants/erc1155-features";
|
||||||
import type { NFTCollectionInitializer } from "../../contracts";
|
import type { NFTCollectionInitializer } from "../../contracts";
|
||||||
@@ -330,6 +331,12 @@ export class Erc1155SignatureMintable implements DetectableFeature {
|
|||||||
const signer = this.contractWrapper.getSigner();
|
const signer = this.contractWrapper.getSigner();
|
||||||
invariant(signer, "No signer available");
|
invariant(signer, "No signer available");
|
||||||
|
|
||||||
|
const contractInfo = await getPrebuiltInfo(
|
||||||
|
this.contractWrapper.readContract.address,
|
||||||
|
this.contractWrapper.getProvider(),
|
||||||
|
);
|
||||||
|
const isLegacyContract = contractInfo?.type === "TokenERC1155";
|
||||||
|
|
||||||
return await Promise.all(
|
return await Promise.all(
|
||||||
parsedRequests.map(async (m, i) => {
|
parsedRequests.map(async (m, i) => {
|
||||||
const uri = uris[i];
|
const uri = uris[i];
|
||||||
@@ -340,7 +347,7 @@ export class Erc1155SignatureMintable implements DetectableFeature {
|
|||||||
const signature = await this.contractWrapper.signTypedData(
|
const signature = await this.contractWrapper.signTypedData(
|
||||||
signer,
|
signer,
|
||||||
{
|
{
|
||||||
name: "TokenERC1155",
|
name: isLegacyContract ? "TokenERC1155" : "SignatureMintERC1155",
|
||||||
version: "1",
|
version: "1",
|
||||||
chainId,
|
chainId,
|
||||||
verifyingContract: this.contractWrapper.readContract.address,
|
verifyingContract: this.contractWrapper.readContract.address,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
CONTRACT_ADDRESSES,
|
|
||||||
getApprovedImplementation,
|
getApprovedImplementation,
|
||||||
SUPPORTED_CHAIN_IDS,
|
getDefaultTrustedForwarders,
|
||||||
} from "../../constants";
|
} from "../../constants";
|
||||||
import {
|
import {
|
||||||
EditionDropInitializer,
|
EditionDropInitializer,
|
||||||
@@ -296,16 +295,7 @@ export class ContractFactory extends ContractWrapper<TWFactory> {
|
|||||||
|
|
||||||
private async getDefaultTrustedForwarders(): Promise<string[]> {
|
private async getDefaultTrustedForwarders(): Promise<string[]> {
|
||||||
const chainId = await this.getChainID();
|
const chainId = await this.getChainID();
|
||||||
const chainEnum = SUPPORTED_CHAIN_IDS.find((c) => c === chainId);
|
return getDefaultTrustedForwarders(chainId);
|
||||||
const biconomyForwarder = chainEnum
|
|
||||||
? CONTRACT_ADDRESSES[chainEnum].biconomyForwarder
|
|
||||||
: constants.AddressZero;
|
|
||||||
const openzeppelinForwarder = chainEnum
|
|
||||||
? CONTRACT_ADDRESSES[chainEnum].openzeppelinForwarder
|
|
||||||
: constants.AddressZero;
|
|
||||||
return biconomyForwarder !== constants.AddressZero
|
|
||||||
? [openzeppelinForwarder, biconomyForwarder]
|
|
||||||
: [openzeppelinForwarder];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getImplementation(
|
private async getImplementation(
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
import { SmartContract } from "../contracts/smart-contract";
|
import { SmartContract } from "../contracts/smart-contract";
|
||||||
import { SDKOptions } from "../schema/sdk-options";
|
import { SDKOptions } from "../schema/sdk-options";
|
||||||
import { CurrencyValue } from "../types/index";
|
import { CurrencyValue } from "../types/index";
|
||||||
|
import type { AbstractWallet } from "../wallets";
|
||||||
import { WalletAuthenticator } from "./auth/wallet-authenticator";
|
import { WalletAuthenticator } from "./auth/wallet-authenticator";
|
||||||
import type { ContractMetadata } from "./classes";
|
import type { ContractMetadata } from "./classes";
|
||||||
import { ContractDeployer } from "./classes/contract-deployer";
|
import { ContractDeployer } from "./classes/contract-deployer";
|
||||||
@@ -39,6 +40,43 @@ import invariant from "tiny-invariant";
|
|||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
export class ThirdwebSDK extends RPCConnectionHandler {
|
export class ThirdwebSDK extends RPCConnectionHandler {
|
||||||
|
/**
|
||||||
|
* Get an instance of the thirdweb SDK based on an AbstractWallet
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```javascript
|
||||||
|
* import { ThirdwebSDK } from "@thirdweb-dev/sdk"
|
||||||
|
*
|
||||||
|
* const wallet = new AbstractWalletImplementation();
|
||||||
|
* const sdk = await ThirdwebSDK.fromWallet(wallet, "mainnet");
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param wallet - the implementation of the AbstractWallet class to use for signing
|
||||||
|
* @param network - the network (chain) to connect to (e.g. "mainnet", "rinkeby", "polygon", "mumbai"...) or a fully formed RPC url
|
||||||
|
* @param options - the SDK options to use
|
||||||
|
* @param storage - optional storage implementation to use
|
||||||
|
* @returns an instance of the SDK
|
||||||
|
*
|
||||||
|
* @beta
|
||||||
|
*/
|
||||||
|
static async fromWallet(
|
||||||
|
wallet: AbstractWallet,
|
||||||
|
network: ChainOrRpc,
|
||||||
|
options: SDKOptions = {},
|
||||||
|
storage: ThirdwebStorage = new ThirdwebStorage(),
|
||||||
|
) {
|
||||||
|
const signerOrProvider = getProviderForNetwork(network);
|
||||||
|
const provider = Signer.isSigner(signerOrProvider)
|
||||||
|
? signerOrProvider.provider
|
||||||
|
: typeof signerOrProvider === "string"
|
||||||
|
? getReadOnlyProvider(signerOrProvider)
|
||||||
|
: signerOrProvider;
|
||||||
|
|
||||||
|
const signer = await wallet.getSigner(provider);
|
||||||
|
|
||||||
|
return ThirdwebSDK.fromSigner(signer, network, options, storage);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an instance of the thirdweb SDK based on an existing ethers signer
|
* Get an instance of the thirdweb SDK based on an existing ethers signer
|
||||||
*
|
*
|
||||||
@@ -54,8 +92,8 @@ export class ThirdwebSDK extends RPCConnectionHandler {
|
|||||||
* @param signer - a ethers Signer to be used for transactions
|
* @param signer - a ethers Signer to be used for transactions
|
||||||
* @param network - the network (chain) to connect to (e.g. "mainnet", "rinkeby", "polygon", "mumbai"...) or a fully formed RPC url
|
* @param network - the network (chain) to connect to (e.g. "mainnet", "rinkeby", "polygon", "mumbai"...) or a fully formed RPC url
|
||||||
* @param options - the SDK options to use
|
* @param options - the SDK options to use
|
||||||
* @returns an instance of the SDK
|
|
||||||
* @param storage - optional storage implementation to use
|
* @param storage - optional storage implementation to use
|
||||||
|
* @returns an instance of the SDK
|
||||||
*
|
*
|
||||||
* @beta
|
* @beta
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -162,6 +162,7 @@ export const ExtraPublishMetadataSchemaInput = z
|
|||||||
.object({
|
.object({
|
||||||
displayName: z.string().optional(),
|
displayName: z.string().optional(),
|
||||||
description: z.string().optional(),
|
description: z.string().optional(),
|
||||||
|
defaultValue: z.string().optional(),
|
||||||
})
|
})
|
||||||
.catchall(z.any()),
|
.catchall(z.any()),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -8,3 +8,4 @@ export * from "./token-erc20";
|
|||||||
export * from "./token-erc721";
|
export * from "./token-erc721";
|
||||||
export * from "./token-erc1155";
|
export * from "./token-erc1155";
|
||||||
export * from "./vote";
|
export * from "./vote";
|
||||||
|
export * from "./custom";
|
||||||
|
|||||||
@@ -80,4 +80,4 @@ export type SDKOptions = z.input<typeof SDKOptionsSchema>;
|
|||||||
/**
|
/**
|
||||||
* @internal
|
* @internal
|
||||||
*/
|
*/
|
||||||
export type SDKOptionsOutput = z.output<typeof SDKOptionsSchema>;
|
export type SDKOptionsOutput = z.output<typeof SDKOptionsSchema>;
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { AbstractWallet } from "../types/abstract";
|
||||||
|
import {
|
||||||
|
TypedDataDomain,
|
||||||
|
TypedDataField,
|
||||||
|
} from "@ethersproject/abstract-signer";
|
||||||
|
import { ethers } from "ethers";
|
||||||
|
import { AwsKmsSigner, AwsKmsSignerCredentials } from "ethers-aws-kms-signer";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a wallet instance using a private key stored in AWS KMS.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```javascript
|
||||||
|
* import { ThirdwebSDK } from "@thirdweb-dev/sdk"
|
||||||
|
* import { AwsKmsWallet } from "@thirdweb-dev/sdk/evm/wallets"
|
||||||
|
*
|
||||||
|
* const wallet = new AwsKmsallet({
|
||||||
|
* region: "us-east-1",
|
||||||
|
* accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||||
|
* secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||||
|
* sessionToken: process.env.AWS_SESSION_TOKEN,
|
||||||
|
* keyId: process.env.AWS_KEY_ID,
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* const sdk = await ThirdwebSDK.fromWallet(wallet, "mainnet");
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class AwsKmsWallet extends AbstractWallet {
|
||||||
|
private cachedSigner: AwsKmsSigner;
|
||||||
|
|
||||||
|
constructor(options: AwsKmsSignerCredentials) {
|
||||||
|
super();
|
||||||
|
this.cachedSigner = this.updateSigner(new AwsKmsSigner(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSigner(
|
||||||
|
provider?: ethers.providers.Provider,
|
||||||
|
): Promise<ethers.Signer> {
|
||||||
|
if (provider) {
|
||||||
|
this.cachedSigner = this.updateSigner(
|
||||||
|
this.cachedSigner.connect(provider),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.cachedSigner;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add _signTypedData method onto the signer for now so we don't need to reimpliment
|
||||||
|
// The entire AWS KMS signer repository and maintain it ourselves.
|
||||||
|
private updateSigner(signer: AwsKmsSigner): AwsKmsSigner {
|
||||||
|
(signer as any)._signTypedData = async function (
|
||||||
|
domain: TypedDataDomain,
|
||||||
|
types: Record<string, Array<TypedDataField>>,
|
||||||
|
value: Record<string, any>,
|
||||||
|
) {
|
||||||
|
const hash = ethers.utils._TypedDataEncoder.hash(domain, types, value);
|
||||||
|
return signer._signDigest(hash);
|
||||||
|
};
|
||||||
|
|
||||||
|
return signer;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { AbstractWallet } from "../types/abstract";
|
||||||
|
import {
|
||||||
|
GetSecretValueCommand,
|
||||||
|
SecretsManagerClient,
|
||||||
|
SecretsManagerClientConfig,
|
||||||
|
} from "@aws-sdk/client-secrets-manager";
|
||||||
|
import { ethers } from "ethers";
|
||||||
|
|
||||||
|
export type AwsSecretsManagerWalletOptions = {
|
||||||
|
secretId: string;
|
||||||
|
secretKeyName: string;
|
||||||
|
awsConfig: SecretsManagerClientConfig;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a wallet instance using a private key stored in AWS Secrets Manager.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```javascript
|
||||||
|
* import { ThirdwebSDK } from "@thirdweb-dev/sdk"
|
||||||
|
* import { AwsSecretsManagerWallet } from "@thirdweb-dev/sdk/evm/wallets"
|
||||||
|
*
|
||||||
|
* const wallet = new AwsSecretsManagerWallet({
|
||||||
|
* secretName: "my-secret",
|
||||||
|
* secretKeyName: "private-key",
|
||||||
|
* awsConfig: {
|
||||||
|
* region: "us-east-1",
|
||||||
|
* credentials: {
|
||||||
|
* accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||||
|
* secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||||
|
* },
|
||||||
|
* }
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* const sdk = await ThirdwebSDK.fromWallet(wallet, "mainnet");
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class AwsSecretsManagerWallet extends AbstractWallet {
|
||||||
|
private secretId: string;
|
||||||
|
private secretKeyName: string;
|
||||||
|
private client: SecretsManagerClient;
|
||||||
|
private cachedSigner: ethers.Signer | undefined;
|
||||||
|
|
||||||
|
constructor(options: AwsSecretsManagerWalletOptions) {
|
||||||
|
super();
|
||||||
|
this.secretId = options.secretId;
|
||||||
|
this.secretKeyName = options.secretKeyName;
|
||||||
|
this.client = new SecretsManagerClient(options.awsConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSigner(
|
||||||
|
provider?: ethers.providers.Provider,
|
||||||
|
): Promise<ethers.Signer> {
|
||||||
|
if (this.cachedSigner) {
|
||||||
|
return this.cachedSigner;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this.client.send(
|
||||||
|
new GetSecretValueCommand({
|
||||||
|
SecretId: this.secretId,
|
||||||
|
VersionStage: "AWSCURRENT", // VersionStage defaults to AWSCURRENT if unspecified
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!res || !res.SecretString) {
|
||||||
|
throw new Error(`No secret found at ${this.secretId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const privateKey = JSON.parse(res.SecretString)[this.secretKeyName];
|
||||||
|
if (!privateKey) {
|
||||||
|
throw new Error(
|
||||||
|
`Secret ${this.secretId} does not have key ${this.secretKeyName}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cachedSigner = new ethers.Wallet(privateKey, provider);
|
||||||
|
return this.cachedSigner;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./aws-secrets-manager";
|
||||||
|
export * from "./aws-kms";
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./core";
|
||||||
|
export * from "./types";
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { ethers } from "ethers";
|
||||||
|
|
||||||
|
export abstract class AbstractWallet {
|
||||||
|
abstract getSigner(
|
||||||
|
provider?: ethers.providers.Provider,
|
||||||
|
): Promise<ethers.Signer>;
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from "./abstract";
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
import { toCurrencyValue } from "../utils/token";
|
import { toCurrencyValue } from "../utils/token";
|
||||||
import {
|
import {
|
||||||
Amount,
|
Amount,
|
||||||
CandyMachineEndSettings,
|
CandyMachineV2EndSettings,
|
||||||
DateTime,
|
DateTime,
|
||||||
Metaplex,
|
Metaplex,
|
||||||
sol,
|
sol,
|
||||||
@@ -168,8 +168,7 @@ export class ClaimConditions {
|
|||||||
if (parsed.currencyAddress && parsed.price) {
|
if (parsed.currencyAddress && parsed.price) {
|
||||||
const fetchedToken = await this.metaplex
|
const fetchedToken = await this.metaplex
|
||||||
.tokens()
|
.tokens()
|
||||||
.findMintByAddress({ address: new PublicKey(parsed.currencyAddress) })
|
.findMintByAddress({ address: new PublicKey(parsed.currencyAddress) });
|
||||||
.run();
|
|
||||||
price = token(Number(parsed.price), fetchedToken.decimals);
|
price = token(Number(parsed.price), fetchedToken.decimals);
|
||||||
tokenMint = fetchedToken.address;
|
tokenMint = fetchedToken.address;
|
||||||
}
|
}
|
||||||
@@ -180,7 +179,7 @@ export class ClaimConditions {
|
|||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
// max claimable
|
// max claimable
|
||||||
const endSettings: CandyMachineEndSettings | null | undefined =
|
const endSettings: CandyMachineV2EndSettings | null | undefined =
|
||||||
parsed.maxClaimable
|
parsed.maxClaimable
|
||||||
? parsed.maxClaimable === "unlimited"
|
? parsed.maxClaimable === "unlimited"
|
||||||
? null
|
? null
|
||||||
@@ -194,20 +193,22 @@ export class ClaimConditions {
|
|||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
...(wallet && { wallet }),
|
...(wallet && { wallet }),
|
||||||
...(tokenMint && { tokenMint }),
|
...(tokenMint
|
||||||
|
? { tokenMint }
|
||||||
|
: // if passing currencyAddress explcitly as null we need to honor that!
|
||||||
|
parsed.currencyAddress === null
|
||||||
|
? { tokenMint: null }
|
||||||
|
: {}),
|
||||||
...(price && { price }),
|
...(price && { price }),
|
||||||
...(goLiveDate && { goLiveDate }),
|
...(goLiveDate && { goLiveDate }),
|
||||||
...(sellerFeeBasisPoints && { sellerFeeBasisPoints }),
|
...(sellerFeeBasisPoints && { sellerFeeBasisPoints }),
|
||||||
...(endSettings !== undefined && { endSettings }),
|
...(endSettings !== undefined && { endSettings }),
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = await this.metaplex
|
const result = await this.metaplex.candyMachinesV2().update({
|
||||||
.candyMachines()
|
candyMachine: await this.getCandyMachine(),
|
||||||
.update({
|
...data,
|
||||||
candyMachine: await this.getCandyMachine(),
|
});
|
||||||
...data,
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
signature: result.response.signature,
|
signature: result.response.signature,
|
||||||
@@ -216,8 +217,7 @@ export class ClaimConditions {
|
|||||||
|
|
||||||
private async getCandyMachine() {
|
private async getCandyMachine() {
|
||||||
return this.metaplex
|
return this.metaplex
|
||||||
.candyMachines()
|
.candyMachinesV2()
|
||||||
.findByAddress({ address: this.dropMintAddress })
|
.findByAddress({ address: this.dropMintAddress });
|
||||||
.run();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -234,7 +234,7 @@ export class Deployer {
|
|||||||
// initialize candy machine with default config
|
// initialize candy machine with default config
|
||||||
// final claim conditions can be updated later
|
// final claim conditions can be updated later
|
||||||
const candyMachineTx = await this.metaplex
|
const candyMachineTx = await this.metaplex
|
||||||
.candyMachines()
|
.candyMachinesV2()
|
||||||
.builders()
|
.builders()
|
||||||
.create({
|
.create({
|
||||||
itemsAvailable: toBigNumber(candyMachineInfo.totalSupply),
|
itemsAvailable: toBigNumber(candyMachineInfo.totalSupply),
|
||||||
@@ -264,23 +264,20 @@ export class Deployer {
|
|||||||
const block = await this.metaplex.connection.getLatestBlockhash();
|
const block = await this.metaplex.connection.getLatestBlockhash();
|
||||||
const dropTx = collectionTx
|
const dropTx = collectionTx
|
||||||
.add(candyMachineTx)
|
.add(candyMachineTx)
|
||||||
.setFeePayer(this.metaplex.identity())
|
.setFeePayer(this.metaplex.identity());
|
||||||
.setTransactionOptions({
|
const regTransaction = TransactionBuilder.make()
|
||||||
blockhash: block.blockhash,
|
|
||||||
feePayer: this.metaplex.identity().publicKey,
|
|
||||||
lastValidBlockHeight: block.lastValidBlockHeight,
|
|
||||||
});
|
|
||||||
const regTx = TransactionBuilder.make()
|
|
||||||
.add(...registryInstructions)
|
.add(...registryInstructions)
|
||||||
.setFeePayer(this.metaplex.identity())
|
.setFeePayer(this.metaplex.identity())
|
||||||
.setTransactionOptions({
|
.toTransaction({
|
||||||
blockhash: block.blockhash,
|
blockhash: block.blockhash,
|
||||||
feePayer: this.metaplex.identity().publicKey,
|
|
||||||
lastValidBlockHeight: block.lastValidBlockHeight,
|
lastValidBlockHeight: block.lastValidBlockHeight,
|
||||||
});
|
});
|
||||||
const dropSigners = [this.metaplex.identity(), ...dropTx.getSigners()];
|
const dropSigners = [this.metaplex.identity(), ...dropTx.getSigners()];
|
||||||
const { keypairs } = getSignerHistogram(dropSigners);
|
const { keypairs } = getSignerHistogram(dropSigners);
|
||||||
const dropTransaction = dropTx.toTransaction();
|
const dropTransaction = dropTx.toTransaction({
|
||||||
|
blockhash: block.blockhash,
|
||||||
|
lastValidBlockHeight: block.lastValidBlockHeight,
|
||||||
|
});
|
||||||
// partially sign with the PDA keypairs
|
// partially sign with the PDA keypairs
|
||||||
if (keypairs.length > 0) {
|
if (keypairs.length > 0) {
|
||||||
dropTransaction.partialSign(...keypairs);
|
dropTransaction.partialSign(...keypairs);
|
||||||
@@ -288,7 +285,7 @@ export class Deployer {
|
|||||||
// make the connected wallet sign both candyMachine + registry transactions
|
// make the connected wallet sign both candyMachine + registry transactions
|
||||||
const signedTx = await this.metaplex
|
const signedTx = await this.metaplex
|
||||||
.identity()
|
.identity()
|
||||||
.signAllTransactions([dropTransaction, regTx.toTransaction()]);
|
.signAllTransactions([dropTransaction, regTransaction]);
|
||||||
|
|
||||||
// send the signed transactions *sequentially* the drop creation needs to succeed first before adding to registry
|
// send the signed transactions *sequentially* the drop creation needs to succeed first before adding to registry
|
||||||
const signatures: string[] = [];
|
const signatures: string[] = [];
|
||||||
@@ -301,7 +298,10 @@ export class Deployer {
|
|||||||
// wait for confirmations in parallel
|
// wait for confirmations in parallel
|
||||||
const confirmations = await Promise.all(
|
const confirmations = await Promise.all(
|
||||||
signatures.map((sig) => {
|
signatures.map((sig) => {
|
||||||
return this.metaplex.rpc().confirmTransaction(sig);
|
return this.metaplex.rpc().confirmTransaction(sig, {
|
||||||
|
blockhash: block.blockhash,
|
||||||
|
lastValidBlockHeight: block.lastValidBlockHeight,
|
||||||
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
QueryAllParams,
|
QueryAllParams,
|
||||||
DEFAULT_QUERY_ALL_COUNT,
|
QueryAllParamsSchema,
|
||||||
} from "../../../core/schema/QueryParams";
|
} from "../../../core/schema/QueryParams";
|
||||||
import { NFT } from "../../../core/schema/nft";
|
import { NFT } from "../../../core/schema/nft";
|
||||||
import {
|
import {
|
||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
} from "../../constants/addresses";
|
} from "../../constants/addresses";
|
||||||
import { TransactionResult } from "../../types/common";
|
import { TransactionResult } from "../../types/common";
|
||||||
import { CreatorOutput } from "../../types/programs";
|
import { CreatorOutput } from "../../types/programs";
|
||||||
import { getPublicRpc } from "../../utils/urls";
|
|
||||||
import { parseCreators } from "./creators-helper";
|
import { parseCreators } from "./creators-helper";
|
||||||
import {
|
import {
|
||||||
findMasterEditionV2Pda,
|
findMasterEditionV2Pda,
|
||||||
@@ -49,12 +48,9 @@ export class NFTHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getRaw(nftAddress: string) {
|
async getRaw(nftAddress: string) {
|
||||||
return await this.metaplex
|
return await this.metaplex.nfts().findByMint({
|
||||||
.nfts()
|
mintAddress: new PublicKey(nftAddress),
|
||||||
.findByMint({
|
});
|
||||||
mintAddress: new PublicKey(nftAddress),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(nftAddress: string): Promise<NFT> {
|
async get(nftAddress: string): Promise<NFT> {
|
||||||
@@ -67,14 +63,11 @@ export class NFTHelper {
|
|||||||
nftAddress: string,
|
nftAddress: string,
|
||||||
quantity: number = 1,
|
quantity: number = 1,
|
||||||
): Promise<TransactionResult> {
|
): Promise<TransactionResult> {
|
||||||
const result = await this.metaplex
|
const result = await this.metaplex.nfts().send({
|
||||||
.nfts()
|
mintAddress: new PublicKey(nftAddress),
|
||||||
.send({
|
toOwner: new PublicKey(receiverAddress),
|
||||||
mintAddress: new PublicKey(nftAddress),
|
amount: token(quantity, 0),
|
||||||
toOwner: new PublicKey(receiverAddress),
|
});
|
||||||
amount: token(quantity, 0),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
signature: result.response.signature,
|
signature: result.response.signature,
|
||||||
@@ -102,15 +95,10 @@ export class NFTHelper {
|
|||||||
|
|
||||||
async ownerOf(nftAddress: string): Promise<string | undefined> {
|
async ownerOf(nftAddress: string): Promise<string | undefined> {
|
||||||
try {
|
try {
|
||||||
// TODO switch back to normal connection when alchemy supports getTokenLargestAccounts
|
const largestAccounts = await this.connection.getTokenLargestAccounts(
|
||||||
const connection = new Connection(
|
|
||||||
getPublicRpc(this.metaplex),
|
|
||||||
"confirmed",
|
|
||||||
);
|
|
||||||
const largestAccounts = await connection.getTokenLargestAccounts(
|
|
||||||
new PublicKey(nftAddress),
|
new PublicKey(nftAddress),
|
||||||
);
|
);
|
||||||
const largestAccountInfo = await connection.getParsedAccountInfo(
|
const largestAccountInfo = await this.connection.getParsedAccountInfo(
|
||||||
largestAccounts.value[0].address,
|
largestAccounts.value[0].address,
|
||||||
);
|
);
|
||||||
const parsedData = largestAccountInfo?.value?.data as ParsedAccountData;
|
const parsedData = largestAccountInfo?.value?.data as ParsedAccountData;
|
||||||
@@ -121,13 +109,73 @@ export class NFTHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async supplyOf(nftAddress: string): Promise<number> {
|
||||||
|
let originalEdition;
|
||||||
|
|
||||||
|
const originalEditionAccount = await this.metaplex
|
||||||
|
.rpc()
|
||||||
|
.getAccount(findMasterEditionV2Pda(new PublicKey(nftAddress)));
|
||||||
|
|
||||||
|
if (originalEditionAccount.exists) {
|
||||||
|
originalEdition = toNftOriginalEdition(
|
||||||
|
toOriginalEditionAccount(originalEditionAccount),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add one to supply to account for the master edition
|
||||||
|
return originalEdition.supply.toNumber() + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async totalSupply(collectionAddress: string): Promise<number> {
|
||||||
|
const metadataAddresses = await this.getAllMetadataAddresses(
|
||||||
|
collectionAddress,
|
||||||
|
);
|
||||||
|
return metadataAddresses.length;
|
||||||
|
}
|
||||||
|
|
||||||
async getAll(
|
async getAll(
|
||||||
collectionAddress: string,
|
collectionAddress: string,
|
||||||
queryParams?: QueryAllParams,
|
queryParams?: QueryAllParams,
|
||||||
): Promise<NFT[]> {
|
): Promise<NFT[]> {
|
||||||
|
const { start, count } = QueryAllParamsSchema.parse(queryParams);
|
||||||
|
|
||||||
|
const metadataAddresses = await this.getAllMetadataAddresses(
|
||||||
|
collectionAddress,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Metaplex GmaBuilder has a weird thing where they always start at 1 not 0
|
||||||
|
// so we workaround it by adding an extra address, and shifting the count to get the actual count we want
|
||||||
|
const fixedMetadataAddresses = (
|
||||||
|
start === 0 ? [PublicKey.default] : []
|
||||||
|
).concat(metadataAddresses);
|
||||||
|
const metadataInfos = await GmaBuilder.make(
|
||||||
|
this.metaplex,
|
||||||
|
fixedMetadataAddresses,
|
||||||
|
).getBetween(start, start === 0 ? count + 1 : start + count);
|
||||||
|
|
||||||
|
// Parse each account into a metadata account
|
||||||
|
const metadataParsed: Metadata<JsonMetadata<string>>[] = [];
|
||||||
|
for (const metadataInfo of metadataInfos) {
|
||||||
|
if (metadataInfo.exists) {
|
||||||
|
try {
|
||||||
|
metadataParsed.push(toMetadata(toMetadataAccount(metadataInfo)));
|
||||||
|
} catch (error) {
|
||||||
|
// no-op
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally, fetch the metadata + mint for each in parallel
|
||||||
|
const nfts = await Promise.all(
|
||||||
|
metadataParsed.map((m) => this.toNFTMetadata(m)),
|
||||||
|
);
|
||||||
|
return nfts;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAllMetadataAddresses(collectionAddress: string) {
|
||||||
const collectionKey = new PublicKey(collectionAddress);
|
const collectionKey = new PublicKey(collectionAddress);
|
||||||
const start = queryParams?.start || 0;
|
|
||||||
const count = queryParams?.count || DEFAULT_QUERY_ALL_COUNT;
|
|
||||||
|
|
||||||
// TODO cache signatures <> transactions mapping in memory so pagination doesn't re-request this everytime
|
// TODO cache signatures <> transactions mapping in memory so pagination doesn't re-request this everytime
|
||||||
const allSignatures: ConfirmedSignatureInfo[] = [];
|
const allSignatures: ConfirmedSignatureInfo[] = [];
|
||||||
@@ -205,52 +253,7 @@ export class NFTHelper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Metaplex GmaBuilder has a weird thing where they always start at 1 not 0
|
return metadataAddresses;
|
||||||
// so we workaround it by adding an extra address, and shifting the count to get the actual count we want
|
|
||||||
const fixedMetadataAddresses = (
|
|
||||||
start === 0 ? [PublicKey.default] : []
|
|
||||||
).concat(metadataAddresses);
|
|
||||||
const metadataInfos = await GmaBuilder.make(
|
|
||||||
this.metaplex,
|
|
||||||
fixedMetadataAddresses,
|
|
||||||
).getBetween(start, start === 0 ? count + 1 : start + count);
|
|
||||||
|
|
||||||
// parse each account into a metadata account
|
|
||||||
const metadataParsed: Metadata<JsonMetadata<string>>[] = [];
|
|
||||||
for (const metadataInfo of metadataInfos) {
|
|
||||||
if (metadataInfo.exists) {
|
|
||||||
try {
|
|
||||||
metadataParsed.push(toMetadata(toMetadataAccount(metadataInfo)));
|
|
||||||
} catch (error) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// finally fetch the metadta + mint for each in parallel
|
|
||||||
const nfts = await Promise.all(
|
|
||||||
metadataParsed.map((m) => this.toNFTMetadata(m)),
|
|
||||||
);
|
|
||||||
return nfts;
|
|
||||||
}
|
|
||||||
|
|
||||||
async supplyOf(nftAddress: string): Promise<number> {
|
|
||||||
let originalEdition;
|
|
||||||
|
|
||||||
const originalEditionAccount = await this.metaplex
|
|
||||||
.rpc()
|
|
||||||
.getAccount(findMasterEditionV2Pda(new PublicKey(nftAddress)));
|
|
||||||
|
|
||||||
if (originalEditionAccount.exists) {
|
|
||||||
originalEdition = toNftOriginalEdition(
|
|
||||||
toOriginalEditionAccount(originalEditionAccount),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add one to supply to account for the master edition
|
|
||||||
return originalEdition.supply.toNumber() + 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async toNFTMetadata(
|
async toNFTMetadata(
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ import { WalletAccount } from "../types/common";
|
|||||||
import { RegisteredProgram } from "../types/programs";
|
import { RegisteredProgram } from "../types/programs";
|
||||||
import { UserWallet } from "./user-wallet";
|
import { UserWallet } from "./user-wallet";
|
||||||
import {
|
import {
|
||||||
CandyMachine,
|
CandyMachineV2,
|
||||||
InstructionWithSigners,
|
InstructionWithSigners,
|
||||||
Metadata,
|
Metadata,
|
||||||
Metaplex,
|
Metaplex,
|
||||||
Pda,
|
Pda,
|
||||||
TokenProgram,
|
TokenGpaBuilder,
|
||||||
} from "@metaplex-foundation/js";
|
} from "@metaplex-foundation/js";
|
||||||
import { TokenStandard } from "@metaplex-foundation/mpl-token-metadata";
|
import { TokenStandard } from "@metaplex-foundation/mpl-token-metadata";
|
||||||
import type { BN, Idl } from "@project-serum/anchor";
|
import type { BN, Idl } from "@project-serum/anchor";
|
||||||
@@ -38,9 +38,8 @@ export class Registry {
|
|||||||
public async getProgramType(address: string) {
|
public async getProgramType(address: string) {
|
||||||
try {
|
try {
|
||||||
const candyMachine = await this.metaplex
|
const candyMachine = await this.metaplex
|
||||||
.candyMachines()
|
.candyMachinesV2()
|
||||||
.findByAddress({ address: new PublicKey(address) })
|
.findByAddress({ address: new PublicKey(address) });
|
||||||
.run();
|
|
||||||
if (candyMachine) {
|
if (candyMachine) {
|
||||||
return "nft-drop";
|
return "nft-drop";
|
||||||
}
|
}
|
||||||
@@ -49,8 +48,7 @@ export class Registry {
|
|||||||
}
|
}
|
||||||
const metadata = await this.metaplex
|
const metadata = await this.metaplex
|
||||||
.nfts()
|
.nfts()
|
||||||
.findByMint({ mintAddress: new PublicKey(address) })
|
.findByMint({ mintAddress: new PublicKey(address) });
|
||||||
.run();
|
|
||||||
|
|
||||||
if (metadata) {
|
if (metadata) {
|
||||||
if (metadata.collectionDetails) {
|
if (metadata.collectionDetails) {
|
||||||
@@ -198,7 +196,10 @@ export class Registry {
|
|||||||
return account.exists;
|
return account.exists;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getDropForCollection(candyMachines: CandyMachine[], meta: Metadata) {
|
private getDropForCollection(
|
||||||
|
candyMachines: CandyMachineV2[],
|
||||||
|
meta: Metadata,
|
||||||
|
) {
|
||||||
return candyMachines.find(
|
return candyMachines.find(
|
||||||
(candyMachine) =>
|
(candyMachine) =>
|
||||||
candyMachine.collectionMintAddress?.toBase58() ===
|
candyMachine.collectionMintAddress?.toBase58() ===
|
||||||
@@ -211,18 +212,12 @@ export class Registry {
|
|||||||
walletAddress: string,
|
walletAddress: string,
|
||||||
): Promise<WalletAccount[]> {
|
): Promise<WalletAccount[]> {
|
||||||
const mints = await this.getOwnedTokenAddreses(walletAddress);
|
const mints = await this.getOwnedTokenAddreses(walletAddress);
|
||||||
const metadatas = await this.metaplex
|
const metadatas = await this.metaplex.nfts().findAllByMintList({ mints });
|
||||||
.nfts()
|
|
||||||
.findAllByMintList({ mints })
|
|
||||||
.run();
|
|
||||||
|
|
||||||
const candyMachines = await this.metaplex
|
const candyMachines = await this.metaplex.candyMachinesV2().findAllBy({
|
||||||
.candyMachines()
|
type: "authority",
|
||||||
.findAllBy({
|
publicKey: new PublicKey(walletAddress),
|
||||||
type: "authority",
|
});
|
||||||
publicKey: new PublicKey(walletAddress),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
|
|
||||||
return metadatas
|
return metadatas
|
||||||
.map((mintMetadata) => {
|
.map((mintMetadata) => {
|
||||||
@@ -260,7 +255,7 @@ export class Registry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async getOwnedTokenAddreses(walletAddress: string) {
|
private async getOwnedTokenAddreses(walletAddress: string) {
|
||||||
return await TokenProgram.tokenAccounts(this.metaplex)
|
return await new TokenGpaBuilder(this.metaplex)
|
||||||
.selectMint()
|
.selectMint()
|
||||||
.whereOwner(new PublicKey(walletAddress))
|
.whereOwner(new PublicKey(walletAddress))
|
||||||
.getDataAsPublicKeys();
|
.getDataAsPublicKeys();
|
||||||
|
|||||||
@@ -140,6 +140,18 @@ export class NFTCollection {
|
|||||||
return this.nft.getAll(this.publicKey.toBase58(), queryParams);
|
return this.nft.getAll(this.publicKey.toBase58(), queryParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the total number of nfts minted on this program
|
||||||
|
* @returns the total number of NFTs minted on this program
|
||||||
|
*
|
||||||
|
* ```jsx
|
||||||
|
* const totalSupply = await program.totalSupply();
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
async totalSupply(): Promise<number> {
|
||||||
|
return this.nft.totalSupply(this.publicKey.toBase58());
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the NFT balance of the connected wallet
|
* Get the NFT balance of the connected wallet
|
||||||
* @returns the NFT balance
|
* @returns the NFT balance
|
||||||
@@ -297,20 +309,17 @@ export class NFTCollection {
|
|||||||
const name =
|
const name =
|
||||||
typeof metadata === "string" ? "" : metadata.name?.toString() || "";
|
typeof metadata === "string" ? "" : metadata.name?.toString() || "";
|
||||||
const collection = await this.getCollection();
|
const collection = await this.getCollection();
|
||||||
const { nft } = await this.metaplex
|
const { nft } = await this.metaplex.nfts().create({
|
||||||
.nfts()
|
name,
|
||||||
.create({
|
uri,
|
||||||
name,
|
creators: collection.creators,
|
||||||
uri,
|
sellerFeeBasisPoints: collection.sellerFeeBasisPoints,
|
||||||
creators: collection.creators,
|
collection: this.publicKey,
|
||||||
sellerFeeBasisPoints: collection.sellerFeeBasisPoints,
|
collectionAuthority: this.metaplex.identity(),
|
||||||
collection: this.publicKey,
|
tokenOwner: new PublicKey(to),
|
||||||
collectionAuthority: this.metaplex.identity(),
|
// Always sets max supply to unlimited so editions can be minted
|
||||||
tokenOwner: new PublicKey(to),
|
maxSupply: null,
|
||||||
// Always sets max supply to unlimited so editions can be minted
|
});
|
||||||
maxSupply: null,
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
|
|
||||||
return nft.address.toBase58();
|
return nft.address.toBase58();
|
||||||
}
|
}
|
||||||
@@ -411,13 +420,11 @@ export class NFTCollection {
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
async burn(nftAddress: string): Promise<TransactionResult> {
|
async burn(nftAddress: string): Promise<TransactionResult> {
|
||||||
const tx = await this.metaplex
|
const tx = await this.metaplex.nfts().delete({
|
||||||
.nfts()
|
mintAddress: new PublicKey(nftAddress),
|
||||||
.delete({
|
collection: this.publicKey,
|
||||||
mintAddress: new PublicKey(nftAddress),
|
});
|
||||||
collection: this.publicKey,
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return {
|
return {
|
||||||
signature: tx.response.signature,
|
signature: tx.response.signature,
|
||||||
};
|
};
|
||||||
@@ -458,8 +465,7 @@ export class NFTCollection {
|
|||||||
allNfts.map(async (nft) => {
|
allNfts.map(async (nft) => {
|
||||||
const metaplexNft = await this.metaplex
|
const metaplexNft = await this.metaplex
|
||||||
.nfts()
|
.nfts()
|
||||||
.findByMint({ mintAddress: new PublicKey(nft.metadata.id) })
|
.findByMint({ mintAddress: new PublicKey(nft.metadata.id) });
|
||||||
.run();
|
|
||||||
|
|
||||||
txs.push(
|
txs.push(
|
||||||
this.metaplex
|
this.metaplex
|
||||||
@@ -479,16 +485,10 @@ export class NFTCollection {
|
|||||||
|
|
||||||
return await sendMultipartTransaction(txs, this.metaplex);
|
return await sendMultipartTransaction(txs, this.metaplex);
|
||||||
} else {
|
} else {
|
||||||
const tx = await this.metaplex
|
const tx = await this.metaplex.nfts().update({
|
||||||
.nfts()
|
nftOrSft: await this.getCollection(),
|
||||||
.update({
|
creators: enforceCreator(creators, this.metaplex.identity().publicKey),
|
||||||
nftOrSft: await this.getCollection(),
|
});
|
||||||
creators: enforceCreator(
|
|
||||||
creators,
|
|
||||||
this.metaplex.identity().publicKey,
|
|
||||||
),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -526,8 +526,7 @@ export class NFTCollection {
|
|||||||
allNfts.map(async (nft) => {
|
allNfts.map(async (nft) => {
|
||||||
const metaplexNft = await this.metaplex
|
const metaplexNft = await this.metaplex
|
||||||
.nfts()
|
.nfts()
|
||||||
.findByMint({ mintAddress: new PublicKey(nft.metadata.id) })
|
.findByMint({ mintAddress: new PublicKey(nft.metadata.id) });
|
||||||
.run();
|
|
||||||
|
|
||||||
txs.push(
|
txs.push(
|
||||||
this.metaplex.nfts().builders().update({
|
this.metaplex.nfts().builders().update({
|
||||||
@@ -541,13 +540,10 @@ export class NFTCollection {
|
|||||||
|
|
||||||
return await sendMultipartTransaction(txs, this.metaplex);
|
return await sendMultipartTransaction(txs, this.metaplex);
|
||||||
} else {
|
} else {
|
||||||
const tx = await this.metaplex
|
const tx = await this.metaplex.nfts().update({
|
||||||
.nfts()
|
nftOrSft: await this.getCollection(),
|
||||||
.update({
|
sellerFeeBasisPoints,
|
||||||
nftOrSft: await this.getCollection(),
|
});
|
||||||
sellerFeeBasisPoints,
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -560,7 +556,6 @@ export class NFTCollection {
|
|||||||
private async getCollection() {
|
private async getCollection() {
|
||||||
return await this.metaplex
|
return await this.metaplex
|
||||||
.nfts()
|
.nfts()
|
||||||
.findByMint({ mintAddress: this.publicKey })
|
.findByMint({ mintAddress: this.publicKey });
|
||||||
.run();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
import {
|
||||||
|
QueryAllParams,
|
||||||
|
QueryAllParamsSchema,
|
||||||
|
} from "../../core/schema/QueryParams";
|
||||||
import {
|
import {
|
||||||
CommonNFTInput,
|
CommonNFTInput,
|
||||||
NFT,
|
NFT,
|
||||||
@@ -16,7 +20,7 @@ import { CreatorInput, CreatorOutput } from "../types/programs";
|
|||||||
import { sendMultipartTransaction } from "../utils/transactions";
|
import { sendMultipartTransaction } from "../utils/transactions";
|
||||||
import { getNework } from "../utils/urls";
|
import { getNework } from "../utils/urls";
|
||||||
import {
|
import {
|
||||||
CandyMachineItem,
|
CandyMachineV2Item,
|
||||||
Metaplex,
|
Metaplex,
|
||||||
toBigNumber,
|
toBigNumber,
|
||||||
} from "@metaplex-foundation/js";
|
} from "@metaplex-foundation/js";
|
||||||
@@ -99,8 +103,7 @@ export class NFTDrop {
|
|||||||
invariant(info.collectionMintAddress, "Collection mint address not found");
|
invariant(info.collectionMintAddress, "Collection mint address not found");
|
||||||
const metadata = await this.metaplex
|
const metadata = await this.metaplex
|
||||||
.nfts()
|
.nfts()
|
||||||
.findByMint({ mintAddress: info.collectionMintAddress })
|
.findByMint({ mintAddress: info.collectionMintAddress });
|
||||||
.run();
|
|
||||||
|
|
||||||
return (await this.nft.toNFTMetadata(metadata)).metadata;
|
return (await this.nft.toNFTMetadata(metadata)).metadata;
|
||||||
}
|
}
|
||||||
@@ -166,22 +169,37 @@ export class NFTDrop {
|
|||||||
* console.log(nfts[0].metadata.name);
|
* console.log(nfts[0].metadata.name);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
async getAll(): Promise<NFT[]> {
|
async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
|
||||||
// TODO: Add pagination to get NFT functions
|
const parsedQueryParams = QueryAllParamsSchema.parse(queryParams);
|
||||||
const info = await this.getCandyMachine();
|
const info = await this.getCandyMachine();
|
||||||
const claimed = await this.getAllClaimed();
|
|
||||||
return await Promise.all(
|
// First, get all the claimed NFTs within the query params range
|
||||||
info.items.map(async (item) => {
|
const claimedNfts = await this.getAllClaimed(parsedQueryParams);
|
||||||
// Check if the NFT has been claimed
|
const totalClaimed = await this.totalClaimedSupply();
|
||||||
// TODO: This only checks name/uri which is potentially not unique
|
|
||||||
const claimedNFT = claimed.find(
|
// Then filter out all claimed NFTs from items to leave only unclaimed remaining
|
||||||
|
const unclaimedItems: CandyMachineV2Item[] = [];
|
||||||
|
info.items.forEach((item) => {
|
||||||
|
const isClaimed =
|
||||||
|
claimedNfts.filter(
|
||||||
(nft) =>
|
(nft) =>
|
||||||
nft.metadata.name === item.name && nft.metadata.uri === item.uri,
|
nft.metadata.name === item.name && nft.metadata.uri === item.uri,
|
||||||
);
|
).length > 0;
|
||||||
if (claimedNFT) {
|
|
||||||
return claimedNFT;
|
if (!isClaimed) {
|
||||||
}
|
unclaimedItems.push(item);
|
||||||
// not claimed yet, return a unclaimed NFT with just the metadata
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Only fill the remaining count left over after claimed NFTs with unclaimed NFTs
|
||||||
|
const startIndex = Math.max(0, parsedQueryParams.start - totalClaimed);
|
||||||
|
const endIndex = Math.max(
|
||||||
|
0,
|
||||||
|
startIndex + parsedQueryParams.count - claimedNfts.length,
|
||||||
|
);
|
||||||
|
|
||||||
|
const unclaimedNfts = await Promise.all(
|
||||||
|
unclaimedItems.slice(startIndex, endIndex).map(async (item) => {
|
||||||
const metadata: NFTMetadata = await this.storage.downloadJSON(item.uri);
|
const metadata: NFTMetadata = await this.storage.downloadJSON(item.uri);
|
||||||
return {
|
return {
|
||||||
metadata: {
|
metadata: {
|
||||||
@@ -195,6 +213,9 @@ export class NFTDrop {
|
|||||||
} as NFT;
|
} as NFT;
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Always return claimed NFTs first, and then fill remaining query count with unclaimed NFTs
|
||||||
|
return [...claimedNfts, ...unclaimedNfts];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -208,11 +229,14 @@ export class NFTDrop {
|
|||||||
* console.log(nfts[0].name)
|
* console.log(nfts[0].name)
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
async getAllClaimed(): Promise<NFT[]> {
|
async getAllClaimed(queryParams?: QueryAllParams): Promise<NFT[]> {
|
||||||
// using getAll from collection here because candy machin findAllMinted doesn't return anything
|
// using getAll from collection here because candy machin findAllMinted doesn't return anything
|
||||||
const candy = await this.getCandyMachine();
|
const candy = await this.getCandyMachine();
|
||||||
invariant(candy.collectionMintAddress, "Collection mint address not found");
|
invariant(candy.collectionMintAddress, "Collection mint address not found");
|
||||||
return await this.nft.getAll(candy.collectionMintAddress.toBase58());
|
return await this.nft.getAll(
|
||||||
|
candy.collectionMintAddress.toBase58(),
|
||||||
|
queryParams,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -268,6 +292,21 @@ export class NFTDrop {
|
|||||||
return this.nft.ownerOf(nftAddress);
|
return this.nft.ownerOf(nftAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the total minted supply of this drop
|
||||||
|
* @returns the total supply
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```jsx
|
||||||
|
* // Get the total number of NFTs that have been minted on this drop
|
||||||
|
* const supply = await program.totalSupply();
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
async totalSupply(): Promise<number> {
|
||||||
|
const info = await this.getCandyMachine();
|
||||||
|
return info.itemsLoaded.toNumber();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the total unclaimed supply of this drop
|
* Get the total unclaimed supply of this drop
|
||||||
* @returns the total supply
|
* @returns the total supply
|
||||||
@@ -361,20 +400,20 @@ export class NFTDrop {
|
|||||||
CommonNFTInput.parse(metadata),
|
CommonNFTInput.parse(metadata),
|
||||||
);
|
);
|
||||||
const uris = await this.storage.uploadBatch(parsedMetadatas, options);
|
const uris = await this.storage.uploadBatch(parsedMetadatas, options);
|
||||||
const items: CandyMachineItem[] = uris.map((uri, i) => ({
|
const items: CandyMachineV2Item[] = uris.map((uri, i) => ({
|
||||||
name: parsedMetadatas[i].name?.toString() || "",
|
name: parsedMetadatas[i].name?.toString() || "",
|
||||||
uri,
|
uri,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// turn items into batches of $LAZY_MINT_BATCH_SIZE
|
// turn items into batches of $LAZY_MINT_BATCH_SIZE
|
||||||
const batches: CandyMachineItem[][] = [];
|
const batches: CandyMachineV2Item[][] = [];
|
||||||
while (items.length) {
|
while (items.length) {
|
||||||
batches.push(items.splice(0, LAZY_MINT_BATCH_SIZE));
|
batches.push(items.splice(0, LAZY_MINT_BATCH_SIZE));
|
||||||
}
|
}
|
||||||
|
|
||||||
const builders = batches.map((batch, i) =>
|
const builders = batches.map((batch, i) =>
|
||||||
this.metaplex
|
this.metaplex
|
||||||
.candyMachines()
|
.candyMachinesV2()
|
||||||
.builders()
|
.builders()
|
||||||
.insertItems({
|
.insertItems({
|
||||||
candyMachine,
|
candyMachine,
|
||||||
@@ -425,7 +464,7 @@ export class NFTDrop {
|
|||||||
const builders = await Promise.all(
|
const builders = await Promise.all(
|
||||||
[...Array(amount).keys()].map(async () => {
|
[...Array(amount).keys()].map(async () => {
|
||||||
return await this.metaplex
|
return await this.metaplex
|
||||||
.candyMachines()
|
.candyMachinesV2()
|
||||||
.builders()
|
.builders()
|
||||||
.mint({
|
.mint({
|
||||||
candyMachine,
|
candyMachine,
|
||||||
@@ -458,13 +497,10 @@ export class NFTDrop {
|
|||||||
const collection = candyMachine.collectionMintAddress
|
const collection = candyMachine.collectionMintAddress
|
||||||
? candyMachine.collectionMintAddress
|
? candyMachine.collectionMintAddress
|
||||||
: undefined;
|
: undefined;
|
||||||
const tx = await this.metaplex
|
const tx = await this.metaplex.nfts().delete({
|
||||||
.nfts()
|
mintAddress: new PublicKey(nftAddress),
|
||||||
.delete({
|
collection,
|
||||||
mintAddress: new PublicKey(nftAddress),
|
});
|
||||||
collection,
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return {
|
return {
|
||||||
signature: tx.response.signature,
|
signature: tx.response.signature,
|
||||||
};
|
};
|
||||||
@@ -475,13 +511,11 @@ export class NFTDrop {
|
|||||||
* @param creators - the creators to update
|
* @param creators - the creators to update
|
||||||
*/
|
*/
|
||||||
async updateCreators(creators: CreatorInput[]) {
|
async updateCreators(creators: CreatorInput[]) {
|
||||||
const tx = await this.metaplex
|
const tx = await this.metaplex.candyMachinesV2().update({
|
||||||
.candyMachines()
|
candyMachine: await this.getCandyMachine(),
|
||||||
.update({
|
creators: enforceCreator(creators, this.metaplex.identity().publicKey),
|
||||||
candyMachine: await this.getCandyMachine(),
|
});
|
||||||
creators: enforceCreator(creators, this.metaplex.identity().publicKey),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return {
|
return {
|
||||||
signature: tx.response.signature,
|
signature: tx.response.signature,
|
||||||
};
|
};
|
||||||
@@ -492,13 +526,11 @@ export class NFTDrop {
|
|||||||
* @param sellerFeeBasisPoints - the royalty basis points of the collection
|
* @param sellerFeeBasisPoints - the royalty basis points of the collection
|
||||||
*/
|
*/
|
||||||
async updateRoyalty(sellerFeeBasisPoints: number) {
|
async updateRoyalty(sellerFeeBasisPoints: number) {
|
||||||
const tx = await this.metaplex
|
const tx = await this.metaplex.candyMachinesV2().update({
|
||||||
.candyMachines()
|
candyMachine: await this.getCandyMachine(),
|
||||||
.update({
|
sellerFeeBasisPoints,
|
||||||
candyMachine: await this.getCandyMachine(),
|
});
|
||||||
sellerFeeBasisPoints,
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return {
|
return {
|
||||||
signature: tx.response.signature,
|
signature: tx.response.signature,
|
||||||
};
|
};
|
||||||
@@ -506,8 +538,7 @@ export class NFTDrop {
|
|||||||
|
|
||||||
private async getCandyMachine() {
|
private async getCandyMachine() {
|
||||||
return this.metaplex
|
return this.metaplex
|
||||||
.candyMachines()
|
.candyMachinesV2()
|
||||||
.findByAddress({ address: this.publicKey })
|
.findByAddress({ address: this.publicKey });
|
||||||
.run();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,14 +131,11 @@ export class Token {
|
|||||||
): Promise<TransactionResult> {
|
): Promise<TransactionResult> {
|
||||||
const amountParsed = AmountSchema.parse(amount);
|
const amountParsed = AmountSchema.parse(amount);
|
||||||
const info = await this.getMint();
|
const info = await this.getMint();
|
||||||
const result = await this.metaplex
|
const result = await this.metaplex.tokens().mint({
|
||||||
.tokens()
|
amount: token(amountParsed, info.decimals),
|
||||||
.mint({
|
mintAddress: this.publicKey,
|
||||||
amount: token(amountParsed, info.decimals),
|
toOwner: new PublicKey(receiverAddress),
|
||||||
mintAddress: this.publicKey,
|
});
|
||||||
toOwner: new PublicKey(receiverAddress),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return {
|
return {
|
||||||
signature: result.response.signature,
|
signature: result.response.signature,
|
||||||
};
|
};
|
||||||
@@ -165,14 +162,11 @@ export class Token {
|
|||||||
amount: Amount,
|
amount: Amount,
|
||||||
): Promise<TransactionResult> {
|
): Promise<TransactionResult> {
|
||||||
const info = await this.getMint();
|
const info = await this.getMint();
|
||||||
const result = await this.metaplex
|
const result = await this.metaplex.tokens().send({
|
||||||
.tokens()
|
mintAddress: this.publicKey,
|
||||||
.send({
|
amount: token(amount, info.decimals),
|
||||||
mintAddress: this.publicKey,
|
toOwner: new PublicKey(receiverAddress),
|
||||||
amount: token(amount, info.decimals),
|
});
|
||||||
toOwner: new PublicKey(receiverAddress),
|
|
||||||
})
|
|
||||||
.run();
|
|
||||||
return {
|
return {
|
||||||
signature: result.response.signature,
|
signature: result.response.signature,
|
||||||
};
|
};
|
||||||
@@ -228,7 +222,6 @@ export class Token {
|
|||||||
private async getMint() {
|
private async getMint() {
|
||||||
return await this.metaplex
|
return await this.metaplex
|
||||||
.tokens()
|
.tokens()
|
||||||
.findMintByAddress({ address: this.publicKey })
|
.findMintByAddress({ address: this.publicKey });
|
||||||
.run(); // TODO abstract types away
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,16 @@ export type NFTCollectionMetadataInput = z.input<
|
|||||||
*/
|
*/
|
||||||
export const TokenMetadataInputSchema = CommonContractSchema.extend({
|
export const TokenMetadataInputSchema = CommonContractSchema.extend({
|
||||||
decimals: z.number().default(9),
|
decimals: z.number().default(9),
|
||||||
initialSupply: AmountSchema,
|
initialSupply: AmountSchema.superRefine((val, context) => {
|
||||||
|
// TODO remove this limitation when metaplex fixes https://github.com/metaplex-foundation/js/issues/421
|
||||||
|
if (Number(val) > 9999999) {
|
||||||
|
context.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
message: `Initial supply must less than 10M, additional supply can be minted after deployment.`,
|
||||||
|
path: ["initialSupply"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,6 +78,22 @@ export type TokenMetadataInput = z.input<typeof TokenMetadataInputSchema>;
|
|||||||
*/
|
*/
|
||||||
export type CreatorInput = z.input<typeof CreatorInputSchema>;
|
export type CreatorInput = z.input<typeof CreatorInputSchema>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export type UpdateCreatorInput = {
|
||||||
|
creators: CreatorInput[];
|
||||||
|
updateAll: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export type UpdateRoyaltySettingsInput = {
|
||||||
|
sellerFeeBasisPoints: number;
|
||||||
|
updateAll: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @public
|
* @public
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -11,17 +11,14 @@ export async function sendMultipartTransaction(
|
|||||||
): Promise<TransactionResult[]> {
|
): Promise<TransactionResult[]> {
|
||||||
const block = await metaplex.connection.getLatestBlockhash();
|
const block = await metaplex.connection.getLatestBlockhash();
|
||||||
const txns = builders.map((builder) => {
|
const txns = builders.map((builder) => {
|
||||||
const builderTx = builder
|
const builderTx = builder.setFeePayer(metaplex.identity());
|
||||||
.setTransactionOptions({
|
|
||||||
blockhash: block.blockhash,
|
|
||||||
feePayer: metaplex.identity().publicKey,
|
|
||||||
lastValidBlockHeight: block.lastValidBlockHeight,
|
|
||||||
})
|
|
||||||
.setFeePayer(metaplex.identity());
|
|
||||||
|
|
||||||
const dropSigners = [metaplex.identity(), ...builderTx.getSigners()];
|
const dropSigners = [metaplex.identity(), ...builderTx.getSigners()];
|
||||||
const { keypairs } = getSignerHistogram(dropSigners);
|
const { keypairs } = getSignerHistogram(dropSigners);
|
||||||
const tx = builderTx.toTransaction();
|
const tx = builderTx.toTransaction({
|
||||||
|
blockhash: block.blockhash,
|
||||||
|
lastValidBlockHeight: block.lastValidBlockHeight,
|
||||||
|
});
|
||||||
|
|
||||||
if (keypairs.length > 0) {
|
if (keypairs.length > 0) {
|
||||||
tx.partialSign(...keypairs);
|
tx.partialSign(...keypairs);
|
||||||
@@ -44,7 +41,10 @@ export async function sendMultipartTransaction(
|
|||||||
// wait for confirmations in parallel
|
// wait for confirmations in parallel
|
||||||
const confirmations = await Promise.all(
|
const confirmations = await Promise.all(
|
||||||
signatures.map((sig) => {
|
signatures.map((sig) => {
|
||||||
return metaplex.rpc().confirmTransaction(sig);
|
return metaplex.rpc().confirmTransaction(sig, {
|
||||||
|
blockhash: block.blockhash,
|
||||||
|
lastValidBlockHeight: block.lastValidBlockHeight,
|
||||||
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ export const mochaHooks = {
|
|||||||
if (contractType === "custom") {
|
if (contractType === "custom") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let factories = [];
|
let factories: any[] = [];
|
||||||
switch (contractType) {
|
switch (contractType) {
|
||||||
case TokenInitializer.contractType:
|
case TokenInitializer.contractType:
|
||||||
factories.push(TokenERC20__factory);
|
factories.push(TokenERC20__factory);
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import {
|
||||||
|
extractMinimalProxyImplementationAddress,
|
||||||
|
ThirdwebSDK,
|
||||||
|
} from "../../src/evm";
|
||||||
|
import { signers, sdk } from "./before-setup";
|
||||||
|
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
|
||||||
|
import { expect } from "chai";
|
||||||
|
|
||||||
|
global.fetch = require("cross-fetch");
|
||||||
|
|
||||||
|
describe("Custom Contracts", async () => {
|
||||||
|
let adminWallet: SignerWithAddress;
|
||||||
|
let realSDK: ThirdwebSDK;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
[adminWallet] = signers;
|
||||||
|
realSDK = new ThirdwebSDK(adminWallet);
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
sdk.updateSignerOrProvider(adminWallet);
|
||||||
|
realSDK.updateSignerOrProvider(adminWallet);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should extract implementation address for eip-1167 minimal proxy", async () => {
|
||||||
|
// https://eips.ethereum.org/EIPS/eip-1167#specification
|
||||||
|
const code =
|
||||||
|
"0x363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3";
|
||||||
|
const implementationAddress =
|
||||||
|
extractMinimalProxyImplementationAddress(code);
|
||||||
|
expect(implementationAddress).to.equal(
|
||||||
|
"0xbebebebebebebebebebebebebebebebebebebebe",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should extract implementation address for minimal proxy with receive", async () => {
|
||||||
|
// https://github.com/0xSplits/splits-contracts/blob/c7b741926ec9746182d0d1e2c4c2046102e5d337/contracts/libraries/Clones.sol#L32
|
||||||
|
const code =
|
||||||
|
"0x36603057343d52307f830d2d700a97af574b186c80d40429385d24241565b08a7c559ba283a964d9b160203da23d3df35b3d3d3d3d363d3d37363d73bebebebebebebebebebebebebebebebebebebebe5af43d3d93803e605b57fd5bf3";
|
||||||
|
const implementationAddress =
|
||||||
|
extractMinimalProxyImplementationAddress(code);
|
||||||
|
expect(implementationAddress).to.equal(
|
||||||
|
"0xbebebebebebebebebebebebebebebebebebebebe",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should extract implementation address for more minimal proxy", async () => {
|
||||||
|
// https://medium.com/coinmonks/the-more-minimal-proxy-5756ae08ee48
|
||||||
|
const code =
|
||||||
|
"0x3d3d3d3d363d3d37363d73bebebebebebebebebebebebebebebebebebebebe5af43d3d93803e602a57fd5bf3";
|
||||||
|
const implementationAddress =
|
||||||
|
extractMinimalProxyImplementationAddress(code);
|
||||||
|
expect(implementationAddress).to.equal(
|
||||||
|
"0xbebebebebebebebebebebebebebebebebebebebe",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should extract implementation address for older vyper (uniswap v1) proxy", async () => {
|
||||||
|
const code =
|
||||||
|
"0x366000600037611000600036600073bebebebebebebebebebebebebebebebebebebebe5af41558576110006000f3";
|
||||||
|
const implementationAddress =
|
||||||
|
extractMinimalProxyImplementationAddress(code);
|
||||||
|
expect(implementationAddress).to.equal(
|
||||||
|
"0xbebebebebebebebebebebebebebebebebebebebe",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
ChainId,
|
ChainId,
|
||||||
|
getAllDetectedFeatureNames,
|
||||||
isFeatureEnabled,
|
isFeatureEnabled,
|
||||||
resolveContractUriFromAddress,
|
resolveContractUriFromAddress,
|
||||||
ThirdwebSDK,
|
ThirdwebSDK,
|
||||||
@@ -9,10 +10,11 @@ import { AddressZero } from "@ethersproject/constants";
|
|||||||
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
|
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
|
||||||
import {
|
import {
|
||||||
DropERC721__factory,
|
DropERC721__factory,
|
||||||
|
DropERC721_V3__factory,
|
||||||
TokenERC721__factory,
|
TokenERC721__factory,
|
||||||
} from "@thirdweb-dev/contracts-js";
|
} from "@thirdweb-dev/contracts-js";
|
||||||
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
import { ThirdwebStorage } from "@thirdweb-dev/storage";
|
||||||
import { expect } from "chai";
|
import { assert, expect } from "chai";
|
||||||
import { ethers } from "ethers";
|
import { ethers } from "ethers";
|
||||||
import { readFileSync } from "fs";
|
import { readFileSync } from "fs";
|
||||||
import invariant from "tiny-invariant";
|
import invariant from "tiny-invariant";
|
||||||
@@ -94,6 +96,17 @@ describe("Publishing", async () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should extract all features", async () => {
|
||||||
|
const tokenFeatures = getAllDetectedFeatureNames(TokenERC721__factory.abi);
|
||||||
|
expect(tokenFeatures).to.contain("ERC721Enumerable");
|
||||||
|
expect(getAllDetectedFeatureNames(DropERC721__factory.abi)).to.contain(
|
||||||
|
"ERC721ClaimPhasesV2",
|
||||||
|
);
|
||||||
|
expect(getAllDetectedFeatureNames(DropERC721_V3__factory.abi)).to.contain(
|
||||||
|
"ERC721ClaimPhasesV1",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("should update bio", async () => {
|
it("should update bio", async () => {
|
||||||
const address = adminWallet.address;
|
const address = adminWallet.address;
|
||||||
const publisher = sdk.getPublisher();
|
const publisher = sdk.getPublisher();
|
||||||
@@ -454,6 +467,30 @@ describe("Publishing", async () => {
|
|||||||
expect(nftsAfter[1].supply).to.equal(0);
|
expect(nftsAfter[1].supply).to.equal(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("ERC1155Signature mint feature detection", async () => {
|
||||||
|
const ipfsUri = "ipfs://QmNuKYGZoiHyumKjT7gPk3vwy3WKt7gTf1hKGZ2eyGZGRd";
|
||||||
|
const addr = await sdk.deployer.deployContractFromUri(ipfsUri, [
|
||||||
|
"test",
|
||||||
|
"test",
|
||||||
|
]);
|
||||||
|
const c = await sdk.getContract(addr);
|
||||||
|
const payload = {
|
||||||
|
metadata: {
|
||||||
|
name: "SigMinted Edition",
|
||||||
|
},
|
||||||
|
to: samWallet.address, // Who will receive the NFT (or AddressZero for anyone)
|
||||||
|
price: 0.5, // the price to pay for minting
|
||||||
|
royaltyBps: 100, // custom royalty fees for this NFT (in bps)
|
||||||
|
quantity: "1",
|
||||||
|
};
|
||||||
|
|
||||||
|
const goodPayload = await c.erc1155.signature.generate(payload);
|
||||||
|
const valid = await c.erc1155.signature.verify(goodPayload);
|
||||||
|
expect(valid).to.eq(true);
|
||||||
|
const tx = await c.erc1155.signature.mint(goodPayload);
|
||||||
|
expect(tx.id.toNumber()).to.eq(0);
|
||||||
|
});
|
||||||
|
|
||||||
it("Constructor params with tuples", async () => {
|
it("Constructor params with tuples", async () => {
|
||||||
const ipfsUri = "ipfs://QmZQa56Cj1gFnZgKSkvGE5uzhaQrQV3nU6upDWDusCaCwY/0";
|
const ipfsUri = "ipfs://QmZQa56Cj1gFnZgKSkvGE5uzhaQrQV3nU6upDWDusCaCwY/0";
|
||||||
const addr = await sdk.deployer.deployContractFromUri(ipfsUri, [
|
const addr = await sdk.deployer.deployContractFromUri(ipfsUri, [
|
||||||
|
|||||||
@@ -152,4 +152,44 @@ describe("NFTDrop", async () => {
|
|||||||
royalty = await drop.getRoyalty();
|
royalty = await drop.getRoyalty();
|
||||||
expect(royalty).to.equal(100);
|
expect(royalty).to.equal(100);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("Should get all correctly", async () => {
|
||||||
|
const address = await sdk.deployer.createNftDrop({
|
||||||
|
name: "NFT Drop #1",
|
||||||
|
totalSupply: 5,
|
||||||
|
});
|
||||||
|
const contract = await sdk.getNFTDrop(address);
|
||||||
|
|
||||||
|
await contract.lazyMint([
|
||||||
|
{ name: "NFT #1", description: "This is the #1 NFT" },
|
||||||
|
{ name: "NFT #2", description: "This is the #2 NFT" },
|
||||||
|
{ name: "NFT #3", description: "This is the #3 NFT" },
|
||||||
|
{ name: "NFT #4", description: "This is the #4 NFT" },
|
||||||
|
{ name: "NFT #5", description: "This is the #5 NFT" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
let all = await contract.getAll();
|
||||||
|
expect(all.length).to.equal(5);
|
||||||
|
expect(all[0].metadata.name).to.equal("NFT #1");
|
||||||
|
expect(all.filter((nft) => nft.supply > 0).length).to.equal(0);
|
||||||
|
|
||||||
|
await contract.claimConditions.set({
|
||||||
|
price: 0,
|
||||||
|
maxClaimable: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
await contract.claim(2);
|
||||||
|
all = await contract.getAll();
|
||||||
|
expect(all.length).to.equal(5);
|
||||||
|
expect(all[0].supply).to.equal(1);
|
||||||
|
expect(all[1].supply).to.equal(1);
|
||||||
|
expect(all[2].supply).to.equal(0);
|
||||||
|
|
||||||
|
all = await contract.getAll({ start: 2, count: 3 });
|
||||||
|
expect(all.length).to.equal(3);
|
||||||
|
expect(all.filter((nft) => nft.supply > 0).length).to.equal(0);
|
||||||
|
|
||||||
|
all = await contract.getAll({ start: 0, count: 3 });
|
||||||
|
expect(all.filter((nft) => nft.supply > 0).length).to.equal(2);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -43,7 +43,7 @@
|
|||||||
"@preconstruct/cli": "^2.2.1",
|
"@preconstruct/cli": "^2.2.1",
|
||||||
"@swc-node/register": "^1.5.1",
|
"@swc-node/register": "^1.5.1",
|
||||||
"@types/chai": "^4.3.3",
|
"@types/chai": "^4.3.3",
|
||||||
"@types/mocha": "^9.1.1",
|
"@types/mocha": "^10.0.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
||||||
"@typescript-eslint/parser": "^5.33.0",
|
"@typescript-eslint/parser": "^5.33.0",
|
||||||
"chai": "^4.3.6",
|
"chai": "^4.3.6",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user