Compare commits

..
Author SHA1 Message Date
github-actions[bot]andgithub-actions[bot] 8e591383fc Version Packages (#265)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-10-05 12:53:02 -07:00
Adam Majmudar 6f95a520e6 [CLI] Add npx thirdweb upload command (#259) 2022-10-05 18:42:03 +00:00
Nacho Iacovino f669d3ef4a [React] Use same data structure for useLazyMint (#264) 2022-10-05 11:25:42 -07:00
github-actions[bot]andgithub-actions[bot] 83575058db Version Packages (#235)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-10-04 21:02:13 -07:00
Jonas Daniels 028cb78125 [SDK] - fix HexColor schema (#262) 2022-10-05 01:31:10 +00:00
Jonas Daniels c8261b74b5 [SDK, React] - align getContract and useContract across sdk and react (#261) 2022-10-04 18:09:36 -07:00
Jonas Daniels a36c788415 Create size.yml 2022-10-04 12:47:09 -07:00
Nacho Iacovino ac232b5aff Accept TokenContract instead of erc20 instance (#258) 2022-10-04 18:39:13 +00:00
Jonas Daniels ba6f45027a [SDK] - fix permissions enumerable export (#257) 2022-10-04 17:51:10 +00:00
Jonas Daniels d677e9d634 [React] - enable permissions enumerable feature (#256) 2022-10-04 17:21:22 +00:00
Jonas Daniels 9b92697fb7 [React] - useContract can accept an abi now (#255) 2022-10-04 04:40:16 +00:00
Joaquim Verges c19e471f65 [React] Update react docs (#254) 2022-10-03 21:13:07 -07:00
Jonas Daniels b6fc298d0c [React] - allow passing in contractType in useContract() (#253) 2022-10-03 20:18:07 -07:00
Jonas Daniels ea41231b3e [React] - fix usage of Buffer (#251) 2022-10-04 01:26:37 +00:00
Joaquim Verges 2ea3f00c41 [SDK] Expose additional claim condition information (#252) 2022-10-04 00:26:46 +00:00
Nacho IacovinoandJonas Daniels 20745f8cd6 [SDK] Add check if abi exists (#250)
Co-authored-by: Jonas Daniels <[email protected]>
2022-10-03 22:36:32 +02:00
Furqan Rydhan caf979537b AppURI detection enabled [SDK] (#247) 2022-10-03 19:12:09 +00:00
Joaquim Verges e4b10bc5bd [SDK] Polish + Fixes for Solana NFT Drops (#249) 2022-10-03 12:03:16 -07:00
ef0bac7f44 Renamed initial commit message during thirdweb cli createApp (#246)
Co-authored-by: simon.lim <[email protected]>
Co-authored-by: Jonas Daniels <[email protected]>
2022-10-02 16:43:30 +00:00
Jonas Daniels 23de9eac4f Update README.md 2022-10-02 09:38:13 -07:00
Jonas Daniels 1972f3ec0d [SDK, React] - useBurnNFT for solana (#245) 2022-10-01 01:46:07 +00:00
Adam Majmudar ffd0fc42ae [React] Add code snippets for Solana (#244) 2022-09-30 15:28:21 -07:00
Jonas Daniels 93531a5d47 fix build outputs 2022-09-30 15:16:16 -07:00
Joaquim Verges b16aaebc4c update solana docs 2022-09-30 10:30:32 -07:00
Jonas Daniels 1136d959ba fix persister logic (#243) 2022-09-30 04:38:40 +00:00
Jonas Daniels db23f0588d [Storage] - send different header in tests (#242) 2022-09-29 20:14:53 -07:00
Jonas Daniels e662408e19 [SDK] - unify program metadata return type again (#240) 2022-09-30 01:41:08 +00:00
Adam Majmudar afe4ba6471 Update solana docs (#239) 2022-09-30 00:27:45 +00:00
Joaquim Verges 6647f707bd [SDK, React] Unify NFT types for EVM and Solana (#238) 2022-09-30 00:12:37 +00:00
Jonas Daniels cac373b010 [React, SDK] - solana improvements (#236) 2022-09-29 06:51:16 +00:00
Joaquim Verges 9412d41683 [SDK] add burn function, better RPC, rename inputs (#234) 2022-09-28 22:16:09 -07:00
139 changed files with 2941 additions and 1148 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
"changelog": ["@changesets/changelog-github", { "repo": "thirdweb-dev/js" }],
"commit": false,
"fixed": [],
"fixed": [["@thirdweb-dev/sdk", "@thirdweb-dev/react"]],
"linked": [],
"access": "public",
"baseBranch": "main",
+2 -4
View File
@@ -30,8 +30,6 @@ jobs:
- name: Install
uses: ./.github/composite-actions/install
- name: Build
run: yarn build
- name: Test
# this already builds anything that changed...
- name: Build & Test
run: yarn test
+18
View File
@@ -0,0 +1,18 @@
name: Compressed Size
on: [pull_request]
jobs:
build:
# try out buildjet to speed up build and test
runs-on: buildjet-32vcpu-ubuntu-2204
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: preactjs/compressed-size-action@v2
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
strip-hash: "\\-(\\w{8})(?:\\.esm|\\.cjs)"
minimum-change-threshold: 100
+1 -1
View File
@@ -27,7 +27,7 @@
| [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?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> |
| [/solana](./packages/solana) | Solana SDK for Browser, Node and React Native | <a href="https://www.npmjs.com/package/@thirdweb-dev/solana"><img src="https://img.shields.io/npm/v/@thirdweb-dev/solana?color=red&label=npm&logo=npm" alt="npm version"/></a> |
## Documentation
+1 -1
View File
@@ -12,7 +12,7 @@
]
},
"scripts": {
"test": "turbo run test && turbo run test:evm && turbo run test:solana",
"test": "turbo run test test:evm test:solana",
"e2e": "turbo run e2e",
"build": "turbo run build",
"build:release": "turbo run build --force",
+4
View File
@@ -1,5 +1,9 @@
# @thirdweb-dev/auth
## 2.0.13
## 2.0.12
## 2.0.11
## 2.0.10
+5 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/auth",
"version": "2.0.11",
"version": "2.0.13",
"exports": {
"./next": {
"module": "./next/dist/thirdweb-dev-auth-next.esm.js",
@@ -44,6 +44,7 @@
"exports": true
},
"devDependencies": {
"@babel/core": "^7.19.3",
"@babel/preset-env": "^7.18.10",
"@babel/preset-typescript": "^7.18.6",
"@microsoft/api-documenter": "^7.19.4",
@@ -62,11 +63,13 @@
"eslint-plugin-inclusive-language": "^2.2.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-tsdoc": "^0.2.16",
"ethers": "^5.7.0",
"ethers": "^5.7.1",
"express": "^4.18.1",
"next": "^12.2.0",
"next-auth": "^4.10.3",
"prettier": "^2.7.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"typescript": "^4.7.4"
},
"peerDependencies": {
+18
View File
@@ -1,5 +1,23 @@
# thirdweb
## 0.7.24
### Patch Changes
- [#259](https://github.com/thirdweb-dev/js/pull/259) [`6f95a52`](https://github.com/thirdweb-dev/js/commit/6f95a520e6cc69e08f734705e8adc71431b091cc) Thanks [@adam-maj](https://github.com/adam-maj)! - Add npx thirdweb upload command
- Updated dependencies []:
- @thirdweb-dev/sdk@3.2.1
## 0.7.23
### Patch Changes
- [#246](https://github.com/thirdweb-dev/js/pull/246) [`ef0bac7`](https://github.com/thirdweb-dev/js/commit/ef0bac7f44b93939bfc9e2706b39edaa22992eec) Thanks [@simonlim94](https://github.com/simonlim94)! - Renamed initial commit message during thirdweb cli createApp
- Updated dependencies [[`ba6f450`](https://github.com/thirdweb-dev/js/commit/ba6f45027a6ec11aebb4a1918ab2ba4f88894ede), [`c8261b7`](https://github.com/thirdweb-dev/js/commit/c8261b74b5828ac66ea3a6d7636aa57e40ea1a14), [`20745f8`](https://github.com/thirdweb-dev/js/commit/20745f8cd603235eb5039e61a39c0959c5860bca), [`2ea3f00`](https://github.com/thirdweb-dev/js/commit/2ea3f00c41b5e70d9bb634cd86790890520fc4d6), [`9412d41`](https://github.com/thirdweb-dev/js/commit/9412d416832c87ab2c858cb120c6c5de03459c50), [`d677e9d`](https://github.com/thirdweb-dev/js/commit/d677e9d6341252013762882d25408ea8f93791e5), [`e662408`](https://github.com/thirdweb-dev/js/commit/e662408e1936983485936609552f80a56cbed082), [`e4b10bc`](https://github.com/thirdweb-dev/js/commit/e4b10bc5bd12178cba8856b60255732123cb7ae5), [`caf9795`](https://github.com/thirdweb-dev/js/commit/caf979537b5acb1610f182c94afa5d95c208ec3f), [`028cb78`](https://github.com/thirdweb-dev/js/commit/028cb781252b0050943b14cfdf38132c18753a4b), [`1972f3e`](https://github.com/thirdweb-dev/js/commit/1972f3ec0d511fbc17642b2a30852a177092a09e), [`6647f70`](https://github.com/thirdweb-dev/js/commit/6647f707bdd050725264a8a74220c11912f68e57), [`cac373b`](https://github.com/thirdweb-dev/js/commit/cac373b010ce3be3615a36671b66815a27785061)]:
- @thirdweb-dev/sdk@3.2.0
## 0.7.22
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "thirdweb",
"main": "dist/cli/index.js",
"version": "0.7.22",
"version": "0.7.24",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
+17
View File
@@ -6,6 +6,8 @@ import { cliVersion, pkg } from "../constants/urls";
import { info, logger } from "../core/helpers/logger";
import { twCreate } from "../create/command";
import generateDashboardUrl from "../helpers/generate-dashboard-url";
import { upload } from "../storage/command";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import chalk from "chalk";
import { Command } from "commander";
import open from "open";
@@ -141,6 +143,21 @@ $$$$$$\\ $$$$$$$\\ $$\\ $$$$$$\\ $$$$$$$ |$$\\ $$\\ $$\\ $$$$$$\\ $$$$
await detectExtensions(options);
});
program
.command("upload")
.description("Upload any file or directory using decentralized storage")
.argument("<upload-path>", "path to file or directory to upload")
.action(async (path) => {
const storage = new ThirdwebStorage();
const uri = await upload(storage, path);
info(`Files stored at the following IPFS URI:`);
logger.info(chalk.blueBright(uri.toString()));
const url = storage.resolveScheme(uri);
info(`Open this link to view your upload:`);
logger.info(chalk.blueBright(url.toString()));
});
program
.command("install-ci")
.description(
+1 -1
View File
@@ -33,7 +33,7 @@ export function tryGitInit(root: string): boolean {
execSync("git checkout -b main", { stdio: "ignore" });
execSync("git add -A", { stdio: "ignore" });
execSync('git commit -m "Initial commit from Create thirdweb app"', {
execSync('git commit -m "Initial commit from npx thirdweb create"', {
stdio: "ignore",
});
return true;
+63
View File
@@ -0,0 +1,63 @@
import { logger } from "../core/helpers/logger";
import { spinner } from "../core/helpers/logger";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import chalk from "chalk";
import fs from "fs";
import path from "path";
export async function upload(
storage: ThirdwebStorage,
uploadPath: string,
): Promise<string> {
const pathExists = fs.existsSync(uploadPath);
if (!pathExists) {
logger.error(
`Invalid path ${chalk.blueBright(
uploadPath,
)} provided. Please provide a valid path to a file or directory to upload."`,
);
process.exit(1);
}
let uri = "";
const fileType = fs.lstatSync(uploadPath);
if (fileType.isDirectory()) {
const subPaths = fs.readdirSync(uploadPath);
const filePaths = subPaths
.map((subPath) => path.join(uploadPath, subPath))
.filter((subPath) => fs.lstatSync(subPath).isFile());
const files = filePaths.map((filePath) => fs.readFileSync(filePath));
if (files.length === 0) {
logger.error(
`No files detected in specified directory ${chalk.blueBright(
uploadPath,
)} to upload.`,
);
process.exit(1);
}
const spin = spinner(
"Uploading directory to IPFS. This may take a while depending on file sizes.",
);
const uris = await storage.uploadBatch(files);
spin.succeed("Successfully uploaded directory to IPFS");
uri = uris[0].substring(0, uris[0].lastIndexOf("/"));
} else if (fileType.isFile()) {
const file = fs.readFileSync(uploadPath);
const spin = spinner(
"Uploading file to IPFS. This may take a while depending on file sizes.",
);
uri = await storage.upload(file);
spin.succeed("Succesfully uploaded file to IPFS.");
} else {
logger.error(
`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;
}
+1
View File
@@ -12,6 +12,7 @@
"@babel/preset-env": "^7.18.10",
"@babel/preset-typescript": "^7.18.6",
"@preconstruct/cli": "^2.2.1",
"@typechain/ethers-v5": "10.0.0",
"ethers": "^5.7.0",
"typechain": "^8.1.0",
"typescript": "^4.7.4"
+5
View File
@@ -5,3 +5,8 @@ node_modules/
/test-results/
/playwright-report/
/playwright/.cache/
etc/
temp/
temp-evm/
temp-solana/
docs/
+26
View File
@@ -1,5 +1,31 @@
# @thirdweb-dev/react
## 3.2.1
### Patch Changes
- [#264](https://github.com/thirdweb-dev/js/pull/264) [`f669d3e`](https://github.com/thirdweb-dev/js/commit/f669d3ef4a84368c23f0359aec304f66a4063042) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Standarize data between evm/solana for useLazyMint hook
## 3.2.0
### Patch Changes
- [#261](https://github.com/thirdweb-dev/js/pull/261) [`c8261b7`](https://github.com/thirdweb-dev/js/commit/c8261b74b5828ac66ea3a6d7636aa57e40ea1a14) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - align behavior of `useContract()` and `getContract()` across react & sdk to both allow passing optional second params of contract types or ABIs
- [#236](https://github.com/thirdweb-dev/js/pull/236) [`cac373b`](https://github.com/thirdweb-dev/js/commit/cac373b010ce3be3615a36671b66815a27785061) Thanks [@jnsdls](https://github.com/jnsdls)! - [SOL] - do not require a connection, instead handle a network directly
- [#251](https://github.com/thirdweb-dev/js/pull/251) [`ea41231`](https://github.com/thirdweb-dev/js/commit/ea41231b3ec4a2aef6a203db195d0e450c45ef56) Thanks [@jnsdls](https://github.com/jnsdls)! - fix missing Buffer implementation for WalletConnect and CoinbaseWallet connectors
- [#253](https://github.com/thirdweb-dev/js/pull/253) [`b6fc298`](https://github.com/thirdweb-dev/js/commit/b6fc298d0cf63bc7129104f7779cc9d84e405093) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - allow passing contractType as second param to `useContract()`
- [#243](https://github.com/thirdweb-dev/js/pull/243) [`1136d95`](https://github.com/thirdweb-dev/js/commit/1136d959baf936c166e5f7c051d5173d68d9eb9b) Thanks [@jnsdls](https://github.com/jnsdls)! - fix persister logic
- [#258](https://github.com/thirdweb-dev/js/pull/258) [`ac232b5`](https://github.com/thirdweb-dev/js/commit/ac232b5affe31780ef1c10ec76edb21596850e7e) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Accept SmartContract instead of erc20 instance
- [#245](https://github.com/thirdweb-dev/js/pull/245) [`1972f3e`](https://github.com/thirdweb-dev/js/commit/1972f3ec0d511fbc17642b2a30852a177092a09e) Thanks [@jnsdls](https://github.com/jnsdls)! - [SOL] - expose `useBurnNFT` hook
- [#255](https://github.com/thirdweb-dev/js/pull/255) [`9b92697`](https://github.com/thirdweb-dev/js/commit/9b92697fb77d3072e3e53b451f9b348595ae410e) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - `useContract()` and `<Web3Button />` can now accept an optional ABI directly and will return a `SmartContract` based on it
## 3.1.2
### Patch Changes
@@ -0,0 +1,342 @@
/**
* Config file for API Extractor. For more info, please visit: https://api-extractor.com
*/
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
/**
* Optionally specifies another JSON config file that this file extends from. This provides a way for
* standard settings to be shared across multiple projects.
*
* If the path starts with "./" or "../", the path is resolved relative to the folder of the file that contains
* the "extends" field. Otherwise, the first path segment is interpreted as an NPM package name, and will be
* resolved using NodeJS require().
*
* SUPPORTED TOKENS: none
* DEFAULT VALUE: ""
*/
// "extends": "./shared/api-extractor-base.json"
// "extends": "my-package/include/api-extractor-base.json"
/**
* Determines the "<projectFolder>" token that can be used with other config file settings. The project folder
* typically contains the tsconfig.json and package.json config files, but the path is user-defined.
*
* The path is resolved relative to the folder of the config file that contains the setting.
*
* The default value for "projectFolder" is the token "<lookup>", which means the folder is determined by traversing
* parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder
* that contains a tsconfig.json file. If a tsconfig.json file cannot be found in this way, then an error
* will be reported.
*
* SUPPORTED TOKENS: <lookup>
* DEFAULT VALUE: "<lookup>"
*/
// "projectFolder": "..",
/**
* (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis. API Extractor
* analyzes the symbols exported by this module.
*
* The file extension must be ".d.ts" and not ".ts".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
*/
"mainEntryPointFilePath": "<projectFolder>/solana/dist/thirdweb-dev-react-solana.cjs.d.ts",
/**
* A list of NPM package names whose exports should be treated as part of this package.
*
* For example, suppose that Webpack is used to generate a distributed bundle for the project "library1",
* and another NPM package "library2" is embedded in this bundle. Some types from library2 may become part
* of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly
* imports library2. To avoid this, we can specify:
*
* "bundledPackages": [ "library2" ],
*
* This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been
* local files for library1.
*/
"bundledPackages": [
"wagmi",
"wagmi-core"
],
/**
* Determines how the TypeScript compiler engine will be invoked by API Extractor.
*/
"compiler": {
/**
* Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* Note: This setting will be ignored if "overrideTsconfig" is used.
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/tsconfig.json"
*/
// "tsconfigFilePath": "<projectFolder>/tsconfig.json",
/**
* Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.
* The object must conform to the TypeScript tsconfig schema:
*
* http://json.schemastore.org/tsconfig
*
* If omitted, then the tsconfig.json file will be read from the "projectFolder".
*
* DEFAULT VALUE: no overrideTsconfig section
*/
"overrideTsconfig": {
"skipLibCheck": true
}
/**
* This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended
* and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when
* dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses
* for its analysis. Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.
*
* DEFAULT VALUE: false
*/
// "skipLibCheck": true,
},
/**
* Configures how the API report file (*.api.md) will be generated.
*/
"apiReport": {
/**
* (REQUIRED) Whether to generate an API report.
*/
"enabled": true
/**
* The filename for the API report files. It will be combined with "reportFolder" or "reportTempFolder" to produce
* a full file path.
*
* The file extension should be ".api.md", and the string should not contain a path separator such as "\" or "/".
*
* SUPPORTED TOKENS: <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<unscopedPackageName>.api.md"
*/
// "reportFileName": "<unscopedPackageName>.api.md",
/**
* Specifies the folder where the API report file is written. The file name portion is determined by
* the "reportFileName" setting.
*
* The API report file is normally tracked by Git. Changes to it can be used to trigger a branch policy,
* e.g. for an API review.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/etc/"
*/
// "reportFolder": "<projectFolder>/etc/",
/**
* Specifies the folder where the temporary report file is written. The file name portion is determined by
* the "reportFileName" setting.
*
* After the temporary file is written to disk, it is compared with the file in the "reportFolder".
* If they are different, a production build will fail.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/"
*/
// "reportTempFolder": "<projectFolder>/temp/"
},
/**
* Configures how the doc model file (*.api.json) will be generated.
*/
"docModel": {
/**
* (REQUIRED) Whether to generate a doc model file.
*/
"enabled": true
/**
* The output path for the doc model file. The file extension should be ".api.json".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/<unscopedPackageName>.api.json"
*/
// "apiJsonFilePath": "<projectFolder>/temp/<unscopedPackageName>.api.json"
},
/**
* Configures how the .d.ts rollup file will be generated.
*/
"dtsRollup": {
/**
* (REQUIRED) Whether to generate the .d.ts rollup file.
*/
"enabled": false,
/**
* Specifies the output path for a .d.ts rollup file to be generated without any trimming.
* This file will include all declarations that are exported by the main entry point.
*
* If the path is an empty string, then this file will not be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/dist/<unscopedPackageName>.d.ts"
*/
"untrimmedFilePath": "<projectFolder>/lib/<unscopedPackageName>.d.ts"
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "beta" release.
* This file will include only declarations that are marked as "@public" or "@beta".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-beta.d.ts",
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release.
* This file will include only declarations that are marked as "@public".
*
* If the path is an empty string, then this file will not be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "publicTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-public.d.ts",
/**
* When a declaration is trimmed, by default it will be replaced by a code comment such as
* "Excluded from this release type: exampleMember". Set "omitTrimmingComments" to true to remove the
* declaration completely.
*
* DEFAULT VALUE: false
*/
// "omitTrimmingComments": true
},
/**
* Configures how the tsdoc-metadata.json file will be generated.
*/
"tsdocMetadata": {
/**
* Whether to generate the tsdoc-metadata.json file.
*
* DEFAULT VALUE: true
*/
// "enabled": true,
/**
* Specifies where the TSDoc metadata file should be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* The default value is "<lookup>", which causes the path to be automatically inferred from the "tsdocMetadata",
* "typings" or "main" fields of the project's package.json. If none of these fields are set, the lookup
* falls back to "tsdoc-metadata.json" in the package folder.
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<lookup>"
*/
// "tsdocMetadataFilePath": "<projectFolder>/dist/tsdoc-metadata.json"
},
/**
* Specifies what type of newlines API Extractor should use when writing output files. By default, the output files
* will be written with Windows-style newlines. To use POSIX-style newlines, specify "lf" instead.
* To use the OS's default newline kind, specify "os".
*
* DEFAULT VALUE: "crlf"
*/
// "newlineKind": "crlf",
/**
* Configures how API Extractor reports error and warning messages produced during analysis.
*
* There are three sources of messages: compiler messages, API Extractor messages, and TSDoc messages.
*/
"messages": {
/**
* Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing
* the input .d.ts files.
*
* TypeScript message identifiers start with "TS" followed by an integer. For example: "TS2551"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"compilerMessageReporting": {
/**
* Configures the default routing for messages that don't match an explicit rule in this table.
*/
"default": {
/**
* Specifies whether the message should be written to the the tool's output log. Note that
* the "addToApiReportFile" property may supersede this option.
*
* Possible values: "error", "warning", "none"
*
* Errors cause the build to fail and return a nonzero exit code. Warnings cause a production build fail
* and return a nonzero exit code. For a non-production build (e.g. when "api-extractor run" includes
* the "--local" option), the warning is displayed but the build will not fail.
*
* DEFAULT VALUE: "warning"
*/
"logLevel": "warning"
/**
* When addToApiReportFile is true: If API Extractor is configured to write an API report file (.api.md),
* then the message will be written inside that file; otherwise, the message is instead logged according to
* the "logLevel" option.
*
* DEFAULT VALUE: false
*/
// "addToApiReportFile": false
}
// "TS2551": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},
/**
* Configures handling of messages reported by API Extractor during its analysis.
*
* API Extractor message identifiers start with "ae-". For example: "ae-extra-release-tag"
*
* DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings
*/
"extractorMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
}
// "ae-extra-release-tag": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},
/**
* Configures handling of messages reported by the TSDoc parser when analyzing code comments.
*
* TSDoc message identifiers start with "tsdoc-". For example: "tsdoc-link-tag-unescaped-text"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"tsdocMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
}
// "tsdoc-link-tag-unescaped-text": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
}
}
}
+8 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react",
"version": "3.1.2",
"version": "3.2.1",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -44,9 +44,10 @@
"lint": "eslint src/",
"fix": "eslint src/ --fix",
"clean": "rm -rf dist/",
"generate-docs": "api-extractor run --local && yarn api-documenter markdown -i ./temp -o ./docs && yarn generate-snippets",
"generate:md-docs": "yarn api-documenter markdown -i ./temp -o ./docs",
"generate-snippets": "node ./scripts/generate-snippets.mjs && node ./scripts/generate-feature-snippets.mjs",
"generate-docs": "yarn generate-docs:evm && yarn generate-docs:solana && yarn generate-snippets",
"generate-docs:evm": "api-extractor run --local --config ./config/api-extractor-evm.json && api-documenter markdown -i ./temp -o ./docs/evm && rm -rf ./temp-evm && mv ./temp ./temp-evm",
"generate-docs:solana": "api-extractor run --local --config ./config/api-extractor-solana.json && api-documenter markdown -i ./temp -o ./docs/solana && rm -rf ./temp-solana && mv ./temp ./temp-solana",
"generate-snippets": "node ./scripts/generate-snippets-evm.mjs && node ./scripts/generate-snippets-solana.mjs && node ./scripts/generate-feature-snippets-evm.mjs",
"build": "tsc && preconstruct build",
"e2e": "yarn test-ct",
"test-ct": "playwright test -c playwright-ct.config.ts",
@@ -58,6 +59,7 @@
"@babel/preset-env": "^7.18.10",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"@babel/runtime": "^7.19.0",
"@microsoft/api-documenter": "^7.19.4",
"@microsoft/api-extractor": "^7.29.2",
"@microsoft/tsdoc": "^0.14.1",
@@ -82,7 +84,7 @@
"eslint-plugin-inclusive-language": "^2.2.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-tsdoc": "^0.2.16",
"ethers": "^5.7.0",
"ethers": "^5.7.1",
"prettier": "^2.7.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -98,6 +100,7 @@
"@tanstack/react-query": "^4.0.10",
"@zag-js/menu": "0.1.14",
"@zag-js/react": "0.1.16",
"buffer": "^6.0.3",
"color": "^4.2.3",
"copy-to-clipboard": "^3.3.2",
"detect-browser": "^5.3.0",
@@ -44,7 +44,7 @@ config.setSupportForTag(tag, true);
const tsdocParser = new TSDocParser(config);
const json = JSON.parse(
fs.readFileSync(`${process.cwd()}/temp/react.api.json`, "utf8"),
fs.readFileSync(`${process.cwd()}/temp-evm/react.api.json`, "utf8"),
);
function languageNameToKey(languageName) {
@@ -160,6 +160,6 @@ classes.forEach((m) => {
});
fs.writeFileSync(
`${process.cwd()}/docs/feature_snippets.json`,
`${process.cwd()}/docs/evm/feature_snippets.json`,
JSON.stringify(features, null, 2),
);
@@ -27,41 +27,6 @@ export class Formatter {
}
}
const tsdocParser = new TSDocParser();
const json = JSON.parse(
fs.readFileSync(`${process.cwd()}/temp/react.api.json`, "utf8"),
);
function languageNameToKey(languageName) {
switch (languageName) {
case "js":
case "jsx":
return "javascript";
case "ts":
case "tsx":
return "typescript";
default:
return languageName;
}
}
const CONTRACT_HOOKS = [
"useSignatureDrop",
"useNFTDrop",
"useEditionDrop",
"useNFTCollection",
"useEdition",
"useTokenDrop",
"useToken",
"useMarketplace",
"useSplit",
"useVote",
"usePack",
"useMultiwrap",
"useContract",
];
const NFT_HOOKS = [
"useNFT",
"useNFTs",
@@ -141,7 +106,7 @@ const CONTRACT_SETTINGS_HOOKS = [
"useRevokeRole",
];
const CONTRACT_SUBHOOKS = {
const HOOKS_CONFIG = {
useSignatureDrop: [...NFT_HOOKS, ...DROP_HOOKS, ...CLAIM_CONDITIONS_HOOKS],
useNFTDrop: [...NFT_HOOKS, ...DROP_HOOKS, ...CLAIM_CONDITIONS_HOOKS],
useEditionDrop: [...NFT_HOOKS, ...DROP_HOOKS, ...CLAIM_CONDITIONS_HOOKS],
@@ -162,8 +127,27 @@ const CONTRACT_SUBHOOKS = {
],
};
const tsdocParser = new TSDocParser();
const json = JSON.parse(
fs.readFileSync(`${process.cwd()}/temp-evm/react.api.json`, "utf8"),
);
function languageNameToKey(languageName) {
switch (languageName) {
case "js":
case "jsx":
return "javascript";
case "ts":
case "tsx":
return "typescript";
default:
return languageName;
}
}
const hooks = json.members[0].members.filter(
(m) => m.kind === "Function" && CONTRACT_HOOKS.includes(m.name),
(m) => m.kind === "Function" && Object.keys(HOOKS_CONFIG).includes(m.name),
);
function parseExampleTag(docComment) {
@@ -192,7 +176,7 @@ function parseExampleTag(docComment) {
return examples;
}
const baseDocUrl = "https://docs.thirdweb.com/typescript/react.";
const baseDocUrl = "https://portal.thirdweb.com/react/react.";
const extractReferenceLink = (m, kind, contractName) => {
if (kind === "Property") {
@@ -212,7 +196,7 @@ const moduleMap = hooks.reduce((acc, m) => {
const examples = parseExampleTag(docComment);
const contractSubhooks = json.members[0].members.filter(
(f) => f.kind === "Function" && CONTRACT_SUBHOOKS[m.name].includes(f.name),
(f) => f.kind === "Function" && HOOKS_CONFIG[m.name].includes(f.name),
);
const contractHooks = contractSubhooks.map((subhookContent) => {
@@ -223,7 +207,7 @@ const moduleMap = hooks.reduce((acc, m) => {
return {
name: subhookContent.name,
example: subhookExamples?.javascript || "",
reference: `https://portal.thirdweb.com/react/react.${subhookContent.name.toLowerCase()}`,
reference: `${baseDocUrl}${subhookContent.name.toLowerCase()}`,
};
});
@@ -241,6 +225,6 @@ const moduleMap = hooks.reduce((acc, m) => {
}, {});
fs.writeFileSync(
`${process.cwd()}/docs/snippets.json`,
`${process.cwd()}/docs/evm/snippets.json`,
JSON.stringify(moduleMap, null, 2),
);
@@ -0,0 +1,135 @@
import { Formatter } from "./generate-snippets-evm.mjs";
import { TSDocParser } from "@microsoft/tsdoc";
import fs from "fs";
const NFT_HOOKS = ["useMintNFT", "useNFT", "useNFTs", "useTransferNFT"];
const DROP_HOOKS = [
"useClaimedSupply",
"useClaimNFT",
"useLazyMintNFT",
"useUnclaimedSupply",
];
const TOKEN_HOOKS = [
"useMintToken",
"useTokenBalance",
"useTokenSupply",
"useTransferToken",
];
const HOOKS_CONFIG = {
useNFTCollection: [...NFT_HOOKS],
useNFTDrop: [...NFT_HOOKS, ...DROP_HOOKS],
useToken: [...TOKEN_HOOKS],
useProgram: [],
};
const tsdocParser = new TSDocParser();
const json = JSON.parse(
fs.readFileSync(`${process.cwd()}/temp-solana/react.api.json`, "utf8"),
);
function languageNameToKey(languageName) {
switch (languageName) {
case "js":
case "jsx":
return "javascript";
case "ts":
case "tsx":
return "typescript";
default:
return languageName;
}
}
function parseExampleTag(docComment) {
const exampleBlocks = docComment._customBlocks.filter(
(b) => b._blockTag._tagName === "@example",
);
const examplesString = Formatter.renderDocNodes(exampleBlocks);
const regex = /```([a-zA-Z]*)\n([\S\s]*?)\n```/g;
let matches;
const examples = {};
while ((matches = regex.exec(examplesString)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (matches.index === regex.lastIndex) {
regex.lastIndex++;
}
const re = /\n( *)\/\/ For example((.|\n)*)\.\.\.\n/g;
const example = matches[2].replace(re, "");
examples[languageNameToKey(matches[1])] = example;
}
return examples;
}
const baseDocUrl = "https://portal.thirdweb.com/react/react.";
const extractReferenceLink = (m, kind, contractName) => {
if (kind === "Property") {
return m.excerptTokens
.filter((e) => e.kind === "Reference")
.map((e) => `${baseDocUrl}${e.text.toLowerCase()}`)[0];
}
if (kind === "Method") {
return `${baseDocUrl}${contractName}.${m.name}`;
}
return `${baseDocUrl}${m.name}`;
};
const moduleMap = Object.keys(HOOKS_CONFIG).reduce((acc, hookName) => {
let summary = "";
let examples = {};
let reference = "";
const doc = json.members[0].members.find(
(m) =>
m.kind === "Function" && Object.keys(HOOKS_CONFIG).includes(hookName),
);
if (doc) {
const parserContext = tsdocParser.parseString(doc);
const docComment = parserContext.docComment;
summary = Formatter.renderDocNode(docComment.summarySection);
examples = parseExampleTag(docComment);
reference = extractReferenceLink(doc);
}
const contractSubhooks = json.members[0].members.filter(
(f) => f.kind === "Function" && HOOKS_CONFIG[hookName].includes(f.name),
);
const subhooks = contractSubhooks.map((subhookContent) => {
const subhookContext = tsdocParser.parseString(subhookContent.docComment);
const subhookComment = subhookContext.docComment;
const subhookExamples = parseExampleTag(subhookComment);
return {
name: subhookContent.name,
example: subhookExamples?.javascript || "",
reference: `${baseDocUrl}${subhookContent.name.toLowerCase()}`,
};
});
acc[hookName] = {
name: hookName,
summary,
examples,
subhooks,
reference,
};
return acc;
}, {});
fs.writeFileSync(
`${process.cwd()}/docs/solana/snippets.json`,
JSON.stringify(moduleMap, null, 2),
);
@@ -27,7 +27,7 @@ export function neverPersist<TKey extends QueryKey>(key: TKey) {
export function shouldNeverPersistQuery<TKey extends QueryKey>(
key: TKey,
): boolean {
return key[key.length] === NEVER_PERSIST_QUERY_POSTFIX;
return key[key.length - 1] === NEVER_PERSIST_QUERY_POSTFIX;
}
// EVM
@@ -13,7 +13,7 @@ import { ThemeProvider, ThemeProviderProps } from "../shared/ThemeProvider";
import { FiWifi } from "@react-icons/all-files/fi/FiWifi";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { SmartContract } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/smart-contract";
import type { CallOverrides } from "ethers";
import type { CallOverrides, ContractInterface } from "ethers";
import { PropsWithChildren, useMemo } from "react";
import invariant from "tiny-invariant";
@@ -23,6 +23,7 @@ interface Web3ButtonProps<TActionFn extends ActionFn>
extends ThemeProviderProps {
className?: string;
contractAddress: `0x${string}` | `${string}.eth` | string;
contractAbi?: ContractInterface;
overrides?: CallOverrides;
// called with the result
@@ -64,6 +65,7 @@ export const Web3Button = <TAction extends ActionFn>({
onError,
onSubmit,
isDisabled,
contractAbi,
children,
action,
className,
@@ -85,7 +87,7 @@ export const Web3Button = <TAction extends ActionFn>({
return null;
}, [sdkChainId, walletChainId]);
const { contract } = useContract(contractAddress);
const { contract } = useContract(contractAddress, contractAbi || "custom");
const mutation = useMutation(
async () => {
+80 -27
View File
@@ -18,13 +18,16 @@ import {
import {
CommonContractSchemaInput,
ContractEvent,
ContractForPrebuiltContractType,
ContractType,
EventQueryFilter,
PrebuiltContractType,
SUPPORTED_CHAIN_ID,
ThirdwebSDK,
ValidContractInstance,
} from "@thirdweb-dev/sdk";
import type { SmartContract } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/smart-contract";
import { CallOverrides } from "ethers";
import { CallOverrides, ContractInterface } from "ethers";
import { useEffect, useMemo } from "react";
import invariant from "tiny-invariant";
@@ -147,9 +150,55 @@ export type UseContractResult<
* @returns a response object that includes the contract once it is resolved
* @public
*/
export function useContract<
TContract extends ValidContractInstance = SmartContract,
>(contractAddress: RequiredParam<ContractAddress>) {
export function useContract(
contractAddress: RequiredParam<ContractAddress>,
): UseContractResult<SmartContract>;
/**
* Use this resolve a contract address to a smart contract instance.
*
* @example
* ```javascript
* const { contract, isLoading, error } = useContract("{{contract_address}}", "nft-drop");
* ```
*
* @param contractAddress - the address of the deployed contract
* @param _contractType - the type of the contract
* @returns a response object that includes the contract once it is resolved
* @public
*/
export function useContract<TContractType extends ContractType>(
contractAddress: RequiredParam<ContractAddress>,
_contractType: TContractType,
): UseContractResult<
TContractType extends PrebuiltContractType
? ContractForPrebuiltContractType<TContractType>
: SmartContract
>;
/**
* Use this resolve a contract address to a smart contract instance.
*
* @example
* ```javascript
* const { contract, isLoading, error } = useContract("{{contract_address}}", ABI);
* ```
*
* @param contractAddress - the address of the deployed contract
* @param _abi - the ABI of the contract to use
* @returns a response object that includes the contract once it is resolved
* @public
*/
export function useContract(
contractAddress: RequiredParam<ContractAddress>,
_abi: ContractInterface,
): UseContractResult<SmartContract>;
export function useContract(
contractAddress: RequiredParam<ContractAddress>,
contractTypeOrABI?: ContractType | ContractInterface,
) {
const sdk = useSDK();
const queryClient = useQueryClient();
const activeChainId = useSDKChainId();
@@ -170,29 +219,33 @@ export function useContract<
invariant(contractAddress, "contract address is required");
invariant(sdk, "SDK not initialized");
invariant(activeChainId, "active chain id is required");
// first fetch the contract type (we fetch this explicitly via the queryClient so **it** gets cached!)
const cType = await queryClient.fetchQuery(
contractType.cacheKey(contractAddress, activeChainId),
() => contractType.fetchQuery(contractAddress, sdk),
{ cacheTime: Infinity, staleTime: Infinity },
);
// if we can't get the contract type, we need to exit
invariant(cType, "could not get contract type");
// if the contract type is NOT "custom", we can use the built-in contract method from the SDK
if (cType !== "custom") {
return await sdk.getBuiltInContract(contractAddress, cType);
}
// if the contract type is "custom", we need to fetch the compiler metadata
const compMetadata = await queryClient.fetchQuery(
compilerMetadata.cacheKey(contractAddress, activeChainId),
() => compilerMetadata.fetchQuery(contractAddress, sdk),
{ cacheTime: Infinity, staleTime: Infinity },
);
// if we can't get the compiler metadata, we need to exit
invariant(compMetadata, "could not get compiler metadata");
// if we have the compiler metadata, we can use the custom contract
return sdk.getContractFromAbi(contractAddress, compMetadata.abi);
// if we don't have a contractType or ABI then we will have to resolve it regardless
// we also handle it being "custom" just in case...
if (!contractTypeOrABI || contractTypeOrABI === "custom") {
// we just resolve here (sdk does this internally anyway)
const resolvedContractType = await queryClient.fetchQuery(
contractType.cacheKey(contractAddress, activeChainId),
() => contractType.fetchQuery(contractAddress, sdk),
{ cacheTime: Infinity, staleTime: Infinity },
);
let abi: ContractInterface | undefined;
if (resolvedContractType === "custom") {
abi = (
await queryClient.fetchQuery(
compilerMetadata.cacheKey(contractAddress, activeChainId),
() => compilerMetadata.fetchQuery(contractAddress, sdk),
{ cacheTime: Infinity, staleTime: Infinity },
)
)?.abi;
}
invariant(resolvedContractType, "failed to resolve contract type");
// just let the sdk handle the rest
// if we have resolved an ABI for a custom contract, use that otherwise use contract type
return sdk.getContract(contractAddress, abi || resolvedContractType);
}
// every other case can just be handled by the sdk directly
return sdk.getContract(contractAddress, contractTypeOrABI);
},
{
// keep the previous value around while we fetch the new one
@@ -211,7 +264,7 @@ export function useContract<
...contractQuery,
data: contractQuery.data,
contract: contractQuery.data,
} as UseContractResult<TContract>;
} as UseContractResult<ValidContractInstance>;
}
/**
+10 -65
View File
@@ -6,10 +6,8 @@ import {
MintNFTParams,
MintNFTReturnType,
MintNFTSupplyParams,
NFT,
TransferNFTParams,
WalletAddress,
Erc721OrErc1155,
NFTContract,
getErcs,
} from "../../types";
@@ -19,45 +17,10 @@ import {
} from "../../utils/cache-keys";
import { useQueryWithNetwork } from "../query-utils/useQueryWithNetwork";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Erc721, Erc1155, QueryAllParams } from "@thirdweb-dev/sdk";
import { Erc1155, QueryAllParams, NFT } from "@thirdweb-dev/sdk";
import { BigNumber, BigNumberish } from "ethers";
import invariant from "tiny-invariant";
/**
* @internal
*/
export function convertResponseToNFTType(
contract: Erc721OrErc1155,
metadata: Awaited<ReturnType<typeof contract["get"]>>,
): NFT<typeof contract> {
if (contract instanceof Erc721) {
return {
type: "ERC721",
supply: 1,
owner: "",
...metadata,
} as NFT<Erc721>;
}
if (contract instanceof Erc1155) {
return {
type: "ERC1155",
supply: 0,
owner: "",
...metadata,
} as NFT<Erc1155>;
}
invariant(false, "Unknown NFT type");
}
/**
* @internal
*/
export function convertResponseToNFTTypeArray(
contract: Erc721OrErc1155,
metadata: Awaited<ReturnType<typeof contract["get"]>>[],
): NFT<typeof contract>[] {
return metadata.map((m) => convertResponseToNFTType(contract, m));
}
/** **********************/
/** READ HOOKS **/
/** **********************/
@@ -84,24 +47,18 @@ export function useNFT<TContract extends NFTContract>(
const contractAddress = contract?.getAddress();
const { erc721, erc1155 } = getErcs(contract);
return useQueryWithNetwork<NFT<Erc721OrErc1155>>(
return useQueryWithNetwork<NFT>(
cacheKeys.contract.nft.get(contractAddress, tokenId),
async () => {
invariant(contract, "No Contract instance provided");
if (erc1155) {
invariant(erc1155.get, "Contract instance does not support get");
return convertResponseToNFTType(
erc1155,
await erc1155.get(BigNumber.from(tokenId || 0)),
);
return await erc1155.get(BigNumber.from(tokenId || 0));
}
if (erc721) {
invariant(erc721.get, "Contract instance does not support get");
return convertResponseToNFTType(
erc721,
await erc721.get(BigNumber.from(tokenId || 0)),
);
return await erc721.get(BigNumber.from(tokenId || 0));
}
invariant(false, "Unknown NFT type");
},
@@ -133,24 +90,18 @@ export function useNFTs<TContract extends NFTContract>(
const contractAddress = contract?.getAddress();
const { erc721, erc1155 } = getErcs(contract);
return useQueryWithNetwork<NFT<Erc721OrErc1155>[]>(
return useQueryWithNetwork<NFT[]>(
cacheKeys.contract.nft.query.all(contractAddress, queryParams),
async () => {
invariant(contract, "No Contract instance provided");
if (erc721) {
invariant(erc721.getAll, "Contract instance does not support getAll");
return convertResponseToNFTTypeArray(
erc721,
await erc721.getAll(queryParams),
);
return await erc721.getAll(queryParams);
}
if (erc1155) {
invariant(erc1155.getAll, "Contract instance does not support getAll");
return convertResponseToNFTTypeArray(
erc1155,
await erc1155.getAll(queryParams),
);
return await erc1155.getAll(queryParams);
}
invariant(false, "Unknown NFT type");
},
@@ -278,22 +229,16 @@ export function useOwnedNFTs<TContract extends NFTContract>(
const contractAddress = contract?.getAddress();
const { erc721, erc1155 } = getErcs(contract);
return useQueryWithNetwork<NFT<Erc721OrErc1155>[]>(
return useQueryWithNetwork<NFT[]>(
cacheKeys.contract.nft.query.owned.all(contractAddress, ownerWalletAddress),
async () => {
invariant(contract, "No Contract instance provided");
invariant(ownerWalletAddress, "No wallet address provided");
if (erc721) {
return convertResponseToNFTTypeArray(
erc721,
await erc721.getOwned(ownerWalletAddress),
);
return await erc721.getOwned(ownerWalletAddress);
}
if (erc1155) {
return convertResponseToNFTTypeArray(
erc1155,
await erc1155.getOwned(ownerWalletAddress),
);
return await erc1155.getOwned(ownerWalletAddress);
}
invariant(false, "Unknown NFT type");
},
+91 -48
View File
@@ -2,7 +2,9 @@ import { RequiredParam } from "../../../core/types/shared";
import { useSDKChainId } from "../../providers/base";
import {
ClaimTokenParams,
getErc20,
TokenBurnParams,
TokenContract,
TokenParams,
WalletAddress,
} from "../../types";
@@ -24,21 +26,26 @@ import invariant from "tiny-invariant";
*
* @example
* ```javascript
* const { data: totalSupply, isLoading, error } = useTokenSupply(<YourTokenContractInstance>);
* const { contract } = useContract(<ContractAddress>);
* const { data: totalSupply, isLoading, error } = useTokenSupply(contract);
* ```
*
* @param contract - an instance of a ERC20 contract.
* @param contract - an instance of a {@link TokenContract}
* @returns a response object that incudes the total minted supply
* @twfeature ERC20
* @beta
*/
export function useTokenSupply(contract: RequiredParam<Erc20>) {
export function useTokenSupply(contract: RequiredParam<TokenContract>) {
const contractAddress = contract?.getAddress();
return useQueryWithNetwork(
cacheKeys.contract.token.totalSupply(contractAddress),
() => {
invariant(contract, "No Contract instance provided");
return contract.totalSupply();
const erc20 = getErc20(contract);
if (erc20) {
return erc20.totalSupply();
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
enabled: !!contract || !!contractAddress,
@@ -51,26 +58,32 @@ export function useTokenSupply(contract: RequiredParam<Erc20>) {
*
* @example
* ```javascript
* const { data: balance, isLoading, error } = useTokenBalance(<YourTokenContractInstance>);
* const { contract } = useContract(<ContractAddress>);
* const { data: balance, isLoading, error } = useTokenBalance(contract);
* ```
*
* @param contract - an instance of a ERC20 contract.
* @param contract - an instance of a {@link TokenContract}
* @returns a response object that includes the balance of the address
* @twfeature ERC20
* @beta
*/
export function useTokenBalance(
contract: RequiredParam<Erc20>,
contract: RequiredParam<TokenContract>,
walletAddress: RequiredParam<WalletAddress>,
) {
const contractAddress = contract?.getAddress();
const erc20 = getErc20(contract);
return useQueryWithNetwork(
cacheKeys.contract.token.balanceOf(contractAddress, walletAddress),
async () => {
invariant(contract, "No Contract instance provided");
invariant(walletAddress, "No address provided");
return await contract.balanceOf(walletAddress);
if (erc20) {
return await erc20.balanceOf(walletAddress);
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
enabled: !!walletAddress && !!contract,
},
@@ -82,21 +95,27 @@ export function useTokenBalance(
*
* @example
* ```javascript
* const { data: decimals, isLoading, error } = useTokenDecimals(<YourTokenContractInstance>);
* const { contract } = useContract(<ContractAddress>);
* const { data: decimals, isLoading, error } = useTokenDecimals(contract);
* ```
*
* @param contract - an instance of an ERC20 contract.
* @param contract - an instance of a {@link TokenContract}
* @returns a response object that includes the decimals of the ERC20 token
* @twfeature ERC20
* @beta
*/
export function useTokenDecimals(contract: RequiredParam<Erc20>) {
export function useTokenDecimals(contract: RequiredParam<TokenContract>) {
const contractAddress = contract?.getAddress();
const erc20 = getErc20(contract);
return useQueryWithNetwork(
cacheKeys.contract.token.decimals(contractAddress),
async () => {
invariant(contract, "No Contract instance provided");
return (await contract.get()).decimals;
if (erc20) {
return (await erc20.get()).decimals;
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
enabled: !!contract,
@@ -114,11 +133,12 @@ export function useTokenDecimals(contract: RequiredParam<Erc20>) {
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const {
* mutate: mintTokens,
* isLoading,
* error,
* } = useMintToken(">>YourERC20ContractInstance<<");
* } = useMintToken(contract);
*
* if (error) {
* console.error("failed to mint tokens", error);
@@ -135,21 +155,25 @@ export function useTokenDecimals(contract: RequiredParam<Erc20>) {
* };
* ```
*
* @param contract - an instance of a contract that extends the ERC20 spec (token, token drop, custom contract that follows the ERC20 spec)
* @param contract - an instance of a {@link TokenContract}
* @returns a mutation object that can be used to mint new tokens to the connected wallet
* @twfeature ERC20Mintable
* @beta
*/
export function useMintToken(contract: RequiredParam<Erc20>) {
export function useMintToken(contract: RequiredParam<TokenContract>) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
const erc20 = getErc20(contract);
return useMutation(
(data: TokenParams) => {
const { to, amount } = data;
invariant(contract, "contract is undefined");
return contract.mintTo(to, amount);
if (erc20) {
return erc20.mintTo(to, amount);
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
onSettled: () =>
@@ -168,11 +192,12 @@ export function useMintToken(contract: RequiredParam<Erc20>) {
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const {
* mutate: claimTokens,
* isLoading,
* error,
* } = useClaimToken(TokenDropContract);
* } = useClaimToken(contract);
*
* if (error) {
* console.error("failed to claim tokens", error);
@@ -189,27 +214,29 @@ export function useMintToken(contract: RequiredParam<Erc20>) {
* };
* ```
*
* @param contract - an instance of a {@link Erc20}
* @param contract - an instance of a {@link TokenContract}
* @returns a mutation object that can be used to tokens to the wallet specificed in the params
* @twfeature ERC20ClaimableWithConditions
* @beta
*/
export function useClaimToken<TContract extends Erc20>(
contract: RequiredParam<TContract>,
) {
export function useClaimToken(contract: RequiredParam<TokenContract>) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
const erc20 = getErc20(contract);
return useMutation(
async (data: ClaimTokenParams) => {
invariant(data.to, 'No "to" address provided');
invariant(contract?.claimTo, "contract does not support claimTo");
return await contract.claimTo(
data.to,
data.amount,
data.checkERC20Allowance,
);
if (erc20) {
invariant(erc20?.claimTo, "contract does not support claimTo");
return await erc20.claimTo(
data.to,
data.amount,
data.checkERC20Allowance,
);
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
onSettled: () =>
@@ -228,11 +255,12 @@ export function useClaimToken<TContract extends Erc20>(
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const {
* mutate: transferTokens,
* isLoading,
* error,
* } = useTransferToken(">>YourERC20ContractInstance<<");
* } = useTransferToken(contract);
*
* if (error) {
* console.error("failed to transfer tokens", error);
@@ -249,21 +277,25 @@ export function useClaimToken<TContract extends Erc20>(
* };
* ```
*
* @param contract - an instance of a contract that extends the ERC20 spec (token, token drop, custom contract that follows the ERC20 spec)
* @param contract - an instance of a {@link TokenContract}
* @returns a mutation object that can be used to transfer tokens
* @twfeature ERC20
* @beta
*/
export function useTransferToken(contract: RequiredParam<Erc20>) {
export function useTransferToken(contract: RequiredParam<TokenContract>) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
const erc20 = getErc20(contract);
return useMutation(
(data: TokenParams) => {
const { to, amount } = data;
invariant(contract?.transfer, "contract does not support transfer");
return contract.transfer(to, amount);
if (erc20) {
invariant(erc20?.transfer, "contract does not support transfer");
return erc20.transfer(to, amount);
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
onSettled: () =>
@@ -282,11 +314,12 @@ export function useTransferToken(contract: RequiredParam<Erc20>) {
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const {
* mutate: transferBatchTokens,
* isLoading,
* error,
* } = useTransferToken(">>YourERC20ContractInstance<<");
* } = useTransferToken(contract);
*
* if (error) {
* console.error("failed to transfer batch tokens", error);
@@ -303,28 +336,32 @@ export function useTransferToken(contract: RequiredParam<Erc20>) {
* };
* ```
*
* @param contract - an instance of a contract that extends the ERC20 spec (token, token drop, custom contract that follows the ERC20 spec)
* @param contract - an instance of a {@link TokenContract}
* @returns a mutation object that can be used to transfer batch tokens
* @twfeature ERC20
* @beta
*/
export function useTransferBatchToken(contract: RequiredParam<Erc20>) {
export function useTransferBatchToken(contract: RequiredParam<TokenContract>) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
const erc20 = getErc20(contract);
return useMutation(
(data: TokenParams[]) => {
invariant(
contract?.transferBatch,
"contract does not support transferBatch",
);
const convertedData = data.map((token) => ({
toAddress: token.to,
amount: token.amount,
}));
if (erc20) {
invariant(
erc20?.transferBatch,
"contract does not support transferBatch",
);
const convertedData = data.map((token) => ({
toAddress: token.to,
amount: token.amount,
}));
return contract.transferBatch(convertedData);
return erc20.transferBatch(convertedData);
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
onSettled: () =>
@@ -343,11 +380,12 @@ export function useTransferBatchToken(contract: RequiredParam<Erc20>) {
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const {
* mutate: burnTokens,
* isLoading,
* error,
* } = useBurnToken(">>YourERC20ContractInstance<<");
* } = useBurnToken(contract);
*
* if (error) {
* console.error("failed to burn tokens", error);
@@ -364,21 +402,26 @@ export function useTransferBatchToken(contract: RequiredParam<Erc20>) {
* };
* ```
*
* @param contract - an instance of a contract that extends the ERC20 spec (token, token drop, custom contract that follows the ERC20 spec)
* @param contract - an instance of a {@link TokenContract}
* @returns a mutation object that can be used to burn tokens from the connected wallet
* @twfeature ERC20Burnable
* @beta
*/
export function useBurnToken(contract: RequiredParam<Erc20>) {
export function useBurnToken(contract: RequiredParam<TokenContract>) {
const activeChainId = useSDKChainId();
const contractAddress = contract?.getAddress();
const queryClient = useQueryClient();
const erc20 = getErc20(contract);
return useMutation(
(data: TokenBurnParams) => {
const { amount } = data;
invariant(contract, "contract is undefined");
return contract.burn(amount);
if (erc20) {
invariant(erc20?.burn, "contract does not support burn");
return erc20.burn(amount);
}
invariant(false, "Smart contract is not a valid erc20 contract");
},
{
onSettled: () =>
@@ -2,6 +2,9 @@ import { useConnect } from "../wagmi-required/useConnect";
import invariant from "tiny-invariant";
import { useContext as useWagmiContext } from "wagmi";
if (!globalThis.Buffer) {
globalThis.Buffer = require("buffer/").Buffer;
}
/**
* Hook for connecting to a mobile wallet with Wallet Connect
*
@@ -2,6 +2,9 @@ import { useConnect } from "../wagmi-required/useConnect";
import invariant from "tiny-invariant";
import { useContext as useWagmiContext } from "wagmi";
if (!globalThis.Buffer) {
globalThis.Buffer = require("buffer/").Buffer;
}
/**
* Hook for connecting to a Coinbase wallet.
*
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Edition } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/edition";
/**
* Hook for getting an instance of an `Edition` contract. This contract is used to interface with ERC1155 compliant NFTs.
@@ -25,9 +25,17 @@ import { Edition } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/p
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const edition = await sdk.useEdition("0x1234...");
* + const edition = await sdk.useContract("0x1234...", "edition").contract;
* ```
*/
export function useEdition(contractAddress?: string) {
showDeprecationWarning("useEdition()", "useContract<Edition>()");
return useContract<Edition>(contractAddress).contract;
export function useEdition(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useEdition("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "edition")`,
);
return useContract(contractAddress, "edition").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { EditionDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/edition-drop";
/**
* Hook for getting an instance of an `EditionDrop` contract. This conract is used to interface with ERC1155 compliant NFTs that can be lazily minted.
@@ -24,9 +24,17 @@ import { EditionDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contrac
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const editionDrop = await sdk.useEditionDrop("0x1234...");
* + const editionDrop = await sdk.useContract("0x1234...", "edition-drop").contract;
* ```
*/
export function useEditionDrop(contractAddress?: string) {
showDeprecationWarning("useEditionDrop()", "useContract<EditionDrop>()");
return useContract<EditionDrop>(contractAddress).contract;
export function useEditionDrop(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useEditionDrop("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "edition-drop")`,
);
return useContract(contractAddress, "edition-drop").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Marketplace } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/marketplace";
/**
* Hook for getting an instance of a `Marketplace` contract. This contract is used to support marketplace for purchase and sale of on-chain assets.
@@ -25,9 +25,17 @@ import { Marketplace } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contrac
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const marketplace = await sdk.useMarketplace("0x1234...");
* + const marketplace = await sdk.useContract("0x1234...", "marketplace").contract;
* ```
*/
export function useMarketplace(contractAddress?: string) {
showDeprecationWarning("useMarketplace()", "useContract<Marketplace>()");
return useContract<Marketplace>(contractAddress).contract;
export function useMarketplace(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useMarketplace("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "marketplace")`,
);
return useContract(contractAddress, "marketplace").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Multiwrap } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/multiwrap";
/**
* Hook for getting an instance of an `Multiwrap` contract. This contract is an ERC721 in which you can wrap ERC721, ERC1155 and ERC20 tokens.
@@ -24,9 +24,17 @@ import { Multiwrap } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const multiwrap = await sdk.useMultiwrap("0x1234...");
* + const multiwrap = await sdk.useContract("0x1234...", "multiwrap").contract;
* ```
*/
export function useMultiwrap(contractAddress?: string) {
showDeprecationWarning("useMultiwrap()", "useContract<Multiwrap>()");
return useContract<Multiwrap>(contractAddress).contract;
export function useMultiwrap(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useMultiwrap("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "multiwrap")`,
);
return useContract(contractAddress, "multiwrap").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { NFTCollection } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/nft-collection";
/**
* Hook for getting an instance of an `NFTCollection` contract. This contract is meant to interface with ERC721 compliant NFTs.
@@ -25,9 +25,17 @@ import { NFTCollection } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contr
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const nftCollection = await sdk.useNFTCollection("0x1234...");
* + const nftCollection = await sdk.useContract("0x1234...", "nft-collection").contract;
* ```
*/
export function useNFTCollection(contractAddress?: string) {
showDeprecationWarning("useNFTCollection()", "useContract<NFTCollection>()");
return useContract<NFTCollection>(contractAddress).contract;
export function useNFTCollection(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useNFTCollection("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "nft-collection")`,
);
return useContract(contractAddress, "nft-collection").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { NFTDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/nft-drop";
/**
* Hook for getting an instance of an `NFTDrop` contract. This contract is meant to interface with ERC721 compliant NFTs that can be lazily minted.
@@ -24,9 +24,17 @@ import { NFTDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/p
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const nftDrop = await sdk.useNFTDrop("0x1234...");
* + const nftDrop = await sdk.useContract("0x1234...", "nft-drop").contract;
* ```
*/
export function useNFTDrop(contractAddress?: string) {
showDeprecationWarning("useNFTDrop()", "useContract<NFTDrop>()");
return useContract<NFTDrop>(contractAddress).contract;
export function useNFTDrop(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useNFTDrop("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "nft-drop")`,
);
return useContract(contractAddress, "nft-drop").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Pack } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/pack";
/**
* Hook for getting an instance of a `Pack` contract. This contract supports the creation of on-chain luck-based lootboxes.
@@ -25,9 +25,17 @@ import { Pack } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/preb
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const pack = await sdk.usePack("0x1234...");
* + const pack = await sdk.useContract("0x1234...", "pack").contract;
* ```
*/
export function usePack(contractAddress?: string) {
showDeprecationWarning("usePack()", "useContract<Pack>()");
return useContract<Pack>(contractAddress).contract;
export function usePack(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`usePack("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "pack")`,
);
return useContract(contractAddress, "pack").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { SignatureDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/signature-drop";
/**
* Hook for getting an instance of an `SignatureDrop` contract. This contract is meant to interface with ERC721 compliant NFTs that can be lazily minted.
@@ -24,9 +24,17 @@ import { SignatureDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contr
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const signatureDrop = await sdk.useSignatureDrop("0x1234...");
* + const signatureDrop = await sdk.useContract("0x1234...", "signature-drop").contract;
* ```
*/
export function useSignatureDrop(contractAddress?: string) {
showDeprecationWarning("useSignatureDrop()", "useContract<SignatureDrop>()");
return useContract<SignatureDrop>(contractAddress).contract;
export function useSignatureDrop(contractAddress?: RequiredParam<string>) {
showDeprecationWarning(
`useSignatureDrop("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "signature-drop")`,
);
return useContract(contractAddress, "signature-drop").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Split } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/split";
/**
* Hook for getting an instance of a `Split` contract. This contract supports fund distribution to multiple parties.
@@ -25,9 +25,17 @@ import { Split } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/pre
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const split = await sdk.useSplit("0x1234...");
* + const split = await sdk.useContract("0x1234...", "split").contract;
* ```
*/
export function useSplit(contractAddress?: string) {
showDeprecationWarning("useSplit()", "useContract<Split>()");
return useContract<Split>(contractAddress).contract;
export function useSplit(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useSplit("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "split")`,
);
return useContract(contractAddress, "split").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Token } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/token";
/**
* Hook for getting an instance of a `Token` contract. This contract supports ERC20 compliant tokens.
@@ -25,9 +25,17 @@ import { Token } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/pre
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const token = await sdk.useToken("0x1234...");
* + const token = await sdk.useContract("0x1234...", "token").contract;
* ```
*/
export function useToken(contractAddress?: string) {
showDeprecationWarning("useToken()", "useContract<Token>()");
return useContract<Token>(contractAddress).contract;
export function useToken(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useToken("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "token")`,
);
return useContract(contractAddress, "token").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { TokenDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/token-drop";
/**
* Hook for getting an instance of a `Token Drop` contract.
@@ -25,9 +25,17 @@ import { TokenDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const token = await sdk.useTokenDrop("0x1234...");
* + const token = await sdk.useContract("0x1234...", "token-drop").contract;
* ```
*/
export function useTokenDrop(contractAddress?: string) {
showDeprecationWarning("useTokenDrop()", "useContract<TokenDrop>()");
return useContract<TokenDrop>(contractAddress).contract;
export function useTokenDrop(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useTokenDrop("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "token-drop")`,
);
return useContract(contractAddress, "token-drop").contract;
}
@@ -1,6 +1,6 @@
import { RequiredParam } from "../../../core/types/shared";
import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts";
import { Vote } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/vote";
/**
* Hook for getting an instance of an `Vote` contract. This contract enables fully featured voting-based decentralized governance systems.
@@ -25,9 +25,17 @@ import { Vote } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/preb
* }
* ```
* @public
* @deprecated use `useContract()` instead
* @deprecated
* This hook is deprecated and will be removed in a future major version. You should use {@link useContract} instead.
* ```diff
* - const vote = await sdk.useVote("0x1234...");
* + const vote = await sdk.useContract("0x1234...", "vote").contract;
* ```
*/
export function useVote(contractAddress?: string) {
showDeprecationWarning("useVote()", "useContract<Vote>()");
return useContract<Vote>(contractAddress).contract;
export function useVote(contractAddress: RequiredParam<string>) {
showDeprecationWarning(
`useVote("${contractAddress || "0x..."}")`,
`useContract("${contractAddress || "0x..."}", "vote")`,
);
return useContract(contractAddress, "vote").contract;
}
+12 -27
View File
@@ -7,13 +7,13 @@ import type {
Erc1155,
Erc1155Mintable,
ListingType,
NFTMetadata,
NFTMetadataInput,
NFTMetadataOrUri,
Price,
ValidContractInstance,
Erc20,
ClaimOptions,
NFTMetadataOrUri,
Token,
} from "@thirdweb-dev/sdk";
import type { Edition } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/edition";
import type { EditionDrop } from "@thirdweb-dev/sdk/dist/declarations/src/evm/contracts/prebuilt-implementations/edition-drop";
@@ -70,37 +70,22 @@ export type NFTContract =
| Edition
| Exclude<DropContract, "TokenDrop">;
/**
* The possible Token contract types.
* @example
* ```javascript
* const { contract } = useContract(<ContractAddress>);
* ```
* @beta
*/
export type TokenContract = TokenDrop | Token | SmartContract | null;
/**
* Possible NFT contract types.
* @beta
*/
export type Erc721OrErc1155 = Erc721 | Erc1155;
/**
* A single NFT token
* @beta
*/
export type NFT<TContract extends Erc721OrErc1155> = {
/**
* The actual metadata of the NFT (name, image, etc)
*/
metadata: NFTMetadata;
/**
* The owner of the nft (this will be an empty string for ERC1155 tokens)
*/
owner: string;
/**
* The type of the NFT (ERC721 or ERC1155)
*/
type: TContract extends Erc721 ? "ERC721" : "ERC1155";
/**
* The total supply of the NFT (this will *always* be 1 for ERC721 tokens)
*/
supply: TContract extends Erc721 ? 1 : number;
[key: string]: unknown;
};
/**
* The params to pass to `useTransferNFT`.
* @beta
@@ -4,6 +4,28 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { NFTDrop } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
/**
* Claim NFTs from an NFT Drop program
* @param program - The NFT Drop program instance to claim from
*
* @example
* ```jsx
* import { useProgram, useClaimNFT } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: claim, isLoading, error } = useClaimNFT(program);
*
* return (
* <button onClick={() => claim(1)}>
* Claim
* </button>
* )
* }
* ```
*
* @public
*/
export function useClaimNFT(program: RequiredParam<NFTDrop>) {
const queryClient = useQueryClient();
return useMutation(
@@ -19,6 +19,26 @@ export function dropTotalClaimedSupplyQuery(program: RequiredParam<NFTDrop>) {
};
}
/**
* Get the total claimed supply of NFTs on an NFT Drop
* @param program - The NFT Drop program to get the claimed supply on
*
* @example
* ```jsx
* import { useProgram, useDropTotalClaimedSupply } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { data: claimedSupply, isLoading } = useDropTotalClaimedSupply(program);
*
* return (
* <p>{claimedSupply}</p>
* )
* }
* ```
*
* @public
*/
export function useDropTotalClaimedSupply(program: RequiredParam<NFTDrop>) {
return useQuery(dropTotalClaimedSupplyQuery(program));
}
@@ -0,0 +1,51 @@
import { createSOLProgramQueryKey } from "../../../../core/query-utils/query-key";
import { RequiredParam } from "../../../../core/types/shared";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { NFTMetadataInput, UploadProgressEvent } from "@thirdweb-dev/sdk";
import type { NFTDrop } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
/**
* Lazy mint NFTs on an NFT Drop program
* @param program - The NFT Drop program instance to lazy mint on
*
* @example
* ```jsx
* import { useProgram, useLazyMintNFT } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: lazyMint, isLoading, error } = useLazyMintNFT(program);
*
* return (
* <button onClick={() => lazyMint({ name: "My NFT", description: "..." })}>
* Claim
* </button>
* )
* }
* ```
*
* @public
*/
export function useLazyMint(
program: RequiredParam<NFTDrop>,
onProgress?: (progress: UploadProgressEvent) => void,
) {
const queryClient = useQueryClient();
return useMutation(
async (data: { metadatas: NFTMetadataInput[] }) => {
invariant(program, "program is required");
let options;
if (onProgress) {
options = {
onProgress,
};
}
return await program.lazyMint(data.metadatas, options);
},
{
onSettled: () =>
queryClient.invalidateQueries(createSOLProgramQueryKey(program)),
},
);
}
@@ -1,19 +0,0 @@
import { createSOLProgramQueryKey } from "../../../../core/query-utils/query-key";
import { RequiredParam } from "../../../../core/types/shared";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { NFTDrop, NFTMetadataInput } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
export function useLazyMintNFT(program: RequiredParam<NFTDrop>) {
const queryClient = useQueryClient();
return useMutation(
async (metadata: NFTMetadataInput[]) => {
invariant(program, "program is required");
return await program.lazyMint(metadata);
},
{
onSettled: () =>
queryClient.invalidateQueries(createSOLProgramQueryKey(program)),
},
);
}
@@ -19,6 +19,26 @@ export function dropUnclaimedSupplyQuery(program: RequiredParam<NFTDrop>) {
};
}
/**
* Get the total unclaimed supply of NFTs on an NFT Drop
* @param program - The NFT Drop program to get the unclaimed supply on
*
* @example
* ```jsx
* import { useProgram, useDropTotalUnclaimedSupply } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { data: unclaimedSupply, isLoading } = useDropTotalUnclaimedSupply(program);
*
* return (
* <p>{unclaimedSupply}</p>
* )
* }
* ```
*
* @public
*/
export function useDropUnclaimedSupply(program: RequiredParam<NFTDrop>) {
return useQuery(dropUnclaimedSupplyQuery(program));
}
@@ -0,0 +1,43 @@
import { createSOLProgramQueryKey } from "../../../core/query-utils/query-key";
import { RequiredParam } from "../../../core/types/shared";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
/**
* Burn an NFT owned by the connected wallet
* @param program - The NFT program instance to burn NFTs on
*
* @example
* ```jsx
* import { useProgram, useBurnNFT } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: burn, isLoading, error } = useBurnNFT(program);
*
* return (
* <button
* onClick={() => burn("...")}
* >
* Burn
* </button>
* )
* }
* ```
*
* @public
*/
export function useBurnNFT(program: RequiredParam<NFTCollection | NFTDrop>) {
const queryClient = useQueryClient();
return useMutation(
async (nftAddress: string) => {
invariant(program, "program is required");
return await program.burn(nftAddress);
},
{
onSettled: () =>
queryClient.invalidateQueries(createSOLProgramQueryKey(program)),
},
);
}
@@ -2,16 +2,42 @@ import { createSOLProgramQueryKey } from "../../../core/query-utils/query-key";
import { RequiredParam } from "../../../core/types/shared";
import { MintNFTParams } from "../../../evm/types";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { NFTCollection, NFTMetadataInput } from "@thirdweb-dev/sdk/solana";
import type { NFTCollection } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
/**
* Mint NFTs on your NFT program
* @param program - The NFT program to mint NFTs to
*
* @example
* ```jsx
* import { useProgram, useMintNFT } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: mint, isLoading, error } = useMintNFT(program);
*
* function mintNFT() {
* const metadata = { name: "First NFT", description: "This is a cool NFT!" };
* mint({ to: "{{wallet_address}}", metadata });
* }
*
* return (
* <button onClick={() => mintNFT()}>
* Mint
* </button>
* )
* }
* ```
*
* @public
*/
export function useMintNFT(program: RequiredParam<NFTCollection>) {
const queryClient = useQueryClient();
return useMutation(
async (data: MintNFTParams) => {
invariant(program, "program is required");
// TODO fix this once consolidated
return await program.mintTo(data.to, data.metadata as NFTMetadataInput);
return await program.mintTo(data.to, data.metadata);
},
{
onSettled: () =>
@@ -23,6 +23,27 @@ export function nftGetOneQuery(
};
}
/**
* Get the metadata for a minted NFT
* @param program - The NFT program to get NFT metadata from
* @param - tokenAdress - The mint address of the NFT to get the metadata of
*
* @example
* ```jsx
* import { useProgram, useNFT } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { data: metadata, isLoading } = useNFT(program, mintAddress);
*
* return (
* <pre>{JSON.stringify(metadata)}</pre>
* )
* }
* ```
*
* @public
*/
export function useNFT(
program: RequiredParam<NFTCollection | NFTDrop>,
tokenAddress: RequiredParam<string>,
@@ -18,6 +18,26 @@ export function nftGetAllQuery(
};
}
/**
* Get the metadata for every NFT on an NFT program
* @param program - The NFT program to get NFTs metadata from
*
* @example
* ```jsx
* import { useProgram, useNFTs } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { data: metadata, isLoading } = useNFTs(program);
*
* return (
* <pre>{JSON.stringify(metadata)}</pre>
* )
* }
* ```
*
* @public
*/
export function useNFTs(program: RequiredParam<NFTCollection | NFTDrop>) {
return useQuery(nftGetAllQuery(program));
}
@@ -1,7 +1,7 @@
import { createSOLProgramQueryKey } from "../../../core/query-utils/query-key";
import { RequiredParam } from "../../../core/types/shared";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { NFTCollection } from "@thirdweb-dev/sdk/solana";
import type { NFTCollection, NFTDrop } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
export type TransferNFTMutationParams = {
@@ -9,7 +9,36 @@ export type TransferNFTMutationParams = {
tokenAddress: string;
};
export function useTransferNFT(program: RequiredParam<NFTCollection>) {
/**
* Transfer NFTs from the connected wallet to another wallet
* @param program - The NFT program instance to transfer NFTs on
*
* @example
* ```jsx
* import { useProgram, useTransferNFT } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: transfer, isLoading, error } = useTransferNFT(program);
*
* return (
* <button
* onClick={() => transfer({
* receiverAddress: "{{wallet_address}}",
* tokenAddress: "..."
* })}
* >
* Transfer
* </button>
* )
* }
* ```
*
* @public
*/
export function useTransferNFT(
program: RequiredParam<NFTCollection | NFTDrop>,
) {
const queryClient = useQueryClient();
return useMutation(
async ({ tokenAddress, receiverAddress }: TransferNFTMutationParams) => {
@@ -67,6 +67,31 @@ export function programQuery<TProgramType extends ProgramType>(
};
}
/**
* Get an SDK instance to interact with any program
* @param address - the address of the program to get an interface for
* @param type - optionally, pass in the program type to get static typing
*
* @example
* ```jsx
* import { useProgram } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
*
* // Now you can use the program in the rest of the component
*
* // For example, we can make a transaction
* async function functionCall() {
* await program.call("mint", ...);
* }
*
* ...
* }
* ```
*
* @public
*/
export function useProgram<TProgramType extends ProgramType>(
address: RequiredParam<string>,
type?: TProgramType,
@@ -28,6 +28,9 @@ export function programAccountTypeQuery(
};
}
/**
* @internal
*/
export function useProgramAccountType(address: RequiredParam<string>) {
const sdk = useSDK();
return useQuery(programAccountTypeQuery(sdk, address));
@@ -18,6 +18,9 @@ export function programMetadataQuery(
};
}
/**
* @internal
*/
export function useProgramMetadata(
program: RequiredParam<UseProgramResult["data"]>,
) {
@@ -5,6 +5,28 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Token } from "@thirdweb-dev/sdk/solana";
import invariant from "tiny-invariant";
/**
* Mint tokens on your token program
* @param program - The program instance of the program to mint on
*
* @example
* ```jsx
* import { useProgram, useMintToken } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: mint, isLoading, error } = useMintToken(program);
*
* return (
* <button onClick={() => mint({ to: "{{wallet_address}}", amount: 1 })}>
* Mint
* </button>
* )
* }
* ```
*
* @public
*/
export function useMintToken(program: RequiredParam<Token>) {
const queryClient = useQueryClient();
return useMutation(
@@ -23,6 +23,27 @@ export function tokenBalanceQuery(
};
}
/**
* Get the token balance of a specified wallet
* @param program - The token program to get the balance on
* @param walletAddress - The address of the wallet to get the balance of
*
* @example
* ```jsx
* import { useProgram, useTokenBalance } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { data: balance, isLoading } = useTokenBalance(program, "{{wallet_address}}");
*
* return (
* <p>{balance}</p>
* )
* }
* ```
*
* @public
*/
export function useTokenBalance(
program: RequiredParam<Token>,
walletAddress: RequiredParam<string>,
@@ -16,6 +16,26 @@ export function tokenSupplyQuery(program: RequiredParam<Token>) {
};
}
/**
* Get the total circulating supply of a token
* @param program - The token program to get the supply of
*
* @example
* ```jsx
* import { useProgram, useMintToken } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { data: totalSupply, isLoading } = useTokenSupply(program);
*
* return (
* <p>{totalSupply}</p>
* )
* }
* ```
*
* @public
*/
export function useTokenSupply(program: RequiredParam<Token>) {
return useQuery(tokenSupplyQuery(program));
}
@@ -9,6 +9,28 @@ export type TransferTokenMutationParams = {
receiverAddress: string;
};
/**
* Transfer tokens from the connected wallet to another wallet
* @param program - The program instance of the program to mint on
*
* @example
* ```jsx
* import { useProgram, useTransferToken } from "@thirdweb-dev/react/solana";
*
* export default function Component() {
* const program = useProgram("{{program_address}}");
* const { mutateAsync: transfer, isLoading, error } = useTransferToken(program);
*
* return (
* <button onClick={() => transfer({ to: "{{wallet_address}}", amount: 1 })}>
* Transfer
* </button>
* )
* }
* ```
*
* @public
*/
export function useTransferToken(program: RequiredParam<Token>) {
const queryClient = useQueryClient();
return useMutation(
+2 -1
View File
@@ -15,9 +15,10 @@ export * from "./hooks/nft/useNFTs";
export * from "./hooks/nft/useMintNFT";
export * from "./hooks/nft/useNFT";
export * from "./hooks/nft/useTransferNFT";
export * from "./hooks/nft/useBurnNFT";
// NFT Drop
export * from "./hooks/nft/drop/useLazyMintNFT";
export * from "./hooks/nft/drop/useLazyMint";
export * from "./hooks/nft/drop/useClaimedSupply";
export * from "./hooks/nft/drop/useUnclaimedSupply";
export * from "./hooks/nft/drop/useClaimNFT";
+36 -16
View File
@@ -3,13 +3,14 @@ import {
QueryClientProviderWithDefault,
} from "../../core/providers/query-client";
import { ComponentWithChildren } from "../../core/types/component";
import { RequiredParam } from "../../core/types/shared";
import type { WalletContextState } from "@solana/wallet-adapter-react";
import type { Connection } from "@solana/web3.js";
import { ThirdwebSDK } from "@thirdweb-dev/sdk/solana";
import { Network, ThirdwebSDK } from "@thirdweb-dev/sdk/solana";
import { createContext, useContext, useEffect, useState } from "react";
import invariant from "tiny-invariant";
interface ThirdwebSDKProviderProps extends QueryClientProviderProps {
connection: Connection;
network: RequiredParam<Network>;
wallet?: WalletContextState;
}
@@ -18,17 +19,13 @@ interface ThirdwebSDKProviderProps extends QueryClientProviderProps {
* Requires to be wrapped with a ConnectionProvider and a WalletProvider from @solana/wallet-adapter-react.
* @example
* ```tsx
* import {
* useConnection,
* useWallet,
* } from "@solana/wallet-adapter-react";
* import { useWallet } from "@solana/wallet-adapter-react";
* import { ThirdwebProvider } from "@thirdweb-dev/react/solana";
*
* const ThirdwebApp = () => {
* const { connection } = useConnection();
* const wallet = useWallet();
* return (
* <ThirdwebSDKProvider connection={connection} wallet={wallet}>
* <ThirdwebSDKProvider network={"devnet"} wallet={wallet}>
* <YourApp />
* </ThirdwebSDKProvider>
* )};
@@ -36,16 +33,18 @@ interface ThirdwebSDKProviderProps extends QueryClientProviderProps {
*/
export const ThirdwebSDKProvider: ComponentWithChildren<
ThirdwebSDKProviderProps
> = ({ children, connection, queryClient, wallet }) => {
> = ({ children, network, queryClient, wallet }) => {
const [sdk, setSDK] = useState<ThirdwebSDK | null>(null);
useEffect(() => {
if (connection) {
setSDK(new ThirdwebSDK(connection));
if (network) {
const _sdk = ThirdwebSDK.fromNetwork(network);
(_sdk as any)._network = network;
setSDK(_sdk);
} else {
setSDK(null);
}
}, [connection]);
}, [network]);
useEffect(() => {
if (sdk) {
@@ -59,15 +58,36 @@ export const ThirdwebSDKProvider: ComponentWithChildren<
return (
<QueryClientProviderWithDefault queryClient={queryClient}>
<ThirdwebSDKContext.Provider value={sdk}>
<ThirdwebSDKContext.Provider
value={{ sdk, desiredNetwork: network || "unknown", _inProvider: true }}
>
{children}
</ThirdwebSDKContext.Provider>
</QueryClientProviderWithDefault>
);
};
const ThirdwebSDKContext = createContext<ThirdwebSDK | null>(null);
interface ThirdwebSDKContext {
sdk: ThirdwebSDK | null;
desiredNetwork: string;
_inProvider?: true;
}
const ThirdwebSDKContext = createContext<ThirdwebSDKContext>({
sdk: null,
desiredNetwork: "unknown",
});
export function useSDK() {
return useContext(ThirdwebSDKContext);
const ctxValue = useContext(ThirdwebSDKContext);
invariant(
ctxValue._inProvider,
"useSDK must be used within a ThirdwebSDKProvider",
);
if (
!ctxValue.sdk ||
(ctxValue.sdk as any)._network !== ctxValue.desiredNetwork
) {
return null;
}
return ctxValue.sdk;
}
+11 -11
View File
@@ -2,7 +2,6 @@ import { ThirdwebSDKProvider } from "./base";
import type { WalletAdapter } from "@solana/wallet-adapter-base";
import {
ConnectionProvider,
useConnection,
useWallet,
WalletProvider,
} from "@solana/wallet-adapter-react";
@@ -11,7 +10,7 @@ import { getUrlForNetwork, Network } from "@thirdweb-dev/sdk/solana";
import { PropsWithChildren } from "react";
interface ThirdwebProviderProps {
endpoint: Network;
network: Network;
wallets?: WalletAdapter[];
autoConnect?: boolean;
}
@@ -27,7 +26,7 @@ const DEFAULT_WALLETS = [new PhantomWalletAdapter()];
*
* const App = () => {
* return (
* <ThirdwebProvider endpoint="devnet">
* <ThirdwebProvider network="devnet">
* <YourApp />
* </ThirdwebProvider>
* )};
@@ -36,12 +35,14 @@ const DEFAULT_WALLETS = [new PhantomWalletAdapter()];
*/
export const ThirdwebProvider: React.FC<
PropsWithChildren<ThirdwebProviderProps>
> = ({ endpoint, wallets = DEFAULT_WALLETS, autoConnect = true, children }) => {
const clusterUrl = getUrlForNetwork(endpoint);
> = ({ network, wallets = DEFAULT_WALLETS, autoConnect = true, children }) => {
const clusterUrl = getUrlForNetwork(network);
return (
<ConnectionProvider endpoint={clusterUrl}>
<WalletProvider wallets={wallets} autoConnect={autoConnect}>
<ThirdwebWrapperProvider>{children}</ThirdwebWrapperProvider>
<ThirdwebWrapperProvider network={network}>
{children}
</ThirdwebWrapperProvider>
</WalletProvider>
</ConnectionProvider>
);
@@ -50,13 +51,12 @@ export const ThirdwebProvider: React.FC<
/**
* @internal
*/
export const ThirdwebWrapperProvider: React.FC<PropsWithChildren> = ({
children,
}) => {
const { connection } = useConnection();
export const ThirdwebWrapperProvider: React.FC<
PropsWithChildren<{ network?: Network }>
> = ({ network, children }) => {
const wallet = useWallet();
return (
<ThirdwebSDKProvider connection={connection} wallet={wallet}>
<ThirdwebSDKProvider network={network} wallet={wallet}>
{children}
</ThirdwebSDKProvider>
);
+45
View File
@@ -1,5 +1,50 @@
# @thirdweb-dev/sdk
## 3.2.1
## 3.2.0
### Minor Changes
- [#247](https://github.com/thirdweb-dev/js/pull/247) [`caf9795`](https://github.com/thirdweb-dev/js/commit/caf979537b5acb1610f182c94afa5d95c208ec3f) Thanks [@furqanrydhan](https://github.com/furqanrydhan)! - AppURI detection now enabled
- [#238](https://github.com/thirdweb-dev/js/pull/238) [`6647f70`](https://github.com/thirdweb-dev/js/commit/6647f707bdd050725264a8a74220c11912f68e57) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Unify NFT return types for EVM and Solana
#### NFT Types are now consistent accross EVM (both ERC721 and ERC1155) and Solana
This is a transparent upgrade, except for one type change for ERC1155 NFTs
- nft.id is now of type `string` instead of `BigNumber`
- edition.supply is now of type `number` instead of `BigNumber`
This should make it much easer to deal with in applications, instead of having to manipulate BigNumber objects.
Most people convert BigNumber to strings, which is compatible with this upgrade.
### Patch Changes
- [#257](https://github.com/thirdweb-dev/js/pull/257) [`ba6f450`](https://github.com/thirdweb-dev/js/commit/ba6f45027a6ec11aebb4a1918ab2ba4f88894ede) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - fix permission enumerable export
- [#261](https://github.com/thirdweb-dev/js/pull/261) [`c8261b7`](https://github.com/thirdweb-dev/js/commit/c8261b74b5828ac66ea3a6d7636aa57e40ea1a14) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - align behavior of `useContract()` and `getContract()` across react & sdk to both allow passing optional second params of contract types or ABIs
- [#250](https://github.com/thirdweb-dev/js/pull/250) [`20745f8`](https://github.com/thirdweb-dev/js/commit/20745f8cd603235eb5039e61a39c0959c5860bca) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add check if abi exists on extractFunctionsFromAbi function
- [#252](https://github.com/thirdweb-dev/js/pull/252) [`2ea3f00`](https://github.com/thirdweb-dev/js/commit/2ea3f00c41b5e70d9bb634cd86790890520fc4d6) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Expose a way to update collection settings, pass in upload options to lazyMint
- [#234](https://github.com/thirdweb-dev/js/pull/234) [`9412d41`](https://github.com/thirdweb-dev/js/commit/9412d416832c87ab2c858cb120c6c5de03459c50) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - [SOL] Add burn NFT functionality + misc API refinement
- [#256](https://github.com/thirdweb-dev/js/pull/256) [`d677e9d`](https://github.com/thirdweb-dev/js/commit/d677e9d6341252013762882d25408ea8f93791e5) Thanks [@jnsdls](https://github.com/jnsdls)! - [EVM] - make PermissiosEnumerable feature available
- [#240](https://github.com/thirdweb-dev/js/pull/240) [`e662408`](https://github.com/thirdweb-dev/js/commit/e662408e1936983485936609552f80a56cbed082) Thanks [@jnsdls](https://github.com/jnsdls)! - unify program metadata return type
- [#249](https://github.com/thirdweb-dev/js/pull/249) [`e4b10bc`](https://github.com/thirdweb-dev/js/commit/e4b10bc5bd12178cba8856b60255732123cb7ae5) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - [SOL] Update NFT Drop API for claim conditions + multiple fixes
- [#262](https://github.com/thirdweb-dev/js/pull/262) [`028cb78`](https://github.com/thirdweb-dev/js/commit/028cb781252b0050943b14cfdf38132c18753a4b) Thanks [@jnsdls](https://github.com/jnsdls)! - [CORE] - fix HexColor schema
- [#245](https://github.com/thirdweb-dev/js/pull/245) [`1972f3e`](https://github.com/thirdweb-dev/js/commit/1972f3ec0d511fbc17642b2a30852a177092a09e) Thanks [@jnsdls](https://github.com/jnsdls)! - [SOL] - allow burning of drop'd NFTs
- [#236](https://github.com/thirdweb-dev/js/pull/236) [`cac373b`](https://github.com/thirdweb-dev/js/commit/cac373b010ce3be3615a36671b66815a27785061) Thanks [@jnsdls](https://github.com/jnsdls)! - [SOL] - attempt to resolve network more agressively
## 3.1.2
### Patch Changes
+5 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/sdk",
"version": "3.1.2",
"version": "3.2.1",
"description": "The main thirdweb SDK.",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
"license": "Apache-2.0",
@@ -50,8 +50,8 @@
"fix": "eslint src/ --fix",
"clean": "rm -rf dist/",
"generate-docs": "yarn generate-docs:evm && yarn generate-docs:solana && yarn generate-snippets",
"generate-docs:evm": "api-extractor run --local --config ./config/api-extractor-evm.json && api-documenter markdown -i ./temp -o ./docs/evm && mv ./temp ./temp-evm",
"generate-docs:solana": "api-extractor run --local --config ./config/api-extractor-solana.json && api-documenter markdown -i ./temp -o ./docs/solana && mv ./temp ./temp-solana",
"generate-docs:evm": "api-extractor run --local --config ./config/api-extractor-evm.json && api-documenter markdown -i ./temp -o ./docs/evm && rm -rf ./temp-evm && mv ./temp ./temp-evm",
"generate-docs:solana": "api-extractor run --local --config ./config/api-extractor-solana.json && api-documenter markdown -i ./temp -o ./docs/solana && rm -rf ./temp-solana && mv ./temp ./temp-solana",
"generate-snippets": "node ./scripts/generate-snippets.mjs && node ./scripts/generate-feature-snippets-evm.mjs",
"build": "tsc && preconstruct build",
"test:evm:all": "SWC_NODE_PROJECT=./tsconfig.test.json mocha --config './test/evm/.mocharc.json' --timeout 30000 --parallel './test/evm/**/*.test.ts'",
@@ -65,7 +65,6 @@
"push": "yalc push"
},
"devDependencies": {
"@esbuild-plugins/node-modules-polyfill": "^0.1.4",
"@gmrchk/cli-testing-library": "^0.1.2",
"@metaplex-foundation/amman": "^0.10.0",
"@metaplex-foundation/amman-client": "^0.2.1",
@@ -76,10 +75,8 @@
"@preconstruct/cli": "^2.2.1",
"@swc-node/register": "^1.5.1",
"@swc/core": "^1.2.177",
"@typechain/ethers-v5": "10.0.0",
"@types/chai": "^4.3.3",
"@types/deep-equal-in-any-order": "^1.0.1",
"@types/expect": "^24.3.0",
"@types/mocha": "^9.1.1",
"@types/node": "^18.0.0",
"@types/uuid": "^8.3.3",
@@ -100,7 +97,6 @@
"mocha": "^10.0.0",
"node-stdlib-browser": "^1.2.0",
"prettier": "^2.7.1",
"typechain": "^8.1.0",
"typescript": "^4.7.4"
},
"peerDependencies": {
@@ -129,7 +125,7 @@
"zod": "^3.11.6"
},
"resolutions": {
"bn.js": "5.2.1",
"bn.js": "^5.2.1",
"nanoid": "^3.1.31",
"typescript": "^4.6.2",
"@microsoft/tsdoc": "^0.14.1"
@@ -138,4 +134,4 @@
"url": "https://github.com/thirdweb-dev/js/issues"
},
"author": "thirdweb eng <[email protected]>"
}
}
@@ -1,44 +1,27 @@
import { OptionalPropertiesInput } from "./properties";
import {
BigNumberSchema,
BigNumberTransformSchema,
FileOrBufferOrStringSchema,
HexColor,
} from "../../shared";
import { OptionalPropertiesInput } from "./properties";
} from "./shared";
import { z } from "zod";
/**
* @internal
*/
export const CommonTokenInput = z
export const CommonNFTInput = z
.object({
name: z.union([z.string(), z.number()]).optional(),
description: z.string().nullable().optional(),
image: FileOrBufferOrStringSchema.nullable().optional(),
external_url: FileOrBufferOrStringSchema.nullable().optional(),
animation_url: FileOrBufferOrStringSchema.optional(),
background_color: HexColor.optional(),
properties: OptionalPropertiesInput,
attributes: OptionalPropertiesInput,
})
.catchall(z.union([BigNumberTransformSchema, z.unknown()]));
/**
* @internal
*/
export const CommonTokenOutput = CommonTokenInput.extend({
id: BigNumberSchema,
uri: z.string(),
image: z.string().nullable().optional(),
external_url: z.string().nullable().optional(),
});
/**
* @internal
*/
export const CommonNFTInput = CommonTokenInput.extend({
animation_url: FileOrBufferOrStringSchema.optional(),
background_color: HexColor.optional(),
properties: OptionalPropertiesInput,
attributes: OptionalPropertiesInput,
});
/**
* @internal
*/
@@ -47,7 +30,11 @@ export const NFTInputOrUriSchema = z.union([CommonNFTInput, z.string()]);
/**
* @internal
*/
export const CommonNFTOutput = CommonTokenOutput.extend({
export const CommonNFTOutput = CommonNFTInput.extend({
id: z.string(),
uri: z.string(),
image: z.string().nullable().optional(),
external_url: z.string().nullable().optional(),
animation_url: z.string().nullable().optional(),
});
@@ -66,4 +53,10 @@ export type NFTMetadata = z.output<typeof CommonNFTOutput>;
/**
* @public
*/
export type NFTMetadataOwner = { metadata: NFTMetadata; owner: string };
export type NFT = {
metadata: NFTMetadata;
owner: string;
type: "ERC1155" | "ERC721" | "metaplex";
supply: number;
quantityOwned?: number;
};
@@ -0,0 +1,13 @@
import { BigNumberTransformSchema } from "./shared";
import { z } from "zod";
const PropertiesInput = z
.object({})
.catchall(z.union([BigNumberTransformSchema, z.unknown()]));
/**
* @internal
*/
export const OptionalPropertiesInput = z
.union([z.array(PropertiesInput), PropertiesInput])
.optional();
+113
View File
@@ -0,0 +1,113 @@
import BN from "bn.js";
import { BigNumber } from "ethers";
import { z } from "zod";
const isBrowser = () => typeof window !== "undefined";
const FileOrBufferUnionSchema = isBrowser()
? (z.instanceof(File) as z.ZodType<InstanceType<typeof File>>)
: (z.instanceof(Buffer) as z.ZodTypeAny); // @fixme, this is a hack to make browser happy for now
/**
* @internal
*/
export const FileOrBufferSchema = z.union([
FileOrBufferUnionSchema,
z.object({
data: z.union([FileOrBufferUnionSchema, z.string()]),
name: z.string(),
}),
]);
/**
* @internal
*/
export const FileOrBufferOrStringSchema = z.union([
FileOrBufferSchema,
z.string(),
]);
export const MAX_BPS = 10000;
export const BytesLikeSchema = z.union([z.array(z.number()), z.string()]);
export const BigNumberSchema = z
.union([
z.string(),
z.number(),
z.bigint(),
z.custom<BigNumber>((data) => {
return BigNumber.isBigNumber(data);
}),
z.custom<BN>((data) => {
return BN.isBN(data);
}),
])
.transform((arg) => {
let str = BN.isBN(arg)
? new BN(arg).toString()
: BigNumber.from(arg).toString();
return BigNumber.from(str);
});
export const BigNumberishSchema = BigNumberSchema.transform((arg) =>
arg.toString(),
);
export const BigNumberTransformSchema = z
.union([
z.bigint(),
z.custom<BigNumber>((data) => {
return BigNumber.isBigNumber(data);
}),
z.custom<BN>((data) => {
return BN.isBN(data);
}),
])
.transform((arg) => {
if (BN.isBN(arg)) {
return new BN(arg).toString();
}
return BigNumber.from(arg).toString();
});
export const BasisPointsSchema = z
.number()
.max(MAX_BPS, "Cannot exeed 100%")
.min(0, "Cannot be below 0%");
export const PercentSchema = z
.number()
.max(100, "Cannot exeed 100%")
.min(0, "Cannot be below 0%");
export const HexColor = z.union([
z.string().regex(/^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, "Invalid hex color"),
z
.string()
.regex(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, "Invalid hex color")
.transform((val) => val.replace("#", "")),
z.string().length(0),
]);
export const AmountSchema = z
.union([
z.string().regex(/^([0-9]+\.?[0-9]*|\.[0-9]+)$/, "Invalid amount"),
z.number().min(0, "Amount cannot be negative"),
])
.transform((arg) => (typeof arg === "number" ? arg.toString() : arg));
export const RawDateSchema = z.date().transform((i) => {
return BigNumber.from(Math.floor(i.getTime() / 1000));
});
/**
* Default to now
*/
export const StartDateSchema = RawDateSchema.default(new Date(0));
/**
* Default to 10 years from now
*/
export const EndDateSchema = RawDateSchema.default(
new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 10),
);
+42
View File
@@ -0,0 +1,42 @@
import { FileOrBufferOrStringSchema } from "./shared";
import { z } from "zod";
/**
* @internal
*/
export const CommonTokenInputSchema = z.object({
name: z.string(),
symbol: z.string(),
decimals: z.number(),
description: z.string().optional(),
image: FileOrBufferOrStringSchema.optional(),
external_link: z.string().url().optional(),
});
/**
* @internal
*/
export const CurrencyValueSchema = z.object({
value: z.string(),
displayValue: z.string(),
});
/**
* Currency value and display value
* @public
*/
export type CurrencyValue = z.input<typeof CurrencyValueSchema>;
/**
* @internal
*/
export const CommonTokenOutputSchema = CommonTokenInputSchema.extend({
image: z.string().optional(),
supply: CurrencyValueSchema,
}).catchall(z.unknown());
/**
* Metadata for a token
* @public
*/
export type TokenMetadata = z.output<typeof CommonTokenOutputSchema>;
@@ -146,7 +146,7 @@ export function extractFunctionsFromAbi(
abi: z.input<typeof AbiSchema>,
metadata?: Record<string, any>,
): AbiFunction[] {
const functions = abi.filter((el) => el.type === "function");
const functions = (abi || []).filter((el) => el.type === "function");
const parsed: AbiFunction[] = [];
for (const f of functions) {
+6 -6
View File
@@ -1,14 +1,14 @@
import {
InterfaceId_IERC1155,
InterfaceId_IERC721,
} from "../constants/contract";
import {
CommonNFTInput,
CommonNFTOutput,
NFTMetadata,
NFTMetadataInput,
NFTMetadataOrUri,
} from "../schema/tokens/common";
} from "../../core/schema/nft";
import {
InterfaceId_IERC1155,
InterfaceId_IERC721,
} from "../constants/contract";
import { NotFoundError } from "./error";
import type {
IERC1155Metadata,
@@ -67,7 +67,7 @@ export async function fetchTokenMetadata(
}
return CommonNFTOutput.parse({
id: BigNumber.from(tokenId),
id: BigNumber.from(tokenId).toString(),
uri: tokenUri,
...jsonMetadata,
});
@@ -35,9 +35,11 @@ import {
FEATURE_METADATA,
FEATURE_OWNER,
FEATURE_PERMISSIONS,
FEATURE_PERMISSIONS_ENUMERABLE,
FEATURE_PLATFORM_FEE,
FEATURE_PRIMARY_SALE,
FEATURE_ROYALTY,
FEATURE_APPURI,
} from "./thirdweb-features";
/**
@@ -75,7 +77,9 @@ export type Feature =
| typeof FEATURE_PLATFORM_FEE
| typeof FEATURE_PRIMARY_SALE
| typeof FEATURE_PERMISSIONS
| typeof FEATURE_PERMISSIONS_ENUMERABLE
| typeof FEATURE_METADATA
| typeof FEATURE_APPURI
| typeof FEATURE_OWNER;
/**
@@ -102,5 +106,6 @@ export const SUPPORTED_FEATURES: Record<string, Feature> = {
[FEATURE_PRIMARY_SALE.name]: FEATURE_PRIMARY_SALE,
[FEATURE_PERMISSIONS.name]: FEATURE_PERMISSIONS,
[FEATURE_METADATA.name]: FEATURE_METADATA,
[FEATURE_APPURI.name]: FEATURE_APPURI,
[FEATURE_OWNER.name]: FEATURE_OWNER,
};
@@ -1,5 +1,7 @@
import IAppURI from "@thirdweb-dev/contracts-js/dist/abis/IAppURI.json";
import IContractMetadataAbi from "@thirdweb-dev/contracts-js/dist/abis/IContractMetadata.json";
import IPermissionsAbi from "@thirdweb-dev/contracts-js/dist/abis/IPermissions.json";
import IPermissionsEnumerableAbi from "@thirdweb-dev/contracts-js/dist/abis/IPermissionsEnumerable.json";
import IThirdwebPlatformFeeAbi from "@thirdweb-dev/contracts-js/dist/abis/IPlatformFee.json";
import IThirdwebPrimarySaleAbi from "@thirdweb-dev/contracts-js/dist/abis/IPrimarySale.json";
import IThirdwebRoyaltyAbi from "@thirdweb-dev/contracts-js/dist/abis/IRoyalty.json";
@@ -38,17 +40,30 @@ export const FEATURE_PLATFORM_FEE = {
features: {},
} as const;
export const FEATURE_PERMISSIONS = {
name: "Permissions",
export const FEATURE_PERMISSIONS_ENUMERABLE = {
name: "PermissionsEnumerable",
namespace: "roles",
docLinks: {
sdk: "sdk.contractroles",
contracts: "PermissionsEnumerable",
},
abis: [IPermissionsAbi],
abis: [IPermissionsEnumerableAbi],
features: {},
} as const;
export const FEATURE_PERMISSIONS = {
name: "Permissions",
namespace: "roles",
docLinks: {
sdk: "sdk.contractroles",
contracts: "Permissions",
},
abis: [IPermissionsAbi],
features: {
[FEATURE_PERMISSIONS_ENUMERABLE.name]: FEATURE_PERMISSIONS_ENUMERABLE,
},
} as const;
export const FEATURE_METADATA = {
name: "ContractMetadata",
namespace: "metadata",
@@ -60,6 +75,17 @@ export const FEATURE_METADATA = {
features: {},
} as const;
export const FEATURE_APPURI = {
name: "AppURI",
namespace: "appURI",
docLinks: {
sdk: "sdk.appURI",
contracts: "AppURI",
},
abis: [IAppURI],
features: {},
} as const;
export const FEATURE_OWNER = {
name: "Ownable",
namespace: "owner",
@@ -1,3 +1,4 @@
import { NFT, NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import { getRoleHash } from "../../common";
import { TransactionTask } from "../../core/classes/TransactionTask";
import { ContractEncoder } from "../../core/classes/contract-encoder";
@@ -21,10 +22,8 @@ import {
TransactionResultWithId,
} from "../../core/types";
import { PaperCheckout } from "../../integrations/paper-xyz";
import { EditionMetadata, EditionMetadataOwner } from "../../schema";
import { DropErc1155ContractSchema } from "../../schema/contracts/drop-erc1155";
import { SDKOptions } from "../../schema/sdk-options";
import { NFTMetadata, NFTMetadataOrUri } from "../../schema/tokens/common";
import { QueryAllParams, UploadProgressEvent } from "../../types";
import type { DropERC1155 } from "@thirdweb-dev/contracts-js";
import type ABI from "@thirdweb-dev/contracts-js/dist/abis/DropERC1155.json";
@@ -193,9 +192,7 @@ export class EditionDrop extends StandardErc1155<DropERC1155> {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<EditionMetadata[]> {
public async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
return this.erc1155.getAll(queryParams);
}
@@ -213,9 +210,7 @@ export class EditionDrop extends StandardErc1155<DropERC1155> {
*
* @returns The NFT metadata for all NFTs in the contract.
*/
public async getOwned(
walletAddress?: string,
): Promise<EditionMetadataOwner[]> {
public async getOwned(walletAddress?: string): Promise<NFT[]> {
return this.erc1155.getOwned(walletAddress);
}
@@ -1,3 +1,4 @@
import { NFT } from "../../../core/schema/nft";
import { getRoleHash } from "../../common";
import { ContractEncoder } from "../../core/classes/contract-encoder";
import { ContractEvents } from "../../core/classes/contract-events";
@@ -20,11 +21,7 @@ import {
} from "../../core/types";
import { TokenErc1155ContractSchema } from "../../schema/contracts/token-erc1155";
import { SDKOptions } from "../../schema/sdk-options";
import {
EditionMetadata,
EditionMetadataOrUri,
EditionMetadataOwner,
} from "../../schema/tokens/edition";
import { EditionMetadataOrUri } from "../../schema/tokens/edition";
import { QueryAllParams } from "../../types";
import type { TokenERC1155 } from "@thirdweb-dev/contracts-js";
import type ABI from "@thirdweb-dev/contracts-js/dist/abis/TokenERC1155.json";
@@ -168,9 +165,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<EditionMetadata[]> {
public async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
return this.erc1155.getAll(queryParams);
}
@@ -188,9 +183,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
*
* @returns The NFT metadata for all NFTs in the contract.
*/
public async getOwned(
walletAddress?: string,
): Promise<EditionMetadataOwner[]> {
public async getOwned(walletAddress?: string): Promise<NFT[]> {
return this.erc1155.getOwned(walletAddress);
}
@@ -225,7 +218,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
*/
public async mint(
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return this.erc1155.mint(metadataWithSupply);
}
@@ -260,7 +253,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
public async mintTo(
to: string,
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return this.erc1155.mintTo(to, metadataWithSupply);
}
@@ -273,7 +266,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
public async mintAdditionalSupply(
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return this.erc1155.mintAdditionalSupply(tokenId, additionalSupply);
}
@@ -288,7 +281,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
to: string,
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return this.erc1155.mintAdditionalSupplyTo(to, tokenId, additionalSupply);
}
@@ -299,7 +292,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
*/
public async mintBatch(
metadatas: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc1155.mintBatch(metadatas);
}
@@ -339,7 +332,7 @@ export class Edition extends StandardErc1155<TokenERC1155> {
public async mintBatchTo(
to: string,
metadataWithSupply: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc1155.mintBatchTo(to, metadataWithSupply);
}
@@ -1,3 +1,4 @@
import { NFT, NFTMetadataOrUri } from "../../../core/schema/nft";
import {
fetchCurrencyMetadata,
hasERC20Allowance,
@@ -19,7 +20,7 @@ import {
TransactionResult,
TransactionResultWithId,
} from "../../core/types";
import { NFTMetadataOrUri, NFTMetadataOwner, SDKOptions } from "../../schema";
import { SDKOptions } from "../../schema";
import { MultiwrapContractSchema } from "../../schema/contracts/multiwrap";
import {
ERC1155Wrappable,
@@ -233,7 +234,7 @@ export class Multiwrap extends StandardErc721<MultiwrapContract> {
contents: TokensToWrap,
wrappedTokenMetadata: NFTMetadataOrUri,
recipientAddress?: string,
): Promise<TransactionResultWithId<NFTMetadataOwner>> {
): Promise<TransactionResultWithId<NFT>> {
const uri = await uploadOrExtractURI(wrappedTokenMetadata, this.storage);
const recipient = recipientAddress
@@ -1,3 +1,4 @@
import { NFT, NFTMetadataOrUri } from "../../../core/schema/nft";
import { getRoleHash } from "../../common";
import { ContractEncoder } from "../../core/classes/contract-encoder";
import { ContractEvents } from "../../core/classes/contract-events";
@@ -18,7 +19,6 @@ import type {
TransactionResult,
TransactionResultWithId,
} from "../../core/types";
import { NFTMetadataOrUri, NFTMetadataOwner } from "../../schema";
import { TokenErc721ContractSchema } from "../../schema/contracts/token-erc721";
import { SDKOptions } from "../../schema/sdk-options";
import type { TokenERC721 } from "@thirdweb-dev/contracts-js";
@@ -193,7 +193,7 @@ export class NFTCollection extends StandardErc721<TokenERC721> {
*/
public async mint(
metadata: NFTMetadataOrUri,
): Promise<TransactionResultWithId<NFTMetadataOwner>> {
): Promise<TransactionResultWithId<NFT>> {
return this.erc721.mint(metadata);
}
@@ -223,7 +223,7 @@ export class NFTCollection extends StandardErc721<TokenERC721> {
public async mintTo(
walletAddress: string,
metadata: NFTMetadataOrUri,
): Promise<TransactionResultWithId<NFTMetadataOwner>> {
): Promise<TransactionResultWithId<NFT>> {
return this.erc721.mintTo(walletAddress, metadata);
}
@@ -253,7 +253,7 @@ export class NFTCollection extends StandardErc721<TokenERC721> {
*/
public async mintBatch(
metadata: NFTMetadataOrUri[],
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc721.mintBatch(metadata);
}
@@ -287,7 +287,7 @@ export class NFTCollection extends StandardErc721<TokenERC721> {
public async mintBatchTo(
walletAddress: string,
metadata: NFTMetadataOrUri[],
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc721.mintBatchTo(walletAddress, metadata);
}
@@ -1,3 +1,4 @@
import { NFT, NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import { getRoleHash } from "../../common";
import { prepareClaim } from "../../common/claim-conditions";
import { uploadOrExtractURIs } from "../../common/nft";
@@ -26,11 +27,6 @@ import {
import { PaperCheckout } from "../../integrations/paper-xyz";
import { DropErc721ContractSchema } from "../../schema/contracts/drop-erc721";
import { SDKOptions } from "../../schema/sdk-options";
import {
NFTMetadata,
NFTMetadataOrUri,
NFTMetadataOwner,
} from "../../schema/tokens/common";
import { ClaimVerification } from "../../types";
import {
DEFAULT_QUERY_ALL_COUNT,
@@ -250,9 +246,7 @@ export class NFTDrop extends StandardErc721<DropERC721> {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata and their ownersfor all NFTs queried.
*/
public async getAllClaimed(
queryParams?: QueryAllParams,
): Promise<NFTMetadataOwner[]> {
public async getAllClaimed(queryParams?: QueryAllParams): Promise<NFT[]> {
const start = BigNumber.from(queryParams?.start || 0).toNumber();
const count = BigNumber.from(
queryParams?.count || DEFAULT_QUERY_ALL_COUNT,
@@ -475,7 +469,7 @@ export class NFTDrop extends StandardErc721<DropERC721> {
destinationAddress: string,
quantity: BigNumberish,
checkERC20Allowance = true,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc721.claimTo(destinationAddress, quantity, {
checkERC20Allowance,
});
@@ -491,7 +485,7 @@ export class NFTDrop extends StandardErc721<DropERC721> {
public async claim(
quantity: BigNumberish,
checkERC20Allowance = true,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.claimTo(
await this.contractWrapper.getSignerAddress(),
quantity,
@@ -529,7 +523,7 @@ export class NFTDrop extends StandardErc721<DropERC721> {
* @param tokenId - the tokenId of the NFT to retrieve
* @returns The NFT metadata
*/
public async get(tokenId: BigNumberish): Promise<NFTMetadataOwner> {
public async get(tokenId: BigNumberish): Promise<NFT> {
return this.erc721.get(tokenId);
}
@@ -1,3 +1,4 @@
import { NFT } from "../../../core/schema/nft";
import {
fetchCurrencyMetadata,
hasERC20Allowance,
@@ -21,7 +22,6 @@ import {
NetworkOrSignerOrProvider,
TransactionResultWithId,
} from "../../core/types";
import { EditionMetadata, EditionMetadataOwner } from "../../schema";
import { PackContractSchema } from "../../schema/contracts/packs";
import { SDKOptions } from "../../schema/sdk-options";
import {
@@ -160,7 +160,7 @@ export class Pack extends StandardErc1155<PackContract> {
* console.log(packs;
* ```
*/
public async get(tokenId: BigNumberish): Promise<EditionMetadata> {
public async get(tokenId: BigNumberish): Promise<NFT> {
return this.erc1155.get(tokenId);
}
@@ -179,9 +179,7 @@ export class Pack extends StandardErc1155<PackContract> {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The pack metadata for all packs queried.
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<EditionMetadata[]> {
public async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
return this.erc1155.getAll(queryParams);
}
@@ -199,9 +197,7 @@ export class Pack extends StandardErc1155<PackContract> {
*
* @returns The pack metadata for all the owned packs in the contract.
*/
public async getOwned(
walletAddress?: string,
): Promise<EditionMetadataOwner[]> {
public async getOwned(walletAddress?: string): Promise<NFT[]> {
return this.erc1155.getOwned(walletAddress);
}
@@ -477,7 +473,7 @@ export class Pack extends StandardErc1155<PackContract> {
public async createTo(
to: string,
metadataWithRewards: PackMetadataInput,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
const uri = await uploadOrExtractURI(
metadataWithRewards.packMetadata,
this.storage,
@@ -1,3 +1,4 @@
import { NFT, NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import { getRoleHash } from "../../common";
import { FEATURE_NFT_REVEALABLE } from "../../constants/erc721-features";
import { TransactionTask } from "../../core/classes/TransactionTask";
@@ -25,11 +26,6 @@ import {
import { PaperCheckout } from "../../integrations/paper-xyz";
import { DropErc721ContractSchema } from "../../schema/contracts/drop-erc721";
import { SDKOptions } from "../../schema/sdk-options";
import {
NFTMetadata,
NFTMetadataOrUri,
NFTMetadataOwner,
} from "../../schema/tokens/common";
import { ClaimOptions, UploadProgressEvent } from "../../types";
import {
DEFAULT_QUERY_ALL_COUNT,
@@ -264,9 +260,7 @@ export class SignatureDrop extends StandardErc721<SignatureDropContract> {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata and their ownersfor all NFTs queried.
*/
public async getAllClaimed(
queryParams?: QueryAllParams,
): Promise<NFTMetadataOwner[]> {
public async getAllClaimed(queryParams?: QueryAllParams): Promise<NFT[]> {
const start = BigNumber.from(queryParams?.start || 0).toNumber();
const count = BigNumber.from(
queryParams?.count || DEFAULT_QUERY_ALL_COUNT,
@@ -450,7 +444,7 @@ export class SignatureDrop extends StandardErc721<SignatureDropContract> {
destinationAddress: string,
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc721.claimTo(destinationAddress, quantity, options);
}
@@ -464,7 +458,7 @@ export class SignatureDrop extends StandardErc721<SignatureDropContract> {
public async claim(
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.erc721.claim(quantity, options);
}
@@ -3,6 +3,7 @@ import { FEATURE_TOKEN } from "../constants/erc20-features";
import { FEATURE_NFT } from "../constants/erc721-features";
import { FEATURE_EDITION } from "../constants/erc1155-features";
import {
FEATURE_APPURI,
FEATURE_OWNER,
FEATURE_PERMISSIONS,
FEATURE_PLATFORM_FEE,
@@ -14,6 +15,7 @@ import {
ContractOwner,
NetworkOrSignerOrProvider,
} from "../core";
import { ContractAppURI } from "../core/classes/contract-appuri";
import { ContractEvents } from "../core/classes/contract-events";
import { ContractInterceptor } from "../core/classes/contract-interceptor";
import { ContractMetadata } from "../core/classes/contract-metadata";
@@ -37,6 +39,7 @@ import type {
IPrimarySale,
IRoyalty,
Ownable,
AppURI,
} from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BaseContract, CallOverrides, ContractInterface } from "ethers";
@@ -117,6 +120,13 @@ export class SmartContract<TContract extends BaseContract = BaseContract>
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.
*/
@@ -273,6 +283,12 @@ export class SmartContract<TContract extends BaseContract = BaseContract>
return undefined;
}
private detectAppURI() {
if (detectContractFeature<AppURI>(this.contractWrapper, "AppURI")) {
return new ContractAppURI(this.contractWrapper);
}
return undefined;
}
private detectOwnable() {
if (detectContractFeature<Ownable>(this.contractWrapper, "Ownable")) {
return new ContractOwner(this.contractWrapper);
@@ -0,0 +1,49 @@
import { FEATURE_APPURI } from "../../constants/thirdweb-features";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResult } from "../types";
import { ContractWrapper } from "./contract-wrapper";
import type { AppURI } from "@thirdweb-dev/contracts-js";
/**
* Have an official Application URI for this contract.
* @remarks Configure an official Application URI for this contract.
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}");
* const appURI = await contract.appuri.get();
* appURI = "ipfs://some_ipfs_hash";
*
* await contract.appuri.set(appURI)
* ```
* @public
*/
export class ContractAppURI<TContract extends AppURI>
implements DetectableFeature
{
featureName = FEATURE_APPURI.name;
private contractWrapper;
constructor(contractWrapper: ContractWrapper<TContract>) {
this.contractWrapper = contractWrapper;
}
/**
* Get the appURI for the contract
* @returns the appURI object
*/
public async get() {
return await this.contractWrapper.readContract.appURI();
}
/**
* Set the appURI for the contract
* @param appURI - the uri to set (typically an IPFS hash)
*/
public async set(appURI: string): Promise<TransactionResult> {
return {
receipt: await this.contractWrapper.sendTransaction("setAppURI", [
appURI,
]),
};
}
}
@@ -626,16 +626,8 @@ export class ContractDeployer extends RPCConnectionHandler {
constructorParamValues,
);
if (isDeployableViaProxy) {
// deploy a proxy directly
return await this.deployProxy(
implementationAddress,
compilerMetadata.abi,
factoryDeploymentData.implementationInitializerFunction,
paramValues,
);
} else if (isDeployableViaFactory) {
// deploy via a factory
if (isDeployableViaFactory) {
// deploy via a factory (prioritise factory)
invariant(
factoryDeploymentData.factoryAddresses,
"isDeployableViaFactory is true so factoryAddresses is required",
@@ -652,6 +644,14 @@ export class ContractDeployer extends RPCConnectionHandler {
factoryDeploymentData.implementationInitializerFunction,
paramValues,
);
} else if (isDeployableViaProxy) {
// deploy a proxy directly
return await this.deployProxy(
implementationAddress,
compilerMetadata.abi,
factoryDeploymentData.implementationInitializerFunction,
paramValues,
);
}
}
@@ -1,14 +1,14 @@
import {
CommonNFTInput,
NFTMetadata,
NFTMetadataInput,
} from "../../../core/schema/nft";
import { hasFunction } from "../../common";
import {
fetchTokenMetadataForContract,
getBaseUriFromBatch,
} from "../../common/nft";
import { FeatureName } from "../../constants/contract-features";
import {
CommonNFTInput,
NFTMetadata,
NFTMetadataInput,
} from "../../schema/tokens/common";
import { BatchToReveal } from "../../types/delayed-reveal";
import {
BaseDelayedRevealERC1155,
@@ -1,6 +1,7 @@
import { NFT } from "../../../core/schema/nft";
import { uploadOrExtractURIs } from "../../common/nft";
import { FEATURE_EDITION_BATCH_MINTABLE } from "../../constants/erc1155-features";
import { EditionMetadata, EditionMetadataOrUri } from "../../schema";
import { EditionMetadataOrUri } from "../../schema";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResultWithId } from "../types";
import { ContractWrapper } from "./contract-wrapper";
@@ -72,7 +73,7 @@ export class Erc1155BatchMintable implements DetectableFeature {
public async to(
to: string,
metadataWithSupply: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
const metadatas = metadataWithSupply.map((a) => a.metadata);
const supplies = metadataWithSupply.map((a) => a.supply);
const uris = await uploadOrExtractURIs(metadatas, this.storage);
@@ -1,5 +1,5 @@
import { NFT } from "../../../core/schema/nft";
import { FEATURE_EDITION_ENUMERABLE } from "../../constants/erc1155-features";
import { EditionMetadata, EditionMetadataOwner } from "../../schema";
import { DEFAULT_QUERY_ALL_COUNT, QueryAllParams } from "../../types";
import { BaseERC1155 } from "../../types/eips";
import { DetectableFeature } from "../interfaces/DetectableFeature";
@@ -45,7 +45,7 @@ export class Erc1155Enumerable implements DetectableFeature {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async all(queryParams?: QueryAllParams): Promise<EditionMetadata[]> {
public async all(queryParams?: QueryAllParams): Promise<NFT[]> {
const start = BigNumber.from(queryParams?.start || 0).toNumber();
const count = BigNumber.from(
queryParams?.count || DEFAULT_QUERY_ALL_COUNT,
@@ -96,7 +96,7 @@ export class Erc1155Enumerable implements DetectableFeature {
*
* @returns The NFT metadata for all NFTs in the contract.
*/
public async owned(walletAddress?: string): Promise<EditionMetadataOwner[]> {
public async owned(walletAddress?: string): Promise<NFT[]> {
const address =
walletAddress || (await this.contractWrapper.getSignerAddress());
const maxId = await this.contractWrapper.readContract.nextTokenIdToMint();
@@ -119,7 +119,7 @@ export class Erc1155Enumerable implements DetectableFeature {
return {
...editionMetadata,
owner: address,
quantityOwned: b.balance,
quantityOwned: b.balance.toNumber(),
};
}),
);
@@ -1,3 +1,4 @@
import { NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import {
detectContractFeature,
hasFunction,
@@ -7,7 +8,6 @@ import {
FEATURE_EDITION_LAZY_MINTABLE,
FEATURE_EDITION_REVEALABLE,
} from "../../constants/erc1155-features";
import { NFTMetadata, NFTMetadataOrUri } from "../../schema/tokens/common";
import {
BaseClaimConditionERC1155,
BaseDelayedRevealERC1155,
@@ -1,7 +1,8 @@
import { NFT } from "../../../core/schema/nft";
import { detectContractFeature } from "../../common";
import { uploadOrExtractURI } from "../../common/nft";
import { FEATURE_EDITION_MINTABLE } from "../../constants/erc1155-features";
import { EditionMetadata, EditionMetadataOrUri } from "../../schema";
import { EditionMetadataOrUri } from "../../schema";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResultWithId } from "../types";
import { ContractWrapper } from "./contract-wrapper";
@@ -75,7 +76,7 @@ export class Erc1155Mintable implements DetectableFeature {
public async to(
to: string,
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
const uri = await uploadOrExtractURI(
metadataWithSupply.metadata,
this.storage,
@@ -122,7 +123,7 @@ export class Erc1155Mintable implements DetectableFeature {
to: string,
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
const metadata = await this.erc1155.getTokenMetadata(tokenId);
const receipt = await this.contractWrapper.sendTransaction("mintTo", [
to,
@@ -1,4 +1,4 @@
import { EditionMetadata } from "../../schema/tokens/edition";
import { NFT } from "../../../core/schema/nft";
import { AirdropInput } from "../../types/airdrop/airdrop";
import { BaseERC1155, BaseSignatureMintERC1155 } from "../../types/eips";
import { UpdateableNetwork } from "../interfaces/contract";
@@ -58,7 +58,7 @@ export class StandardErc1155<
* @param tokenId - the tokenId of the NFT to retrieve
* @returns The NFT metadata
*/
public async get(tokenId: BigNumberish): Promise<EditionMetadata> {
public async get(tokenId: BigNumberish): Promise<NFT> {
return this.erc1155.get(tokenId);
}
+17 -24
View File
@@ -1,3 +1,4 @@
import { NFT, NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import {
assertEnabled,
detectContractFeature,
@@ -19,13 +20,7 @@ import {
FEATURE_EDITION_CLAIMABLE,
} from "../../constants/erc1155-features";
import { AirdropInputSchema } from "../../schema/contracts/common/airdrop";
import { NFTMetadata, NFTMetadataOrUri } from "../../schema/tokens/common";
import {
EditionMetadata,
EditionMetadataOrUri,
EditionMetadataOutputSchema,
EditionMetadataOwner,
} from "../../schema/tokens/edition";
import { EditionMetadataOrUri } from "../../schema/tokens/edition";
import { ClaimOptions, QueryAllParams, UploadProgressEvent } from "../../types";
import { AirdropInput } from "../../types/airdrop/airdrop";
import {
@@ -55,7 +50,7 @@ import type {
TokenERC1155,
} from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, BytesLike } from "ethers";
import { BigNumber, BigNumberish, BytesLike, ethers } from "ethers";
/**
* Standard ERC1155 NFT functions
@@ -117,17 +112,19 @@ export class Erc1155<
* @returns The NFT metadata
* @twfeature ERC1155
*/
public async get(tokenId: BigNumberish): Promise<EditionMetadata> {
public async get(tokenId: BigNumberish): Promise<NFT> {
const [supply, metadata] = await Promise.all([
this.contractWrapper.readContract
.totalSupply(tokenId)
.catch(() => BigNumber.from(0)),
this.getTokenMetadata(tokenId),
]);
return EditionMetadataOutputSchema.parse({
supply,
return {
owner: ethers.constants.AddressZero,
metadata,
});
type: "ERC1155",
supply: supply.toNumber(),
};
}
/**
@@ -328,9 +325,7 @@ export class Erc1155<
* @returns The NFT metadata for all NFTs queried.
* @twfeature ERC1155Enumerable
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<EditionMetadata[]> {
public async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
return assertEnabled(this.query, FEATURE_EDITION_ENUMERABLE).all(
queryParams,
);
@@ -378,9 +373,7 @@ export class Erc1155<
* @returns The NFT metadata for all NFTs in the contract.
* @twfeature ERC1155Enumerable
*/
public async getOwned(
walletAddress?: string,
): Promise<EditionMetadataOwner[]> {
public async getOwned(walletAddress?: string): Promise<NFT[]> {
return assertEnabled(this.query, FEATURE_EDITION_ENUMERABLE).owned(
walletAddress,
);
@@ -419,7 +412,7 @@ export class Erc1155<
*/
public async mint(
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return this.mintTo(
await this.contractWrapper.getSignerAddress(),
metadataWithSupply,
@@ -458,7 +451,7 @@ export class Erc1155<
public async mintTo(
receiver: string,
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return assertEnabled(this.mintable, FEATURE_EDITION_MINTABLE).to(
receiver,
metadataWithSupply,
@@ -482,7 +475,7 @@ export class Erc1155<
public async mintAdditionalSupply(
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return assertEnabled(
this.mintable,
FEATURE_EDITION_MINTABLE,
@@ -504,7 +497,7 @@ export class Erc1155<
receiver: string,
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
): Promise<TransactionResultWithId<NFT>> {
return assertEnabled(
this.mintable,
FEATURE_EDITION_MINTABLE,
@@ -546,7 +539,7 @@ export class Erc1155<
*/
public async mintBatch(
metadataWithSupply: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return this.mintBatchTo(
await this.contractWrapper.getSignerAddress(),
metadataWithSupply,
@@ -590,7 +583,7 @@ export class Erc1155<
public async mintBatchTo(
receiver: string,
metadataWithSupply: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
return assertEnabled(
this.mintable?.batch,
FEATURE_EDITION_BATCH_MINTABLE,
@@ -1,6 +1,6 @@
import { NFT, NFTMetadataOrUri } from "../../../core/schema/nft";
import { uploadOrExtractURIs } from "../../common/nft";
import { FEATURE_NFT_BATCH_MINTABLE } from "../../constants/erc721-features";
import { NFTMetadataOrUri, NFTMetadataOwner } from "../../schema";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResultWithId } from "../types";
import { ContractWrapper } from "./contract-wrapper";
@@ -65,7 +65,7 @@ export class Erc721BatchMintable implements DetectableFeature {
public async to(
to: string,
metadatas: NFTMetadataOrUri[],
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
const uris = await uploadOrExtractURIs(metadatas, this.storage);
const encoded = uris.map((uri) =>
this.contractWrapper.readContract.interface.encodeFunctionData("mintTo", [
@@ -1,6 +1,6 @@
import { NFT } from "../../../core/schema/nft";
import { hasFunction } from "../../common";
import { FEATURE_NFT_CLAIMABLE_WITH_CONDITIONS } from "../../constants/erc721-features";
import { NFTMetadataOwner } from "../../schema";
import { CustomContractSchema } from "../../schema/contracts/custom";
import { ClaimOptions, ClaimVerification } from "../../types";
import { BaseClaimConditionERC721 } from "../../types/eips";
@@ -131,7 +131,7 @@ export class Erc721ClaimableWithConditions implements DetectableFeature {
destinationAddress: string,
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
const task = await this.getClaimTransaction(
destinationAddress,
quantity,
@@ -144,7 +144,7 @@ export class Erc721ClaimableWithConditions implements DetectableFeature {
);
const startingIndex: BigNumber = event[0].args.startTokenId;
const endingIndex = startingIndex.add(quantity);
const results: TransactionResultWithId<NFTMetadataOwner>[] = [];
const results: TransactionResultWithId<NFT>[] = [];
for (let id = startingIndex; id.lt(endingIndex); id = id.add(1)) {
results.push({
id,
@@ -1,6 +1,6 @@
import { NFT } from "../../../core/schema/nft";
import { calculateClaimCost } from "../../common/claim-conditions";
import { FEATURE_NFT_CLAIMABLE } from "../../constants/erc721-features";
import { NFTMetadataOwner } from "../../schema";
import { ClaimOptions } from "../../types";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResultWithId } from "../types";
@@ -90,7 +90,7 @@ export class Erc721Claimable implements DetectableFeature {
destinationAddress: string,
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
const task = await this.getClaimTransaction(
destinationAddress,
quantity,
@@ -103,7 +103,7 @@ export class Erc721Claimable implements DetectableFeature {
);
const startingIndex: BigNumber = event[0].args.startTokenId;
const endingIndex = startingIndex.add(quantity);
const results: TransactionResultWithId<NFTMetadataOwner>[] = [];
const results: TransactionResultWithId<NFT>[] = [];
for (let id = startingIndex; id.lt(endingIndex); id = id.add(1)) {
results.push({
id,
@@ -1,5 +1,5 @@
import { NFT } from "../../../core/schema/nft";
import { FEATURE_NFT_ENUMERABLE } from "../../constants/erc721-features";
import { NFTMetadataOwner } from "../../schema";
import { BaseERC721 } from "../../types/eips";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { ContractWrapper } from "./contract-wrapper";
@@ -45,7 +45,7 @@ export class Erc721Enumerable implements DetectableFeature {
* @param walletAddress - the wallet address to query, defaults to the connected wallet
* @returns The NFT metadata for all NFTs in the contract.
*/
public async all(walletAddress?: string): Promise<NFTMetadataOwner[]> {
public async all(walletAddress?: string): Promise<NFT[]> {
const tokenIds = await this.tokenIds(walletAddress);
return await Promise.all(
tokenIds.map((tokenId) => this.erc721.get(tokenId.toString())),
@@ -1,3 +1,4 @@
import { NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import {
detectContractFeature,
hasFunction,
@@ -7,7 +8,6 @@ import {
FEATURE_NFT_LAZY_MINTABLE,
FEATURE_NFT_REVEALABLE,
} from "../../constants/erc721-features";
import { NFTMetadata, NFTMetadataOrUri } from "../../schema";
import { UploadProgressEvent } from "../../types";
import {
BaseClaimConditionERC721,
@@ -1,7 +1,7 @@
import { NFT, NFTMetadataOrUri } from "../../../core/schema/nft";
import { detectContractFeature } from "../../common";
import { uploadOrExtractURI } from "../../common/nft";
import { FEATURE_NFT_MINTABLE } from "../../constants/erc721-features";
import { NFTMetadataOrUri, NFTMetadataOwner } from "../../schema";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResultWithId } from "../types";
import { ContractWrapper } from "./contract-wrapper";
@@ -66,7 +66,7 @@ export class Erc721Mintable implements DetectableFeature {
public async to(
to: string,
metadata: NFTMetadataOrUri,
): Promise<TransactionResultWithId<NFTMetadataOwner>> {
): Promise<TransactionResultWithId<NFT>> {
const uri = await uploadOrExtractURI(metadata, this.storage);
const receipt = await this.contractWrapper.sendTransaction("mintTo", [
to,
@@ -1,4 +1,4 @@
import { NFTMetadataOwner } from "../../schema/tokens/common";
import { NFT } from "../../../core/schema/nft";
import { QueryAllParams } from "../../types";
import { BaseERC721 } from "../../types/eips";
import { UpdateableNetwork } from "../interfaces/contract";
@@ -63,9 +63,7 @@ export class StandardErc721<
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<NFTMetadataOwner[]> {
public async getAll(queryParams?: QueryAllParams): Promise<NFT[]> {
return this.erc721.getAll(queryParams);
}
@@ -84,7 +82,7 @@ export class StandardErc721<
* @param walletAddress - the wallet address to query, defaults to the connected wallet
* @returns The NFT metadata for all NFTs in the contract.
*/
public async getOwned(walletAddress?: string): Promise<NFTMetadataOwner[]> {
public async getOwned(walletAddress?: string): Promise<NFT[]> {
return this.erc721.getOwned(walletAddress);
}
@@ -114,7 +112,7 @@ export class StandardErc721<
* @param tokenId - the tokenId of the NFT to retrieve
* @returns The NFT metadata
*/
public async get(tokenId: BigNumberish): Promise<NFTMetadataOwner> {
public async get(tokenId: BigNumberish): Promise<NFT> {
return this.erc721.get(tokenId);
}
@@ -1,6 +1,6 @@
import { NFT } from "../../../core/schema/nft";
import { detectContractFeature } from "../../common";
import { FEATURE_NFT_SUPPLY } from "../../constants/erc721-features";
import { NFTMetadataOwner } from "../../schema";
import { DEFAULT_QUERY_ALL_COUNT, QueryAllParams } from "../../types";
import { BaseERC721 } from "../../types/eips";
import { DetectableFeature } from "../interfaces/DetectableFeature";
@@ -53,7 +53,7 @@ export class Erc721Supply implements DetectableFeature {
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async all(queryParams?: QueryAllParams): Promise<NFTMetadataOwner[]> {
public async all(queryParams?: QueryAllParams): Promise<NFT[]> {
const start = BigNumber.from(queryParams?.start || 0).toNumber();
const count = BigNumber.from(
queryParams?.count || DEFAULT_QUERY_ALL_COUNT,
+4 -8
View File
@@ -1,3 +1,4 @@
import { NFT, NFTMetadata, NFTMetadataOrUri } from "../../../core/schema/nft";
import {
assertEnabled,
detectContractFeature,
@@ -18,11 +19,6 @@ import {
FEATURE_NFT_SIGNATURE_MINTABLE,
FEATURE_NFT_SUPPLY,
} from "../../constants/erc721-features";
import {
NFTMetadata,
NFTMetadataOrUri,
NFTMetadataOwner,
} from "../../schema/tokens/common";
import { BaseDropERC721, BaseERC721 } from "../../types/eips";
import {
ClaimOptions,
@@ -118,12 +114,12 @@ export class Erc721<
* @returns The NFT metadata
* @twfeature ERC721
*/
public async get(tokenId: BigNumberish): Promise<NFTMetadataOwner> {
public async get(tokenId: BigNumberish): Promise<NFT> {
const [owner, metadata] = await Promise.all([
this.ownerOf(tokenId).catch(() => constants.AddressZero),
this.getTokenMetadata(tokenId),
]);
return { owner, metadata };
return { owner, metadata, type: "ERC721", supply: 1 };
}
/**
@@ -578,7 +574,7 @@ export class Erc721<
destinationAddress: string,
quantity: BigNumberish,
options?: ClaimOptions,
): Promise<TransactionResultWithId<NFTMetadataOwner>[]> {
): Promise<TransactionResultWithId<NFT>[]> {
const claimWithConditions = this.lazyMintable?.claimWithConditions;
const claim = this.lazyMintable?.claim;
if (claimWithConditions) {
+214 -154
View File
@@ -6,20 +6,8 @@ import {
NATIVE_TOKEN_ADDRESS,
} from "../constants";
import {
EditionDropInitializer,
EditionInitializer,
getContractTypeForRemoteName,
MarketplaceInitializer,
MultiwrapInitializer,
NFTCollectionInitializer,
NFTDropInitializer,
PackInitializer,
PREBUILT_CONTRACTS_MAP,
SignatureDropInitializer,
SplitInitializer,
TokenDropInitializer,
TokenInitializer,
VoteInitializer,
} from "../contracts";
import { SmartContract } from "../contracts/smart-contract";
import { SDKOptions } from "../schema/sdk-options";
@@ -166,184 +154,290 @@ export class ThirdwebSDK extends RPCConnectionHandler {
}
/**
* Get an instance of a Drop contract
* Get an instance of a NFT Drop contract
* @param contractAddress - the address of the deployed contract
* @returns the contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const dropContract = await sdk.getDropContract("0x1234...");
* + const dropContract = await sdk.getContract("0x1234...", "nft-drop");
* ```
*/
public async getNFTDrop(contractAddress: string) {
return await this.getBuiltInContract(
contractAddress,
NFTDropInitializer.contractType,
);
return await this.getContract(contractAddress, "nft-drop");
}
/**
* Get an instance of a SignatureDrop contract
* Get an instance of a Signature Drop contract
* @param contractAddress - the address of the deployed contract
* @returns the contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const signatureDrop = await sdk.getSignatureDrop("0x1234...");
* + const signatureDrop = await sdk.getContract("0x1234...", "signature-drop");
* ```
*/
public async getSignatureDrop(contractAddress: string) {
return await this.getBuiltInContract(
contractAddress,
SignatureDropInitializer.contractType,
);
return await this.getContract(contractAddress, "signature-drop");
}
/**
* Get an instance of a NFT Collection contract
* @param address - the address of the deployed contract
* @returns the contract
* Get an instance of a NFT Collection Drop contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const signatureDrop = await sdk.getNFTCollection("0x1234...");
* + const signatureDrop = await sdk.getContract("0x1234...", "nft-collection");
* ```
*/
public async getNFTCollection(address: string) {
return await this.getBuiltInContract(
address,
NFTCollectionInitializer.contractType,
);
public async getNFTCollection(contractAddress: string) {
return await this.getContract(contractAddress, "nft-collection");
}
/**
* Get an instance of a Edition Drop contract
* @param address - the address of the deployed contract
* @returns the contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const editionDrop = await sdk.getEditionDrop("0x1234...");
* + const editionDrop = await sdk.getContract("0x1234...", "edition-drop");
* ```
*/
public async getEditionDrop(address: string) {
return await this.getBuiltInContract(
address,
EditionDropInitializer.contractType,
);
public async getEditionDrop(contractAddress: string) {
return await this.getContract(contractAddress, "edition-drop");
}
/**
* Get an instance of an Edition contract
* @param address - the address of the deployed contract
* @returns the contract
* Get an instance of a Edition contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const edition = await sdk.getEdition("0x1234...");
* + const edition = await sdk.getContract("0x1234...", "edition");
* ```
*/
public async getEdition(address: string) {
return await this.getBuiltInContract(
address,
EditionInitializer.contractType,
);
public async getEdition(contractAddress: string) {
return await this.getContract(contractAddress, "edition");
}
/**
* Get an instance of a Token Drop contract
* @param address - the address of the deployed contract
* @returns the contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const tokenDrop = await sdk.getTokenDrop("0x1234...");
* + const tokenDrop = await sdk.getContract("0x1234...", "token-drop");
* ```
*/
public async getTokenDrop(address: string) {
return await this.getBuiltInContract(
address,
TokenDropInitializer.contractType,
);
public async getTokenDrop(contractAddress: string) {
return await this.getContract(contractAddress, "token-drop");
}
/**
* Get an instance of a Token contract
* @param address - the address of the deployed contract
* @returns the contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const token = await sdk.getToken("0x1234...");
* + const token = await sdk.getContract("0x1234...", "token");
* ```
*/
public async getToken(address: string) {
return await this.getBuiltInContract(
address,
TokenInitializer.contractType,
);
public async getToken(contractAddress: string) {
return await this.getContract(contractAddress, "token");
}
/**
* Get an instance of a Vote contract
* @param address - the address of the deployed contract
* @returns the contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const vote = await sdk.getVote("0x1234...");
* + const vote = await sdk.getContract("0x1234...", "vote");
* ```
*/
public async getVote(address: string) {
return await this.getBuiltInContract(address, VoteInitializer.contractType);
public async getVote(contractAddress: string) {
return await this.getContract(contractAddress, "vote");
}
/**
* Get an instance of a Splits contract
* @param address - the address of the deployed contract
* @returns the contract
* Get an instance of a Split contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const split = await sdk.getSplit("0x1234...");
* + const split = await sdk.getContract("0x1234...", "split");
* ```
*/
public async getSplit(address: string) {
return await this.getBuiltInContract(
address,
SplitInitializer.contractType,
);
public async getSplit(contractAddress: string) {
return await this.getContract(contractAddress, "split");
}
/**
* Get an instance of a Marketplace contract
* @param address - the address of the deployed contract
* @returns the contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const marketplace = await sdk.getMarketplace("0x1234...");
* + const marketplace = await sdk.getContract("0x1234...", "marketplace");
* ```
*/
public async getMarketplace(address: string) {
return await this.getBuiltInContract(
address,
MarketplaceInitializer.contractType,
);
public async getMarketplace(contractAddress: string) {
return await this.getContract(contractAddress, "marketplace");
}
/**
* Get an instance of a Pack contract
* @param address - the address of the deployed contract
* @returns the contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const pack = await sdk.getPack("0x1234...");
* + const pack = await sdk.getContract("0x1234...", "pack");
* ```
*/
public async getPack(address: string) {
return await this.getBuiltInContract(address, PackInitializer.contractType);
public async getPack(contractAddress: string) {
return await this.getContract(contractAddress, "pack");
}
/**
* Get an instance of a Multiwrap contract
* @param address - the address of the deployed contract
* @returns the contract
* @beta
* Get an instance of a Pack contract
* @param contractAddress - the address of the deployed contract
* @deprecated
* This method is deprecated and will be removed in a future major version. You should use {@link getContract} instead.
* ```diff
* - const multiWrap = await sdk.getMultiwrap("0x1234...");
* + const multiWrap = await sdk.getContract("0x1234...", "multiwrap");
* ```
*/
public async getMultiwrap(address: string) {
return await this.getBuiltInContract(
address,
MultiwrapInitializer.contractType,
);
public async getMultiwrap(contractAddress: string) {
return await this.getContract(contractAddress, "multiwrap");
}
/**
*
* @internal
* @param address - the address of the contract to instantiate
* @param contractType - optional, the type of contract to instantiate
* @returns a promise that resolves with the contract instance
* Get an instance of a Custom ThirdwebContract
* @param address - the address of the deployed contract
* @returns the contract
* @public
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}");
* ```
*/
public async getBuiltInContract<
TContractType extends PrebuiltContractType = PrebuiltContractType,
>(
public async getContract(address: string): Promise<SmartContract>;
/**
* Get an instance of a Custom ThirdwebContract
* @param address - the address of the deployed contract
* @param contractType - the {@link ContractType} of the contract to load
* @returns the contract
* @public
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}", "nft-drop");
* ```
*/
public async getContract<TContractType extends ContractType>(
address: string,
contractType: TContractType,
): Promise<ContractForPrebuiltContractType<TContractType>> {
): Promise<
TContractType extends PrebuiltContractType
? ContractForPrebuiltContractType<TContractType>
: SmartContract
>;
/**
* Get an instance of a Custom ThirdwebContract
* @param address - the address of the deployed contract
* @param abi - the ABI ({@link ContractInterface}) of the contract to load
* @returns the contract
* @public
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}", ABI);
* ```
*/
public async getContract(
address: string,
abi: ContractInterface,
): Promise<SmartContract>;
public async getContract(
address: string,
contractTypeOrABI?: PrebuiltContractType | ContractInterface,
): Promise<ValidContractInstance> {
// if we have a contract in the cache we will return it
// we will do this **without** checking any contract type things for simplicity, this may have to change in the future?
if (this.contractCache.has(address)) {
return this.contractCache.get(
address,
) as ContractForPrebuiltContractType<TContractType>;
// we know this will be there since we check the has above
return this.contractCache.get(address) as ValidContractInstance;
}
//@ts-expect-error - this is just extra runtime safety
if (contractType === "custom") {
throw new Error(
"To get an instance of a custom contract, use getContract(address)",
let newContract: ValidContractInstance;
// if we don't have a contractType or ABI then we will have to resolve it regardless
// we also handle it being "custom" just in case...
if (!contractTypeOrABI || contractTypeOrABI === "custom") {
const resolvedContractType = await this.resolveContractType(address);
if (resolvedContractType === "custom") {
// if it's a custom contract we gotta fetch the compilet metadata
try {
const publisher = this.getPublisher();
const metadata = await publisher.fetchCompilerMetadataFromAddress(
address,
);
newContract = this.getContractFromAbi(address, metadata.abi);
} catch (e) {
throw new Error(`Error fetching ABI for this contract\n\n${e}`);
}
} else {
// otherwise if it's a prebuilt contract we can just use the contract type
const contractAbi = await PREBUILT_CONTRACTS_MAP[
resolvedContractType
].getAbi();
newContract = this.getContractFromAbi(address, contractAbi);
}
}
// if it's a builtin contract type we can just use the contract type to initialize the contract instance
else if (
typeof contractTypeOrABI === "string" &&
contractTypeOrABI in PREBUILT_CONTRACTS_MAP
) {
newContract = await PREBUILT_CONTRACTS_MAP[
contractTypeOrABI as keyof typeof PREBUILT_CONTRACTS_MAP
].initialize(
this.getSignerOrProvider(),
address,
this.storage,
this.options,
);
}
// otherwise it has to be an ABI
else {
newContract = this.getContractFromAbi(address, contractTypeOrABI);
}
//lazy import the contract from the map
const newContract = await PREBUILT_CONTRACTS_MAP[contractType].initialize(
this.getSignerOrProvider(),
address,
this.storageHandler,
this.options,
);
// set whatever we have on the cache
this.contractCache.set(address, newContract);
// return it
return newContract;
}
// return the new contract
return newContract as ContractForPrebuiltContractType<TContractType>;
/**
* @internal
* @deprecated use {@link getContract} directly instead
*/
public async getBuiltInContract<TContractType extends PrebuiltContractType>(
address: string,
contractType: TContractType,
): Promise<ContractForPrebuiltContractType<TContractType>> {
return (await this.getContract(address, contractType)) as Promise<
ContractForPrebuiltContractType<TContractType>
>;
}
/**
@@ -403,8 +497,7 @@ export class ThirdwebSDK extends RPCConnectionHandler {
);
}
} else {
metadata = (await this.getBuiltInContract(address, contractType))
.metadata;
metadata = (await this.getContract(address, contractType)).metadata;
}
return {
address,
@@ -445,39 +538,6 @@ export class ThirdwebSDK extends RPCConnectionHandler {
}
}
/**
* Get an instance of a Custom ThirdwebContract
* @param address - the address of the deployed contract
* @returns the contract
* @beta
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}");
* ```
*/
public async getContract(address: string) {
if (this.contractCache.has(address)) {
return this.contractCache.get(address) as SmartContract;
}
try {
// try built in contract first, eventually all our contracts will have bytecode metadata
const contractType = await this.resolveContractType(address);
invariant(contractType !== "custom", "custom contract type");
const contractAbi = await PREBUILT_CONTRACTS_MAP[contractType].getAbi();
return this.getContractFromAbi(address, contractAbi);
} catch (err) {
try {
const publisher = this.getPublisher();
const metadata = await publisher.fetchCompilerMetadataFromAddress(
address,
);
return this.getContractFromAbi(address, metadata.abi);
} catch (e) {
throw new Error(`Error fetching ABI for this contract\n\n${e}`);
}
}
}
/**
* Get an instance of a Custom contract from a json ABI
* @param address - the address of the deployed contract
+6 -1
View File
@@ -17,6 +17,11 @@ type Equals<A1, A2> = (<A>() => A extends A2 ? 1 : 0) extends <
// --- end utility types --- //
export type PrebuiltContractsMap = typeof PREBUILT_CONTRACTS_MAP;
export type PrebuiltContractsInstances = {
[K in keyof PrebuiltContractsMap]: Awaited<
ReturnType<typeof PREBUILT_CONTRACTS_MAP[K]["initialize"]>
>;
};
export type ContractsMap = typeof CONTRACTS_MAP;
export type PrebuiltContractType = keyof PrebuiltContractsMap;
@@ -36,7 +41,7 @@ export type DeploySchemaForPrebuiltContractType<
export type ContractForPrebuiltContractType<
TContractType extends PrebuiltContractType,
> = Awaited<ReturnType<PrebuiltContractsMap[TContractType]["initialize"]>>;
> = PrebuiltContractsInstances[TContractType];
export type NetworkOrSignerOrProvider =
| providers.Networkish
-6
View File
@@ -2,12 +2,6 @@
globalThis.global = globalThis;
export type { ContractType, NetworkOrSignerOrProvider } from "./core/types";
export type {
NFTMetadataInput,
NFTMetadataOwner,
NFTMetadata,
NFTMetadataOrUri,
} from "./schema/tokens/common";
export type { Role } from "./common/role";

Some files were not shown because too many files have changed in this diff Show More