Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bbc2e092b8 | ||
|
|
4c3c840d88 | ||
|
|
cf606665fc | ||
|
|
3871068aa6 | ||
|
|
d00ca7fd2a | ||
|
|
9ee3c21eac | ||
|
|
ed3afd418c | ||
|
|
b90fa2cc29 | ||
|
|
2ab517aa49 | ||
|
|
e46dd0254f | ||
|
|
1a5627f72d | ||
|
|
b808e942fd | ||
|
|
7fdb1715e4 | ||
|
|
ae2fcf7e00 | ||
|
|
94a8f7960a | ||
|
|
c410a1c18a | ||
|
|
81c46e2298 | ||
|
|
f369bffe5a | ||
|
|
fed1313a19 | ||
|
|
b7d4dee446 | ||
|
|
23db97cca5 | ||
|
|
0f54e99141 | ||
|
|
c701c388c6 | ||
|
|
328ef5dc9c | ||
|
|
07fbb799be | ||
|
|
699f31c20a |
@@ -1,5 +1,33 @@
|
||||
# @thirdweb-dev/auth
|
||||
|
||||
## 4.1.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`cf606665`](https://github.com/thirdweb-dev/js/commit/cf606665fcfdad7b08259350d39b60313278a8dc)]:
|
||||
- @thirdweb-dev/wallets@2.3.4
|
||||
|
||||
## 4.1.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`e46dd025`](https://github.com/thirdweb-dev/js/commit/e46dd0254f157c3c4d50fe3e4f44e2e24eaf34a8)]:
|
||||
- @thirdweb-dev/wallets@2.3.3
|
||||
|
||||
## 4.1.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c), [`81c46e22`](https://github.com/thirdweb-dev/js/commit/81c46e22984cdb5b33b2e6eb99a0ebf0e4fbdb33)]:
|
||||
- @thirdweb-dev/wallets@2.3.2
|
||||
|
||||
## 4.1.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies []:
|
||||
- @thirdweb-dev/wallets@2.3.1
|
||||
|
||||
## 4.1.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/auth",
|
||||
"version": "4.1.17",
|
||||
"version": "4.1.21",
|
||||
"main": "dist/thirdweb-dev-auth.cjs.js",
|
||||
"module": "dist/thirdweb-dev-auth.esm.js",
|
||||
"browser": {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# @thirdweb-dev/chains
|
||||
|
||||
## 0.1.62
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2084](https://github.com/thirdweb-dev/js/pull/2084) [`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c) Thanks [@MananTank](https://github.com/MananTank)! - JSDoc comments Improvements
|
||||
|
||||
## 0.1.61
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/chains",
|
||||
"version": "0.1.61",
|
||||
"version": "0.1.62",
|
||||
"main": "dist/thirdweb-dev-chains.cjs.js",
|
||||
"module": "dist/thirdweb-dev-chains.esm.js",
|
||||
"exports": {
|
||||
|
||||
@@ -83,7 +83,7 @@ export async function fetchChains(options?: {
|
||||
/**
|
||||
*
|
||||
* @param chainId - the chainId of the chain to resolve
|
||||
* @returns a Promise that resolves to the Chain object
|
||||
* @returns A Promise that resolves to the Chain object
|
||||
* @throws if the chainId is not found
|
||||
*/
|
||||
export async function getChainByChainIdAsync(chainId: number): Promise<Chain> {
|
||||
@@ -98,7 +98,7 @@ export async function getChainByChainIdAsync(chainId: number): Promise<Chain> {
|
||||
/**
|
||||
*
|
||||
* @param slug - the slug of the chain to resolve
|
||||
* @returns a Promise that resolves to the Chain object
|
||||
* @returns A Promise that resolves to the Chain object
|
||||
* @throws if the slug is not found
|
||||
*/
|
||||
export async function getChainBySlugAsync(slug: string): Promise<Chain> {
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
# thirdweb
|
||||
|
||||
## 0.13.29
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`cf606665`](https://github.com/thirdweb-dev/js/commit/cf606665fcfdad7b08259350d39b60313278a8dc)]:
|
||||
- @thirdweb-dev/wallets@2.3.4
|
||||
- @thirdweb-dev/sdk@4.0.25
|
||||
- @thirdweb-dev/auth@4.1.21
|
||||
|
||||
## 0.13.28
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`b808e942`](https://github.com/thirdweb-dev/js/commit/b808e942fdaa81b5de61dcb3f2083081cb99ea11), [`e46dd025`](https://github.com/thirdweb-dev/js/commit/e46dd0254f157c3c4d50fe3e4f44e2e24eaf34a8)]:
|
||||
- @thirdweb-dev/sdk@4.0.24
|
||||
- @thirdweb-dev/wallets@2.3.3
|
||||
- @thirdweb-dev/auth@4.1.20
|
||||
|
||||
## 0.13.27
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c), [`fed1313a`](https://github.com/thirdweb-dev/js/commit/fed1313a199011a9b52d7c5e11ad6e72fc969002), [`f369bffe`](https://github.com/thirdweb-dev/js/commit/f369bffe5a30e2e8a9df2ac62f24f93f96324186), [`81c46e22`](https://github.com/thirdweb-dev/js/commit/81c46e22984cdb5b33b2e6eb99a0ebf0e4fbdb33)]:
|
||||
- @thirdweb-dev/storage@2.0.8
|
||||
- @thirdweb-dev/wallets@2.3.2
|
||||
- @thirdweb-dev/chains@0.1.62
|
||||
- @thirdweb-dev/sdk@4.0.23
|
||||
- @thirdweb-dev/auth@4.1.19
|
||||
|
||||
## 0.13.26
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`c701c388`](https://github.com/thirdweb-dev/js/commit/c701c388c65a1e531b88991d8fd67d25f153992e)]:
|
||||
- @thirdweb-dev/sdk@4.0.22
|
||||
- @thirdweb-dev/wallets@2.3.1
|
||||
- @thirdweb-dev/auth@4.1.18
|
||||
|
||||
## 0.13.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "thirdweb",
|
||||
"main": "dist/cli/index.js",
|
||||
"version": "0.13.25",
|
||||
"version": "0.13.29",
|
||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"license": "Apache-2.0",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"presets": [
|
||||
"@babel/preset-typescript",
|
||||
["@babel/preset-env", { "targets": "defaults, not ie 11" }]
|
||||
],
|
||||
"plugins": [
|
||||
"@babel/plugin-transform-flow-strip-types",
|
||||
"@babel/plugin-transform-private-methods",
|
||||
"@babel/plugin-proposal-class-properties"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# folders
|
||||
dist/
|
||||
|
||||
# files
|
||||
@@ -0,0 +1,21 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ["thirdweb"],
|
||||
plugins: ["better-tree-shaking"],
|
||||
rules: {
|
||||
"better-tree-shaking/no-top-level-side-effects": "error",
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
paths: [
|
||||
{
|
||||
name: "eventemitter3",
|
||||
importNames: ["EventEmitter"],
|
||||
message:
|
||||
"Do not use named import for importing EventEmitter, Use default import instead.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
# @thirdweb-dev/payments
|
||||
|
||||
## 1.0.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2115](https://github.com/thirdweb-dev/js/pull/2115) [`d00ca7fd`](https://github.com/thirdweb-dev/js/commit/d00ca7fd2a0fa3e694bb37d1f486d3d4cf1ad79e) Thanks [@IDubuque](https://github.com/IDubuque)! - Update exports with new payments interface
|
||||
|
||||
## 1.0.0
|
||||
|
||||
### Major Changes
|
||||
|
||||
- [#1913](https://github.com/thirdweb-dev/js/pull/1913) [`ed3afd41`](https://github.com/thirdweb-dev/js/commit/ed3afd418cb6e0d711814a1c52afb302460751ba) Thanks [@IDubuque](https://github.com/IDubuque)! - The `@thirdweb-dev/payments` package is a continuation of the `@paperxyz/js-client-sdk`, aligning with the new branding and expanded capabilities under thirdweb. It inherits the core functionality of Paper's developer-first NFT checkout solution.
|
||||
|
||||
### Changed
|
||||
|
||||
- Rebranded package from `@paperxyz/js-client-sdk` to `@thirdweb-dev/payments`. Users of the old package should migrate to this new package name.
|
||||
- Changed PaperSdkError typename to PaymentsSdkError
|
||||
@@ -0,0 +1,14 @@
|
||||
<p align="center">
|
||||
<br />
|
||||
<a href="https://thirdweb.com"><img src="https://github.com/thirdweb-dev/js/blob/main/packages/sdk/logo.svg?raw=true" width="200" alt=""/></a>
|
||||
<br />
|
||||
</p>
|
||||
<h1 align="center">thirdweb Checkouts SDK</h1>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/@thirdweb-dev/payments"><img src="https://img.shields.io/npm/v/@thirdweb-dev/payments?color=red&label=npm&logo=npm" alt="npm version"/></a>
|
||||
<a href="https://github.com/thirdweb-dev/js/actions/workflows/build-test-lint.yml"><img alt="Build Status" src="https://github.com/thirdweb-dev/js/actions/workflows/build-test-lint.yml/badge.svg"/></a>
|
||||
<a href="https://discord.gg/thirdweb"><img alt="Join our Discord!" src="https://img.shields.io/discord/834227967404146718.svg?color=7289da&label=discord&logo=discord&style=flat"/></a>
|
||||
|
||||
</p>
|
||||
<p align="center"><strong>web3 Checkouts library to integrate any NFT checkout into your applications.</strong></p>
|
||||
<br />
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/payments",
|
||||
"version": "1.0.1",
|
||||
"main": "dist/thirdweb-dev-payments.cjs.js",
|
||||
"module": "dist/thirdweb-dev-payments.esm.js",
|
||||
"types": "dist/thirdweb-dev-payments.cjs.d.ts",
|
||||
"browser": {
|
||||
"./dist/thirdweb-dev-payments.esm.js": "./dist/thirdweb-dev-payments.browser.esm.js"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"module": {
|
||||
"browser": "./dist/thirdweb-dev-payments.browser.esm.js",
|
||||
"default": "./dist/thirdweb-dev-payments.esm.js"
|
||||
},
|
||||
"default": "./dist/thirdweb-dev-payments.cjs.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/payments",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/thirdweb-dev/js/issues"
|
||||
},
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"files": [
|
||||
"dist/"
|
||||
],
|
||||
"preconstruct": {
|
||||
"entrypoints": [
|
||||
"index.ts"
|
||||
],
|
||||
"exports": {
|
||||
"envConditions": [
|
||||
"browser"
|
||||
]
|
||||
}
|
||||
},
|
||||
"sideEffects": false,
|
||||
"dependencies": {
|
||||
"ethers": "^5.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@thirdweb-dev/tsconfig": "workspace:*",
|
||||
"eslint-config-thirdweb": "workspace:*",
|
||||
"typescript": "^5.1.6",
|
||||
"@preconstruct/cli": "2.7.0"
|
||||
},
|
||||
"scripts": {
|
||||
"format": "prettier --write 'src/**/*'",
|
||||
"lint": "eslint src/",
|
||||
"fix": "eslint src/ --fix",
|
||||
"clean": "rm -rf dist/",
|
||||
"build": "tsc && preconstruct build",
|
||||
"preconstruct:fix": "preconstruct fix",
|
||||
"push": "yalc push"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// UNCHANGED: MERGED FROM sdk-common-utilities/blockchain
|
||||
export const ChainToPublicRpc: Record<Chain, string> = {
|
||||
Ethereum: "https://ethereum.rpc.thirdweb.com",
|
||||
Goerli: "https://goerli.rpc.thirdweb.com",
|
||||
Mumbai: "https://mumbai.rpc.thirdweb.com",
|
||||
Polygon: "https://polygon.rpc.thirdweb.com",
|
||||
Avalanche: "https://avalanche.rpc.thirdweb.com",
|
||||
Optimism: "https://optimism.rpc.thirdweb.com",
|
||||
OptimismGoerli: "https://optimism-goerli.rpc.thirdweb.com",
|
||||
BSC: "https://binance.rpc.thirdweb.com",
|
||||
BSCTestnet: "https://binance-testnet.rpc.thirdweb.com",
|
||||
ArbitrumOne: "https://arbitrum.rpc.thirdweb.com",
|
||||
ArbitrumGoerli: "https://arbitrum-goerli.rpc.thirdweb.com",
|
||||
Fantom: "https://fantom.rpc.thirdweb.com",
|
||||
FantomTestnet: "https://fantom-testnet.rpc.thirdweb.com",
|
||||
Sepolia: "https://sepolia.rpc.thirdweb.com",
|
||||
AvalancheFuji: "https://avalanche-fuji.rpc.thirdweb.com",
|
||||
};
|
||||
|
||||
export const ChainIdToChain: Record<number, Chain> = {
|
||||
1: "Ethereum",
|
||||
5: "Goerli",
|
||||
80001: "Mumbai",
|
||||
137: "Polygon",
|
||||
43114: "Avalanche",
|
||||
10: "Optimism",
|
||||
420: "OptimismGoerli",
|
||||
56: "BSC",
|
||||
97: "BSCTestnet",
|
||||
42161: "ArbitrumOne",
|
||||
421613: "ArbitrumGoerli",
|
||||
250: "Fantom",
|
||||
4002: "FantomTestnet",
|
||||
11155111: "Sepolia",
|
||||
43113: "AvalancheFuji",
|
||||
};
|
||||
|
||||
// General Embedded wallet types
|
||||
export type Chain =
|
||||
| "Polygon"
|
||||
| "Mumbai"
|
||||
| "Goerli"
|
||||
| "Ethereum"
|
||||
| "Avalanche"
|
||||
| "Optimism"
|
||||
| "OptimismGoerli"
|
||||
| "BSC"
|
||||
| "BSCTestnet"
|
||||
| "ArbitrumOne"
|
||||
| "ArbitrumGoerli"
|
||||
| "Fantom"
|
||||
| "FantomTestnet"
|
||||
| "Sepolia"
|
||||
| "AvalancheFuji";
|
||||
|
||||
export type SupportedChainName = Chain | "Rinkeby";
|
||||
@@ -0,0 +1,12 @@
|
||||
// UNCHANGED: MERGED FROM sdk-common-utilities/iframeMessages
|
||||
export type MessageType<T> =
|
||||
| {
|
||||
eventType: string;
|
||||
success: true;
|
||||
data: T;
|
||||
}
|
||||
| {
|
||||
eventType: string;
|
||||
success: false;
|
||||
error: string;
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
// CHANGED: export merged sdk-common-utilities/constants & js-client-sdk/constants
|
||||
export * from "./settings";
|
||||
export * from "./blockchain";
|
||||
export * from "./style";
|
||||
@@ -0,0 +1,43 @@
|
||||
// UNCHANGED: MERGE BETWEEN sdk-common-utilities/settings and js-client-sdk/settings
|
||||
const isDev = (): boolean => {
|
||||
return !!(
|
||||
typeof window !== "undefined" &&
|
||||
window.localStorage.getItem("IS_PAPER_DEV") === "true"
|
||||
);
|
||||
};
|
||||
|
||||
const isOldPaperDomain = (): boolean =>
|
||||
typeof window !== "undefined" &&
|
||||
(window.location.hostname === "paper.xyz" ||
|
||||
window.location.hostname.endsWith(".paper.xyz"));
|
||||
|
||||
const isThirdwebDomain = (): boolean =>
|
||||
typeof window !== "undefined" &&
|
||||
(window.location.hostname === "thirdweb.com" ||
|
||||
window.location.hostname.endsWith(".thirdweb.com"));
|
||||
|
||||
export const getPaperOriginUrl = (): string => {
|
||||
if (isDev()) {
|
||||
return (
|
||||
window.localStorage.getItem("PAPER_DEV_URL") ?? "http://localhost:3000"
|
||||
);
|
||||
}
|
||||
|
||||
if (isOldPaperDomain()) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
if (isThirdwebDomain()) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
return "https://payments.thirdweb.com";
|
||||
};
|
||||
|
||||
// eslint-disable-next-line better-tree-shaking/no-top-level-side-effects
|
||||
export const PAPER_APP_URL = getPaperOriginUrl();
|
||||
|
||||
export const CHECKOUT_WITH_ETH_IFRAME_URL = "/sdk/2022-08-12/checkout-with-eth";
|
||||
export const CHECKOUT_WITH_CARD_IFRAME_URL =
|
||||
"/sdk/2022-08-12/checkout-with-card";
|
||||
export const CREATE_WALLET_IFRAME_URL = "/sdk/v2/verify-email";
|
||||
@@ -0,0 +1,25 @@
|
||||
// // UNCHANGED: MERGED FROM sdk-common-utilities/style
|
||||
export type StyleObject = Partial<CSSStyleDeclaration>;
|
||||
|
||||
export interface ICustomizationOptions {
|
||||
colorPrimary?: string;
|
||||
colorBackground?: string;
|
||||
colorText?: string;
|
||||
borderRadius?: number;
|
||||
fontFamily?: string;
|
||||
|
||||
inputBackgroundColor?: string;
|
||||
inputBorderColor?: string;
|
||||
}
|
||||
export type CustomizationOptionsType = {
|
||||
[key in keyof ICustomizationOptions]: string;
|
||||
};
|
||||
export type Locale = "en" | "fr" | "es" | "it" | "de" | "ja" | "ko" | "zh";
|
||||
|
||||
export const DEFAULT_BRAND_OPTIONS = {
|
||||
colorPrimary: "#cf3781",
|
||||
colorBackground: "#ffffff",
|
||||
colorText: "#1a202c",
|
||||
borderRadius: 12,
|
||||
fontFamily: "Open Sans",
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
// CHANGED: exports
|
||||
|
||||
// Customization options and base urls
|
||||
export * from "./constants";
|
||||
// Types
|
||||
export * from "./interfaces";
|
||||
// Components
|
||||
export * from "./lib";
|
||||
@@ -0,0 +1,67 @@
|
||||
// UNCHANGED
|
||||
|
||||
export interface ReviewResult {
|
||||
/**
|
||||
* A unique ID for this purchase.
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* The cardholder's full name provided by the buyer.
|
||||
*/
|
||||
cardholderName: string;
|
||||
}
|
||||
|
||||
export interface KycModal {
|
||||
iframeLink: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ICheckoutWithCardConfigs interface defines the configuration options for the checkoutWithCard component provided by Paper.
|
||||
* This component allows users to generate a card payment component for NFTs without needing any backend calls.
|
||||
*
|
||||
* The configuration options include:
|
||||
*
|
||||
* - `contractId`: The id of your contract (not the address) found in you seller dashboard.
|
||||
* - `walletAddress`: The wallet address to which the payment will be sent (AKA the receiving wallet).
|
||||
* - `email`: (Optional) Email address of the buyer.
|
||||
* - `quantity`: (Optional) The number of items to be purchased.
|
||||
* - `metadata`: (Optional) A record of additional information about the transaction.
|
||||
* - `mintMethod`: (Optional, Only required for Custom Contract Types) The contract function name, function args, and payment information which will be sent to your contract.
|
||||
* - `contractArgs`: (Optional) Depending on the contract type, this can defined additional args to call your contract with. See [Thirdweb/Reservoir docs](https://docs.withpaper.com/reference/thirdweb-contracts) for more details.
|
||||
* - `feeBearer`: (Optional) Who will bear the transaction fee, either 'BUYER' or 'SELLER'.
|
||||
* - `capturePaymentLater`: (Optional) If set to true, the payment is authorized but not captured immediately.
|
||||
* - `fiatCurrency`: (Optional) The type of fiat currency for the payment.
|
||||
* - `title`: (Optional) The title to be displayed on the Stripe receipt.
|
||||
* - `sendEmailOnTransferSucceeded`: (Optional) If set to true, an email is sent when the transfer succeeds.
|
||||
* - `postPurchaseMessageMarkdown`: (Optional) A post-purchase message in Markdown format.
|
||||
* - `postPurchaseButtonText`: (Optional) The text for the post-purchase button.
|
||||
* - `successCallbackUrl`: (Optional) The URL to be called back when the transaction is successful.
|
||||
*
|
||||
* Note: This interface is part of an open-source npm package. Please ensure you understand the implications of each field before using this interface.
|
||||
*/
|
||||
export interface ICheckoutWithCardConfigs {
|
||||
contractId: string;
|
||||
walletAddress: string;
|
||||
email?: string;
|
||||
quantity?: number;
|
||||
mintMethod?: {
|
||||
name: string;
|
||||
args: Record<string, any>;
|
||||
payment: { value: string; currency: string };
|
||||
};
|
||||
contractArgs?: Record<string, any>;
|
||||
|
||||
// payment customizations
|
||||
capturePaymentLater?: boolean;
|
||||
fiatCurrency?: string;
|
||||
|
||||
// stripe receipt
|
||||
title?: string;
|
||||
|
||||
// email
|
||||
sendEmailOnTransferSucceeded?: boolean;
|
||||
postPurchaseMessageMarkdown?: string;
|
||||
postPurchaseButtonText?: string;
|
||||
successCallbackUrl?: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// UNCHANGED
|
||||
|
||||
import type { StyleObject } from "../constants/style";
|
||||
|
||||
export interface ModalStyles {
|
||||
main: StyleObject;
|
||||
overlay: StyleObject;
|
||||
body: StyleObject;
|
||||
iframe: StyleObject;
|
||||
closeButton?: StyleObject;
|
||||
spinner: StyleObject;
|
||||
}
|
||||
|
||||
export interface ModalInterface {
|
||||
modalContainer?: HTMLElement;
|
||||
modalStyles?: Partial<ModalStyles>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// UNCHANGED
|
||||
|
||||
export type PaperUser = {
|
||||
/**
|
||||
* The user's email address.
|
||||
* This address is case-insensitive (i.e. different capitalizations map to the same wallet).
|
||||
*/
|
||||
emailAddress: string;
|
||||
|
||||
/**
|
||||
* The Paper Wallet address associated with this user's email address.
|
||||
*/
|
||||
walletAddress: string;
|
||||
|
||||
/**
|
||||
* The user's access code. Will only be set if [clientId] was provided. This can be used to query about the user details.
|
||||
*/
|
||||
accessCode?: string;
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
// CHANGED: Updated name to Payments
|
||||
|
||||
export type PaymentsSDKError = {
|
||||
/**
|
||||
* An enum representing the error encountered.
|
||||
* The value is a human-readable, English message describing the error.
|
||||
*/
|
||||
code: PaymentsSDKErrorCode | PayWithCryptoErrorCode;
|
||||
error: Error;
|
||||
};
|
||||
|
||||
export enum PaymentsSDKErrorCode {
|
||||
UserAbandonedCheckout = "User abandoned the checkout",
|
||||
UserLoginFailed = "User login failed",
|
||||
InvalidProps = "The props you passed in to this component are not valid.",
|
||||
InvalidCard = "The card information is invalid. Please double check that the Card, CVC, and Zip code are all correct.",
|
||||
EmailNotVerified = "The email was unable to be verified.",
|
||||
NotEnoughSupply = "There is not enough supply to claim.",
|
||||
AddressNotAllowed = "This address is not on the allowlist.",
|
||||
NoActiveClaimPhase = "There is no active claim phase at the moment.",
|
||||
}
|
||||
|
||||
export enum PayWithCryptoErrorCode {
|
||||
ErrorConnectingToWallet = "Error connecting to wallet",
|
||||
ErrorSendingTransaction = "Something went wrong sending transaction",
|
||||
InsufficientBalance = `Insufficient ETH`,
|
||||
TransactionCancelled = "Transaction Cancelled",
|
||||
WrongChain = `Wrong Chain Detected`,
|
||||
ChainSwitchUnderway = "There is a network switch already underway",
|
||||
PendingSignature = "Pending Signature",
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// UNCHANGED
|
||||
|
||||
export interface PriceSummary {
|
||||
quantity: number;
|
||||
unitPrice: PriceDetail;
|
||||
networkFees: PriceDetail;
|
||||
serviceFees: PriceDetail;
|
||||
total: PriceDetail;
|
||||
cryptoToFiatConversionRate?: number;
|
||||
}
|
||||
|
||||
export interface PriceDetail {
|
||||
/**
|
||||
* A human-readable string to display.
|
||||
* Example: $123.45 CAD
|
||||
*/
|
||||
display: string;
|
||||
/**
|
||||
* This is the value in smallest units (cents, yen, wei).
|
||||
* Example: 12345
|
||||
*/
|
||||
valueInSubunits: number;
|
||||
/**
|
||||
* The currency associated with the value.
|
||||
* Example: USD, ETH
|
||||
*/
|
||||
currency: string;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// CHANGED: Added exports
|
||||
export * from "./CheckoutWithCard";
|
||||
export * from "./PaymentsSdkError";
|
||||
export * from "./PaperUser";
|
||||
export * from "./PriceSummary";
|
||||
@@ -0,0 +1,256 @@
|
||||
// CHANGED: Added clientId to interface
|
||||
import type { ICustomizationOptions, Locale } from "../constants/style";
|
||||
import { DEFAULT_BRAND_OPTIONS } from "../constants/style";
|
||||
import { getPaperOriginUrl } from "../constants/settings";
|
||||
import {
|
||||
CHECKOUT_WITH_CARD_IFRAME_URL,
|
||||
PAPER_APP_URL,
|
||||
} from "../constants/settings";
|
||||
import type {
|
||||
ICheckoutWithCardConfigs,
|
||||
KycModal,
|
||||
ReviewResult,
|
||||
} from "../interfaces/CheckoutWithCard";
|
||||
import type {
|
||||
PaymentsSDKError,
|
||||
PaymentsSDKErrorCode,
|
||||
} from "../interfaces/PaymentsSdkError";
|
||||
import type { PriceSummary } from "../interfaces/PriceSummary";
|
||||
import { LinksManager } from "../utils/LinksManager";
|
||||
import { openCenteredPopup } from "../utils/device";
|
||||
import { postMessageToIframe } from "../utils/postMessageToIframe";
|
||||
import type { PaperPaymentElementConstructorArgs } from "./CreatePaymentElement";
|
||||
import { PaperPaymentElement } from "./CreatePaymentElement";
|
||||
import { Modal } from "./Modal";
|
||||
|
||||
export interface CheckoutWithCardLinkArgs {
|
||||
clientId?: string;
|
||||
sdkClientSecret?: string;
|
||||
appName?: string;
|
||||
options?: ICustomizationOptions;
|
||||
locale?: Locale;
|
||||
configs?: ICheckoutWithCardConfigs;
|
||||
|
||||
/**
|
||||
* @deprecated: No longer used. Domain is set to "withpaper.com".
|
||||
*/
|
||||
useAltDomain?: boolean;
|
||||
}
|
||||
|
||||
export function createCheckoutWithCardLink({
|
||||
clientId,
|
||||
sdkClientSecret,
|
||||
appName,
|
||||
options = { ...DEFAULT_BRAND_OPTIONS },
|
||||
locale,
|
||||
configs,
|
||||
}: CheckoutWithCardLinkArgs): URL {
|
||||
const CheckoutWithCardUrlBase = new URL(
|
||||
CHECKOUT_WITH_CARD_IFRAME_URL,
|
||||
PAPER_APP_URL,
|
||||
);
|
||||
let clientSecret = sdkClientSecret;
|
||||
if (!clientSecret && configs) {
|
||||
clientSecret = btoa(JSON.stringify(configs));
|
||||
}
|
||||
if (!clientSecret) {
|
||||
const error = `Must have either sdkClientSecret or configs field set. Received neither`;
|
||||
const destination = `/error?errorMessage=${error}`;
|
||||
const domain = getPaperOriginUrl();
|
||||
return new URL(destination, domain);
|
||||
}
|
||||
|
||||
if (!clientId) {
|
||||
const error = `Must have clientId field set. Please add clientId`;
|
||||
const destination = `/error?errorMessage=${error}`;
|
||||
const domain = getPaperOriginUrl();
|
||||
return new URL(destination, domain);
|
||||
}
|
||||
|
||||
const checkoutWithCardLink = new LinksManager(CheckoutWithCardUrlBase);
|
||||
checkoutWithCardLink.addClientId(clientId ?? "");
|
||||
checkoutWithCardLink.addClientSecret(clientSecret ?? "");
|
||||
checkoutWithCardLink.addStylingOptions(options);
|
||||
checkoutWithCardLink.addLocale(locale);
|
||||
checkoutWithCardLink.addAppName(appName);
|
||||
|
||||
return checkoutWithCardLink.getLink();
|
||||
}
|
||||
|
||||
export interface CheckoutWithCardMessageHandlerArgs {
|
||||
iframe: HTMLIFrameElement;
|
||||
onPaymentSuccess?: (props: {
|
||||
transactionId: string;
|
||||
/** @deprecated */
|
||||
id: string;
|
||||
}) => void;
|
||||
onReview?: (result: ReviewResult) => void;
|
||||
onError?: (error: PaymentsSDKError) => void;
|
||||
onOpenKycModal?: (props: KycModal) => void;
|
||||
onCloseKycModal?: () => void;
|
||||
onBeforeModalOpen?: (props: { url: string }) => void;
|
||||
onPriceUpdate?: (props: PriceSummary) => void;
|
||||
useAltDomain?: boolean;
|
||||
}
|
||||
|
||||
export function createCheckoutWithCardMessageHandler({
|
||||
iframe,
|
||||
onError,
|
||||
onReview,
|
||||
onPaymentSuccess,
|
||||
onBeforeModalOpen,
|
||||
onPriceUpdate,
|
||||
}: CheckoutWithCardMessageHandlerArgs) {
|
||||
let modal: Modal;
|
||||
|
||||
return (event: MessageEvent) => {
|
||||
if (!event.origin.startsWith(PAPER_APP_URL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { data } = event;
|
||||
switch (data.eventType) {
|
||||
case "checkoutWithCardError":
|
||||
if (onError) {
|
||||
onError({
|
||||
code: data.code as PaymentsSDKErrorCode,
|
||||
error: data.error,
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case "paymentSuccess":
|
||||
if (onPaymentSuccess) {
|
||||
onPaymentSuccess({ transactionId: data.id, id: data.id });
|
||||
}
|
||||
|
||||
if (data.postToIframe) {
|
||||
postMessageToIframe(iframe, data.eventType, data);
|
||||
}
|
||||
break;
|
||||
|
||||
case "reviewComplete":
|
||||
if (onReview) {
|
||||
onReview({
|
||||
id: data.id,
|
||||
cardholderName: data.cardholderName,
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case "openModalWithUrl":
|
||||
if (
|
||||
onBeforeModalOpen &&
|
||||
data.url &&
|
||||
data.url.includes("promptKYCModal")
|
||||
) {
|
||||
onBeforeModalOpen({
|
||||
url: data.url,
|
||||
});
|
||||
} else {
|
||||
modal = new Modal(undefined, {
|
||||
body: {
|
||||
colorScheme: "light",
|
||||
},
|
||||
});
|
||||
modal.open({ iframeUrl: data.url });
|
||||
}
|
||||
break;
|
||||
|
||||
case "completedSDKModal":
|
||||
modal.close();
|
||||
if (data.postToIframe) {
|
||||
postMessageToIframe(iframe, data.eventType, data);
|
||||
}
|
||||
break;
|
||||
|
||||
case "requestedPopup": {
|
||||
// The iframe requested a popup.
|
||||
// The reference to this window is not stored so the popup cannot
|
||||
// be programmatically closed.
|
||||
const popupRef = openCenteredPopup({
|
||||
url: data.url,
|
||||
width: data.width,
|
||||
height: data.height,
|
||||
});
|
||||
if (!popupRef) {
|
||||
console.error("CheckoutWithCard: Unable to open popup.");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "sizing":
|
||||
iframe.style.height = data.height + "px";
|
||||
iframe.style.maxHeight = data.height + "px";
|
||||
break;
|
||||
|
||||
case "onPriceUpdate": {
|
||||
onPriceUpdate?.(data);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// Ignore unrecognized event
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export type CheckoutWithCardElementArgs = Omit<
|
||||
CheckoutWithCardMessageHandlerArgs,
|
||||
"iframe"
|
||||
> &
|
||||
CheckoutWithCardLinkArgs &
|
||||
PaperPaymentElementConstructorArgs;
|
||||
|
||||
export function createCheckoutWithCardElement({
|
||||
clientId,
|
||||
onCloseKycModal,
|
||||
onOpenKycModal,
|
||||
sdkClientSecret,
|
||||
appName,
|
||||
elementOrId,
|
||||
onLoad,
|
||||
onError,
|
||||
locale,
|
||||
options,
|
||||
onPaymentSuccess,
|
||||
onReview,
|
||||
onBeforeModalOpen,
|
||||
onPriceUpdate,
|
||||
useAltDomain = true,
|
||||
configs,
|
||||
}: CheckoutWithCardElementArgs) {
|
||||
const checkoutWithCardId = "checkout-with-card-iframe";
|
||||
const checkoutWithCardMessageHandler = (iframe: HTMLIFrameElement) =>
|
||||
createCheckoutWithCardMessageHandler({
|
||||
iframe,
|
||||
onCloseKycModal,
|
||||
onOpenKycModal,
|
||||
onError,
|
||||
onPaymentSuccess,
|
||||
onReview,
|
||||
onBeforeModalOpen,
|
||||
onPriceUpdate,
|
||||
useAltDomain,
|
||||
});
|
||||
|
||||
const checkoutWithCardUrl = createCheckoutWithCardLink({
|
||||
clientId,
|
||||
sdkClientSecret,
|
||||
appName,
|
||||
locale,
|
||||
options,
|
||||
useAltDomain,
|
||||
configs,
|
||||
});
|
||||
|
||||
const paymentElement = new PaperPaymentElement({
|
||||
onLoad,
|
||||
elementOrId,
|
||||
});
|
||||
return paymentElement.createPaymentElement({
|
||||
handler: checkoutWithCardMessageHandler,
|
||||
iframeId: checkoutWithCardId,
|
||||
link: checkoutWithCardUrl,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
// CHANGED: Imports only
|
||||
import type { ethers } from "ethers";
|
||||
import {
|
||||
CHECKOUT_WITH_ETH_IFRAME_URL,
|
||||
PAPER_APP_URL,
|
||||
getPaperOriginUrl,
|
||||
} from "../constants/settings";
|
||||
import type { ICustomizationOptions, Locale } from "../constants/style";
|
||||
import { DEFAULT_BRAND_OPTIONS } from "../constants/style";
|
||||
import type { PaymentsSDKError } from "../interfaces/PaymentsSdkError";
|
||||
import { PayWithCryptoErrorCode } from "../interfaces/PaymentsSdkError";
|
||||
import type { PriceSummary } from "../interfaces/PriceSummary";
|
||||
import { LinksManager } from "../utils/LinksManager";
|
||||
import { handlePayWithCryptoError } from "../utils/handleCheckoutWithEthError";
|
||||
import { postMessageToIframe } from "../utils/postMessageToIframe";
|
||||
import type { PaperPaymentElementConstructorArgs } from "./CreatePaymentElement";
|
||||
import { PaperPaymentElement } from "./CreatePaymentElement";
|
||||
|
||||
export const PAY_WITH_ETH_ERROR = "payWithEthError";
|
||||
|
||||
export async function checkAndSendEth({
|
||||
data,
|
||||
iframe,
|
||||
payingWalletSigner,
|
||||
suppressErrorToast,
|
||||
onError,
|
||||
onPaymentSuccess,
|
||||
}: {
|
||||
payingWalletSigner: ethers.Signer;
|
||||
data: {
|
||||
chainId: number;
|
||||
chainName: string;
|
||||
blob: string;
|
||||
paymentAddress: string;
|
||||
value: string;
|
||||
transactionId: string;
|
||||
};
|
||||
suppressErrorToast: boolean;
|
||||
iframe: HTMLIFrameElement;
|
||||
onPaymentSuccess?:
|
||||
| CheckoutWithEthMessageHandlerArgs["onPaymentSuccess"]
|
||||
| CheckoutWithEthMessageHandlerArgs["onSuccess"];
|
||||
onError?: (error: PaymentsSDKError) => Promise<void> | void;
|
||||
}) {
|
||||
try {
|
||||
const chainId = await payingWalletSigner.getChainId();
|
||||
if (chainId !== data.chainId) {
|
||||
throw {
|
||||
isErrorObject: true,
|
||||
title: PayWithCryptoErrorCode.WrongChain,
|
||||
description: `Please change to ${data.chainName} to proceed.`,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
await handlePayWithCryptoError(e as Error, onError, (errorObject) => {
|
||||
postMessageToIframe(iframe, PAY_WITH_ETH_ERROR, {
|
||||
error: errorObject,
|
||||
suppressErrorToast,
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// send the transaction
|
||||
try {
|
||||
console.log("sending funds...", data);
|
||||
const result = await payingWalletSigner.sendTransaction({
|
||||
chainId: data.chainId,
|
||||
data: data.blob,
|
||||
to: data.paymentAddress,
|
||||
value: data.value,
|
||||
});
|
||||
const receipt = await result.wait();
|
||||
if (onPaymentSuccess && result) {
|
||||
await onPaymentSuccess({
|
||||
onChainTxResponse: result,
|
||||
onChainTxReceipt: receipt,
|
||||
transactionId: data.transactionId,
|
||||
});
|
||||
}
|
||||
if (result) {
|
||||
postMessageToIframe(iframe, "paymentSuccess", {
|
||||
suppressErrorToast,
|
||||
transactionHash: result.hash,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("error sending funds", error);
|
||||
await handlePayWithCryptoError(error as Error, onError, (errorObject) => {
|
||||
postMessageToIframe(iframe, PAY_WITH_ETH_ERROR, {
|
||||
error: errorObject,
|
||||
suppressErrorToast,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface CheckoutWithEthMessageHandlerArgs {
|
||||
iframe: HTMLIFrameElement;
|
||||
onPaymentSuccess?: (props: {
|
||||
onChainTxReceipt: ethers.providers.TransactionReceipt;
|
||||
transactionId: string;
|
||||
}) => Promise<void> | void;
|
||||
/** @deprecated */
|
||||
onSuccess?: (props: {
|
||||
onChainTxResponse: ethers.providers.TransactionResponse;
|
||||
transactionId: string;
|
||||
}) => Promise<void> | void;
|
||||
onPriceUpdate?: (props: PriceSummary) => void;
|
||||
onError?: (error: PaymentsSDKError) => void;
|
||||
suppressErrorToast?: boolean;
|
||||
setUpUserPayingWalletSigner?: (args: {
|
||||
chainId: number;
|
||||
chainName?: string;
|
||||
}) => void | Promise<void>;
|
||||
payingWalletSigner: ethers.Signer;
|
||||
}
|
||||
|
||||
export function createCheckoutWithEthMessageHandler({
|
||||
iframe,
|
||||
onError,
|
||||
onPaymentSuccess,
|
||||
onPriceUpdate,
|
||||
payingWalletSigner,
|
||||
suppressErrorToast = false,
|
||||
setUpUserPayingWalletSigner,
|
||||
}: CheckoutWithEthMessageHandlerArgs) {
|
||||
return async (event: MessageEvent) => {
|
||||
if (!event.origin.startsWith(PAPER_APP_URL)) {
|
||||
return;
|
||||
}
|
||||
const data = event.data;
|
||||
switch (data.eventType) {
|
||||
case "payWithEth": {
|
||||
if (data.error) {
|
||||
await handlePayWithCryptoError(
|
||||
new Error(data.error),
|
||||
onError,
|
||||
(errorObject) => {
|
||||
postMessageToIframe(iframe, PAY_WITH_ETH_ERROR, {
|
||||
error: errorObject,
|
||||
suppressErrorToast,
|
||||
});
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Allows Dev's to inject any chain switching for their custom signer here.
|
||||
if (setUpUserPayingWalletSigner) {
|
||||
try {
|
||||
console.log("setting up signer");
|
||||
await setUpUserPayingWalletSigner({
|
||||
chainId: data.chainId,
|
||||
chainName: data.chainName,
|
||||
});
|
||||
} catch (error) {
|
||||
console.log("error setting up signer", error);
|
||||
await handlePayWithCryptoError(
|
||||
error as Error,
|
||||
onError,
|
||||
(errorObject) => {
|
||||
postMessageToIframe(iframe, PAY_WITH_ETH_ERROR, {
|
||||
error: errorObject,
|
||||
suppressErrorToast,
|
||||
});
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await checkAndSendEth({
|
||||
data,
|
||||
iframe,
|
||||
payingWalletSigner,
|
||||
suppressErrorToast,
|
||||
onError,
|
||||
onPaymentSuccess,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "checkout-with-eth-sizing": {
|
||||
iframe.style.height = data.height + "px";
|
||||
iframe.style.maxHeight = data.height + "px";
|
||||
break;
|
||||
}
|
||||
case "onPriceUpdate": {
|
||||
onPriceUpdate?.(data as PriceSummary);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export interface ICheckoutWithEthConfigs {
|
||||
contractId: string;
|
||||
walletAddress: string;
|
||||
email?: string;
|
||||
quantity?: number;
|
||||
mintMethod?: {
|
||||
name: string;
|
||||
args: Record<string, any>[];
|
||||
payment: { value: string; currency: string };
|
||||
};
|
||||
contractArgs?: Record<string, any>;
|
||||
|
||||
// payment customizations
|
||||
capturePaymentLater?: boolean;
|
||||
fiatCurrency?: string;
|
||||
|
||||
// stripe receipt
|
||||
title?: string;
|
||||
|
||||
// email
|
||||
sendEmailOnTransferSucceeded?: boolean;
|
||||
postPurchaseMessageMarkdown?: string;
|
||||
postPurchaseButtonText?: string;
|
||||
successCallbackUrl?: string;
|
||||
}
|
||||
|
||||
export interface CheckoutWithEthLinkArgs {
|
||||
sdkClientSecret?: string;
|
||||
appName?: string;
|
||||
payingWalletSigner: ethers.Signer;
|
||||
receivingWalletType?:
|
||||
| "WalletConnect"
|
||||
| "MetaMask"
|
||||
| "Coinbase Wallet"
|
||||
| string;
|
||||
showConnectWalletOptions?: boolean;
|
||||
|
||||
locale?: Locale;
|
||||
options?: ICustomizationOptions;
|
||||
configs?: ICheckoutWithEthConfigs;
|
||||
}
|
||||
|
||||
export async function createCheckoutWithEthLink({
|
||||
sdkClientSecret,
|
||||
payingWalletSigner,
|
||||
receivingWalletType,
|
||||
showConnectWalletOptions = false,
|
||||
appName,
|
||||
locale,
|
||||
options = {
|
||||
...DEFAULT_BRAND_OPTIONS,
|
||||
},
|
||||
configs,
|
||||
}: CheckoutWithEthLinkArgs) {
|
||||
const checkoutWithEthUrlBase = new URL(
|
||||
CHECKOUT_WITH_ETH_IFRAME_URL,
|
||||
PAPER_APP_URL,
|
||||
);
|
||||
const address = await payingWalletSigner.getAddress();
|
||||
let clientSecret = sdkClientSecret;
|
||||
if (!clientSecret && configs) {
|
||||
clientSecret = btoa(JSON.stringify(configs));
|
||||
}
|
||||
if (!clientSecret) {
|
||||
const error = `Must have either sdkClientSecret or configs field set. Received neither`;
|
||||
const destination = `/error?errorMessage=${error}`;
|
||||
const domain = getPaperOriginUrl();
|
||||
return new URL(destination, domain);
|
||||
}
|
||||
|
||||
const checkoutWithEthLink = new LinksManager(checkoutWithEthUrlBase);
|
||||
checkoutWithEthLink.addClientSecret(clientSecret ?? "");
|
||||
checkoutWithEthLink.addRecipientWalletAddress(address);
|
||||
checkoutWithEthLink.addPayerWalletAddress(address);
|
||||
checkoutWithEthLink.addReceivingWalletType(receivingWalletType);
|
||||
checkoutWithEthLink.addAppName(appName);
|
||||
checkoutWithEthLink.addShowConnectWalletOptions(showConnectWalletOptions);
|
||||
checkoutWithEthLink.addStylingOptions(options);
|
||||
checkoutWithEthLink.addLocale(locale);
|
||||
|
||||
return checkoutWithEthLink.getLink();
|
||||
}
|
||||
|
||||
export type CheckoutWithEthElementArgs = Omit<
|
||||
Omit<CheckoutWithEthMessageHandlerArgs, "iframe">,
|
||||
"setUpUserPayingWalletSigner"
|
||||
> &
|
||||
CheckoutWithEthLinkArgs &
|
||||
PaperPaymentElementConstructorArgs;
|
||||
|
||||
export async function createCheckoutWithEthElement({
|
||||
sdkClientSecret,
|
||||
suppressErrorToast,
|
||||
onError,
|
||||
onLoad,
|
||||
payingWalletSigner,
|
||||
receivingWalletType,
|
||||
appName,
|
||||
showConnectWalletOptions,
|
||||
locale,
|
||||
options,
|
||||
elementOrId,
|
||||
onPaymentSuccess: _onPaymentSuccess,
|
||||
onSuccess,
|
||||
}: CheckoutWithEthElementArgs): Promise<HTMLIFrameElement> {
|
||||
const onPaymentSuccess =
|
||||
_onPaymentSuccess ??
|
||||
(onSuccess as CheckoutWithEthMessageHandlerArgs["onPaymentSuccess"]);
|
||||
const checkoutWithEthId = "checkout-with-eth-iframe";
|
||||
|
||||
const checkoutWithEthMessageHandler = (iframe: HTMLIFrameElement) =>
|
||||
createCheckoutWithEthMessageHandler({
|
||||
iframe,
|
||||
onError,
|
||||
payingWalletSigner,
|
||||
suppressErrorToast,
|
||||
onPaymentSuccess,
|
||||
});
|
||||
|
||||
const checkoutWithEthUrl = await createCheckoutWithEthLink({
|
||||
payingWalletSigner,
|
||||
sdkClientSecret,
|
||||
appName,
|
||||
locale,
|
||||
options,
|
||||
receivingWalletType,
|
||||
showConnectWalletOptions,
|
||||
});
|
||||
const paymentElement = new PaperPaymentElement({
|
||||
onLoad,
|
||||
elementOrId,
|
||||
});
|
||||
return paymentElement.createPaymentElement({
|
||||
handler: checkoutWithEthMessageHandler,
|
||||
iframeId: checkoutWithEthId,
|
||||
link: checkoutWithEthUrl,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// CHANGED: packageJson import + version string
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires, better-tree-shaking/no-top-level-side-effects
|
||||
const packageJson = require("../package.json");
|
||||
|
||||
export interface PaperPaymentElementConstructorArgs {
|
||||
onLoad?: (event?: Event) => void;
|
||||
elementOrId?: string | HTMLElement;
|
||||
}
|
||||
|
||||
export class PaperPaymentElement {
|
||||
private elementOrId?: PaperPaymentElementConstructorArgs["elementOrId"];
|
||||
private onLoad?: PaperPaymentElementConstructorArgs["onLoad"];
|
||||
|
||||
constructor({ elementOrId, onLoad }: PaperPaymentElementConstructorArgs) {
|
||||
this.elementOrId = elementOrId;
|
||||
this.onLoad = onLoad;
|
||||
}
|
||||
createPaymentElement({
|
||||
handler,
|
||||
link,
|
||||
iframeId,
|
||||
}: {
|
||||
handler: (
|
||||
iframe: HTMLIFrameElement,
|
||||
) => (event: MessageEvent) => void | Promise<void>;
|
||||
link: URL;
|
||||
iframeId: string;
|
||||
}) {
|
||||
const iframe = document.createElement("iframe");
|
||||
iframe.src = link.href;
|
||||
iframe.id = iframeId;
|
||||
iframe.allow = "payment";
|
||||
iframe.setAttribute(
|
||||
"style",
|
||||
"margin-left:auto; margin-right:auto; width:100%; height: 100%; min-height:375px; transition-property:all; transition-timing-function:cubic-bezier(0.4, 0, 0.2, 1); transition-duration:150ms; color-scheme: light;",
|
||||
);
|
||||
iframe.onload = (event: Event) => {
|
||||
if (this.onLoad) {
|
||||
this.onLoad(event);
|
||||
}
|
||||
};
|
||||
iframe.setAttribute(
|
||||
"data-thirdweb-sdk-version",
|
||||
`${packageJson.name}@${packageJson.version}`,
|
||||
);
|
||||
|
||||
if (!this.elementOrId) {
|
||||
window.addEventListener("message", handler(iframe));
|
||||
return iframe;
|
||||
}
|
||||
|
||||
let container: HTMLElement | string = this.elementOrId;
|
||||
if (typeof container === "string") {
|
||||
const domElement = document.getElementById(container);
|
||||
if (!domElement) {
|
||||
throw new Error("Invalid id given");
|
||||
}
|
||||
container = domElement;
|
||||
}
|
||||
|
||||
const existing: HTMLIFrameElement | null = container.querySelector(
|
||||
"#" + iframeId,
|
||||
);
|
||||
// if we already created an iframe, consider updating the iframe link if it's new
|
||||
if (existing) {
|
||||
if (existing.src === link.href) {
|
||||
return existing;
|
||||
}
|
||||
existing.src = link.href;
|
||||
return existing;
|
||||
}
|
||||
|
||||
window.addEventListener("message", handler(iframe));
|
||||
return container.appendChild(iframe);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { StyleObject } from "../../constants/style";
|
||||
import type { ModalStyles } from "../../interfaces/Modal";
|
||||
import { getDefaultModalStyles } from "./styles";
|
||||
|
||||
import packageJson from "../../../package.json";
|
||||
|
||||
const MAIN_CLASSNAME = "paper--drawer-main";
|
||||
const OVERLAY_CLASSNAME = "paper--drawer-overlay";
|
||||
const BODY_CLASSNAME = "paper--drawer-body";
|
||||
const CLOSE_CLASSNAME = "paper--drawer-close";
|
||||
|
||||
export class Drawer {
|
||||
protected container: HTMLElement;
|
||||
protected main: HTMLDivElement;
|
||||
protected overlay: HTMLDivElement;
|
||||
protected closeButton: HTMLButtonElement;
|
||||
protected iframe: HTMLIFrameElement;
|
||||
protected onCloseCallback: (() => void) | undefined;
|
||||
|
||||
protected closeTimeout: number | undefined;
|
||||
// eslint-disable-next-line better-tree-shaking/no-top-level-side-effects
|
||||
styles = getDefaultModalStyles();
|
||||
body: HTMLDivElement;
|
||||
|
||||
constructor(container?: HTMLElement, styles?: Partial<ModalStyles>) {
|
||||
this.container = container || document.body;
|
||||
|
||||
if (styles) {
|
||||
this.mergeStyles(styles);
|
||||
}
|
||||
|
||||
this.main = document.createElement("div");
|
||||
this.main.className = MAIN_CLASSNAME;
|
||||
|
||||
this.overlay = document.createElement("div");
|
||||
this.overlay.className = OVERLAY_CLASSNAME;
|
||||
|
||||
this.body = document.createElement("div");
|
||||
this.body.className = BODY_CLASSNAME;
|
||||
|
||||
this.closeButton = document.createElement("button");
|
||||
this.closeButton.className = CLOSE_CLASSNAME;
|
||||
this.closeButton.innerHTML = "✕";
|
||||
this.closeButton.onclick = () => {
|
||||
this.close();
|
||||
};
|
||||
|
||||
this.iframe = document.createElement("iframe");
|
||||
this.iframe.allow = "camera; microphone; payment";
|
||||
this.iframe.setAttribute(
|
||||
"data-thirdweb-sdk-version",
|
||||
`${packageJson.name}@${packageJson.version}`,
|
||||
);
|
||||
|
||||
this.assignStyles(this.main, this.styles.main);
|
||||
this.assignStyles(this.overlay, this.styles.overlay);
|
||||
this.assignStyles(this.body, this.styles.body);
|
||||
this.assignStyles(this.iframe, this.styles.iframe);
|
||||
if (this.styles.closeButton) {
|
||||
this.assignStyles(this.closeButton, this.styles.closeButton);
|
||||
}
|
||||
}
|
||||
|
||||
open({ iframeUrl }: { iframeUrl?: string } = {}) {
|
||||
if (iframeUrl) {
|
||||
this.iframe.src = iframeUrl;
|
||||
this.body.appendChild(this.iframe);
|
||||
}
|
||||
|
||||
this.addAccessibility();
|
||||
|
||||
this.main.appendChild(this.overlay);
|
||||
this.main.appendChild(this.body);
|
||||
this.main.appendChild(this.closeButton);
|
||||
|
||||
this.container.appendChild(this.main);
|
||||
document.body.style.overflow = "hidden";
|
||||
|
||||
// Animate in.
|
||||
this.overlay.style.backgroundColor = "rgba(0, 0, 0, 0.5)";
|
||||
this.body.style.right = "0px";
|
||||
this.body.style.opacity = "1";
|
||||
|
||||
return this.iframe;
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closeButton.remove();
|
||||
|
||||
// Animate out.
|
||||
this.overlay.style.backgroundColor = "rgba(0, 0, 0, 0)";
|
||||
this.body.style.right = "-100px";
|
||||
this.body.style.opacity = "0";
|
||||
|
||||
// Remove drawer from DOM.
|
||||
this.closeTimeout = window.setTimeout(() => {
|
||||
document.body.style.overflow = "visible";
|
||||
this.main.remove();
|
||||
|
||||
window.clearTimeout(this.closeTimeout);
|
||||
this.onCloseCallback?.();
|
||||
}, 250);
|
||||
}
|
||||
|
||||
setOnCloseCallback(callback: () => void) {
|
||||
this.onCloseCallback = callback;
|
||||
}
|
||||
|
||||
protected mergeStyles(styles: Partial<ModalStyles>) {
|
||||
this.styles.body = {
|
||||
...this.styles.body,
|
||||
...(styles.body || {}),
|
||||
};
|
||||
|
||||
this.styles.overlay = {
|
||||
...this.styles.overlay,
|
||||
...(styles.overlay || {}),
|
||||
};
|
||||
|
||||
this.styles.main = {
|
||||
...this.styles.main,
|
||||
...(styles.main || {}),
|
||||
};
|
||||
|
||||
this.styles.iframe = {
|
||||
...this.styles.iframe,
|
||||
...(styles.iframe || {}),
|
||||
};
|
||||
|
||||
this.styles.closeButton = {
|
||||
...this.styles.closeButton,
|
||||
...(styles.closeButton || {}),
|
||||
};
|
||||
}
|
||||
|
||||
protected addAccessibility() {
|
||||
this.main.setAttribute("aria-hidden", "true");
|
||||
this.overlay.setAttribute("aria-hidden", "true");
|
||||
this.body.setAttribute("aria-modal", "true");
|
||||
this.body.setAttribute("role", "dialog");
|
||||
}
|
||||
|
||||
protected assignStyles(el: HTMLElement, styles: StyleObject) {
|
||||
Object.assign(el.style, styles);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { ModalStyles } from "../../interfaces/Modal";
|
||||
|
||||
const fullScreen = {
|
||||
position: "fixed",
|
||||
top: "0px",
|
||||
left: "0px",
|
||||
right: "0px",
|
||||
bottom: "0px",
|
||||
};
|
||||
|
||||
export const getDefaultModalStyles = (): ModalStyles => ({
|
||||
main: {
|
||||
...fullScreen,
|
||||
zIndex: "2147483646",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "end",
|
||||
},
|
||||
overlay: {
|
||||
...fullScreen,
|
||||
backgroundColor: "rgba(0, 0, 0, 0)",
|
||||
transition: "background-color ease-out 0.2s",
|
||||
},
|
||||
body: {
|
||||
position: "fixed",
|
||||
width: "100%",
|
||||
maxWidth: "420px",
|
||||
top: "0px",
|
||||
bottom: "0px",
|
||||
right: "-100px",
|
||||
opacity: "0",
|
||||
boxShadow: "0px 10px 20px rgba(0, 0, 0, 0.25)",
|
||||
backgroundColor: window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "#2F2F2F"
|
||||
: "white",
|
||||
overflow: "hidden",
|
||||
transition: "all ease-out 0.2s",
|
||||
},
|
||||
spinner: {
|
||||
position: "absolute",
|
||||
top: "0",
|
||||
bottom: "0",
|
||||
left: "0",
|
||||
right: "0",
|
||||
margin: "auto",
|
||||
borderWidth: "3px",
|
||||
borderColor: "#2D3748 #2D3748 transparent transparent",
|
||||
borderRadius: "50%",
|
||||
width: "30px",
|
||||
height: "30px",
|
||||
animation: "spin 1s linear infinite",
|
||||
},
|
||||
iframe: {
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
border: "none",
|
||||
backgroundColor: "transparent",
|
||||
},
|
||||
closeButton: {
|
||||
position: "fixed",
|
||||
cursor: "pointer",
|
||||
top: "0.75rem",
|
||||
right: "1rem",
|
||||
color: "#888",
|
||||
padding: "2px 8px",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { StyleObject } from "../../constants/style";
|
||||
import type { ModalStyles } from "../../interfaces/Modal";
|
||||
import { getDefaultModalStyles, modalKeyframeAnimations } from "./styles";
|
||||
|
||||
import packageJson from "../../../package.json";
|
||||
|
||||
export const MODAL_ID = "paper-js-sdk-modal";
|
||||
|
||||
export class Modal {
|
||||
protected container: HTMLElement;
|
||||
protected main: HTMLDivElement;
|
||||
protected overlay: HTMLDivElement;
|
||||
protected iframe: HTMLIFrameElement;
|
||||
protected spinner: HTMLDivElement;
|
||||
|
||||
protected style: HTMLStyleElement;
|
||||
// eslint-disable-next-line better-tree-shaking/no-top-level-side-effects
|
||||
styles = getDefaultModalStyles();
|
||||
body: HTMLDivElement;
|
||||
|
||||
constructor(container?: HTMLElement, styles?: Partial<ModalStyles>) {
|
||||
this.container = container || document.body;
|
||||
|
||||
if (styles) {
|
||||
this.mergeStyles(styles);
|
||||
}
|
||||
|
||||
this.main = document.createElement("div");
|
||||
this.main.id = MODAL_ID;
|
||||
|
||||
this.overlay = document.createElement("div");
|
||||
this.overlay.id = `${MODAL_ID}-overlay`;
|
||||
this.body = document.createElement("div");
|
||||
this.body.id = `${MODAL_ID}-body`;
|
||||
this.spinner = document.createElement("div");
|
||||
this.spinner.id = `${MODAL_ID}-spinner`;
|
||||
this.iframe = document.createElement("iframe");
|
||||
this.iframe.id = `${MODAL_ID}-iframe`;
|
||||
this.iframe.allow = "camera; microphone; payment";
|
||||
this.iframe.setAttribute(
|
||||
"data-thirdweb-sdk-version",
|
||||
`${packageJson.name}@${packageJson.version}`,
|
||||
);
|
||||
|
||||
this.style = document.createElement("style");
|
||||
this.style.innerHTML = modalKeyframeAnimations;
|
||||
|
||||
this.assignStyles(this.main, this.styles.main);
|
||||
this.assignStyles(this.overlay, this.styles.overlay);
|
||||
this.assignStyles(this.body, this.styles.body);
|
||||
this.assignStyles(this.spinner, this.styles.spinner);
|
||||
this.assignStyles(this.iframe, this.styles.iframe);
|
||||
}
|
||||
|
||||
open({ iframeUrl }: { iframeUrl?: string } = {}) {
|
||||
if (iframeUrl) {
|
||||
this.body.appendChild(this.spinner);
|
||||
this.iframe.src = iframeUrl;
|
||||
// Remove the spinner when the iframe loads.
|
||||
this.iframe.onload = () => this.body.removeChild(this.spinner);
|
||||
this.body.appendChild(this.iframe);
|
||||
}
|
||||
|
||||
this.addAccessibility();
|
||||
|
||||
this.main.appendChild(this.overlay);
|
||||
this.main.appendChild(this.style);
|
||||
this.main.appendChild(this.body);
|
||||
|
||||
this.container.appendChild(this.main);
|
||||
document.body.style.overflow = "hidden";
|
||||
}
|
||||
|
||||
close() {
|
||||
this.body.style.animation = "pew-modal-slideOut 0.2s forwards";
|
||||
window.setTimeout(() => this.main.remove(), 250);
|
||||
}
|
||||
|
||||
protected mergeStyles(styles: Partial<ModalStyles>) {
|
||||
this.styles.body = {
|
||||
...this.styles.body,
|
||||
...(styles.body || {}),
|
||||
};
|
||||
|
||||
this.styles.spinner = {
|
||||
...this.styles.spinner,
|
||||
...(styles.spinner || {}),
|
||||
};
|
||||
|
||||
this.styles.overlay = {
|
||||
...this.styles.overlay,
|
||||
...(styles.overlay || {}),
|
||||
};
|
||||
|
||||
this.styles.main = {
|
||||
...this.styles.main,
|
||||
...(styles.main || {}),
|
||||
};
|
||||
|
||||
this.styles.iframe = {
|
||||
...this.styles.iframe,
|
||||
...(styles.iframe || {}),
|
||||
};
|
||||
}
|
||||
|
||||
protected addAccessibility() {
|
||||
this.main.setAttribute("aria-hidden", "true");
|
||||
this.overlay.setAttribute("aria-hidden", "true");
|
||||
this.body.setAttribute("aria-modal", "true");
|
||||
this.body.setAttribute("role", "dialog");
|
||||
}
|
||||
|
||||
protected assignStyles(el: HTMLElement, styles: StyleObject) {
|
||||
Object.assign(el.style, styles);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { ModalStyles } from "../../interfaces/Modal";
|
||||
|
||||
const fullScreen = {
|
||||
top: "0px",
|
||||
left: "0px",
|
||||
right: "0px",
|
||||
bottom: "0px",
|
||||
};
|
||||
|
||||
export const getDefaultModalStyles = (): ModalStyles => ({
|
||||
main: {
|
||||
...fullScreen,
|
||||
position: "fixed",
|
||||
zIndex: "10000",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
pointerEvents: "auto",
|
||||
},
|
||||
overlay: {
|
||||
...fullScreen,
|
||||
position: "absolute",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.33)",
|
||||
pointerEvents: "auto",
|
||||
},
|
||||
body: {
|
||||
background: "transparent",
|
||||
borderRadius: "12px",
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
width: "100%",
|
||||
maxWidth: "500px",
|
||||
height: "700px",
|
||||
maxHeight: "80%",
|
||||
animation: "pew-modal-slideIn 0.2s forwards",
|
||||
pointerEvents: "auto",
|
||||
},
|
||||
spinner: {
|
||||
position: "absolute",
|
||||
top: "0",
|
||||
bottom: "0",
|
||||
left: "0",
|
||||
right: "0",
|
||||
margin: "auto",
|
||||
borderWidth: "3px",
|
||||
borderColor: "#2D3748 #2D3748 transparent transparent",
|
||||
borderRadius: "50%",
|
||||
width: "30px",
|
||||
height: "30px",
|
||||
animation: "spin 1s linear infinite",
|
||||
},
|
||||
iframe: {
|
||||
position: "relative",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
border: "none",
|
||||
background: "transparent",
|
||||
},
|
||||
});
|
||||
|
||||
export const modalKeyframeAnimations = `
|
||||
@keyframes pew-modal-slideIn {
|
||||
from {opacity: 0; transform: translate3d(0, 20px, 0);}
|
||||
to {opacity: 1; transform: translate3d(0, 0, 0);}
|
||||
}
|
||||
|
||||
@keyframes pew-modal-slideOut {
|
||||
from {opacity: 1; transform: translate3d(0, 0, 0);}
|
||||
to {opacity: 0; transform: translate3d(0, 20px, 0);}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,4 @@
|
||||
// CHANGED: ADDED
|
||||
export * from "./CheckoutWithCard";
|
||||
export * from "./CheckoutWithEth";
|
||||
export * from "./renderPaperCheckoutLink";
|
||||
@@ -0,0 +1,82 @@
|
||||
// UNCHANGED
|
||||
import { PAPER_APP_URL } from "../constants/settings";
|
||||
import { Drawer } from "./Drawer";
|
||||
|
||||
async function sleepForSeconds(seconds: number) {
|
||||
return new Promise((res) => {
|
||||
setTimeout(() => {
|
||||
res(0);
|
||||
}, seconds * 1000);
|
||||
});
|
||||
}
|
||||
|
||||
export function renderPaperCheckoutLink({
|
||||
checkoutLinkUrl,
|
||||
onPaymentSucceeded,
|
||||
onPaymentFailed,
|
||||
onTransferSucceeded,
|
||||
onModalClosed,
|
||||
}: {
|
||||
checkoutLinkUrl: string;
|
||||
onPaymentSucceeded?: ({ transactionId }: { transactionId: string }) => void;
|
||||
onPaymentFailed?: ({ transactionId }: { transactionId: string }) => void;
|
||||
onTransferSucceeded?: ({
|
||||
transactionId,
|
||||
claimedTokens,
|
||||
}: {
|
||||
transactionId: string;
|
||||
claimedTokens: any;
|
||||
}) => void;
|
||||
onModalClosed?: () => void;
|
||||
}) {
|
||||
const drawer = new Drawer();
|
||||
|
||||
const formattedCheckoutLinkUrl = new URL(checkoutLinkUrl);
|
||||
formattedCheckoutLinkUrl.searchParams.set("display", "DRAWER");
|
||||
drawer.open({ iframeUrl: formattedCheckoutLinkUrl.href });
|
||||
if (onModalClosed) {
|
||||
drawer.setOnCloseCallback(onModalClosed);
|
||||
}
|
||||
|
||||
const messageHandler = async (e: MessageEvent) => {
|
||||
if (e.origin !== PAPER_APP_URL) {
|
||||
return;
|
||||
}
|
||||
const result = e.data;
|
||||
if (!result.eventType) {
|
||||
return;
|
||||
}
|
||||
switch (result.eventType) {
|
||||
case "paymentSuccess": {
|
||||
const transactionId = e.data.id;
|
||||
onPaymentSucceeded?.({ transactionId });
|
||||
break;
|
||||
}
|
||||
case "claimSuccessful": {
|
||||
const { id: transactionId, claimedTokens } = e.data;
|
||||
onTransferSucceeded?.({ transactionId, claimedTokens });
|
||||
await sleepForSeconds(3.5);
|
||||
drawer.close();
|
||||
break;
|
||||
}
|
||||
case "redirectAfterSuccess": {
|
||||
const redirectUrl = e.data.redirectUrl;
|
||||
window.location.assign(redirectUrl);
|
||||
break;
|
||||
}
|
||||
case "paymentFailed": {
|
||||
const transactionId = e.data.id;
|
||||
onPaymentFailed?.({ transactionId });
|
||||
break;
|
||||
}
|
||||
case "modalClosed": {
|
||||
onModalClosed?.();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported eventType ${result.eventType}`);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", messageHandler);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// CHANGED: added clientId to link
|
||||
|
||||
import type { ICustomizationOptions, Locale } from "../constants/style";
|
||||
|
||||
export class LinksManager {
|
||||
private link: URL;
|
||||
|
||||
constructor(baseLink: URL) {
|
||||
this.link = baseLink;
|
||||
}
|
||||
|
||||
addStylingOptions(options: ICustomizationOptions) {
|
||||
if (options.colorPrimary) {
|
||||
this.link.searchParams.set("colorPrimary", options.colorPrimary);
|
||||
}
|
||||
if (options.colorBackground) {
|
||||
this.link.searchParams.set("colorBackground", options.colorBackground);
|
||||
}
|
||||
if (options.colorText) {
|
||||
this.link.searchParams.set("colorText", options.colorText);
|
||||
}
|
||||
if (options.borderRadius !== undefined) {
|
||||
this.link.searchParams.set(
|
||||
"borderRadius",
|
||||
options.borderRadius.toString(),
|
||||
);
|
||||
}
|
||||
if (options.fontFamily) {
|
||||
this.link.searchParams.set("fontFamily", options.fontFamily);
|
||||
}
|
||||
if (options.inputBackgroundColor) {
|
||||
this.link.searchParams.set(
|
||||
"inputBackgroundColor",
|
||||
options.inputBackgroundColor,
|
||||
);
|
||||
}
|
||||
if (options.inputBorderColor) {
|
||||
this.link.searchParams.set("inputBorderColor", options.inputBorderColor);
|
||||
}
|
||||
}
|
||||
|
||||
addClientSecret(sdkClientSecret: string) {
|
||||
this.link.searchParams.set("sdkClientSecret", sdkClientSecret);
|
||||
}
|
||||
|
||||
addClientId(clientId: string) {
|
||||
this.link.searchParams.set("clientId", clientId);
|
||||
}
|
||||
|
||||
addLocale(locale?: Locale) {
|
||||
if (locale) {
|
||||
this.link.searchParams.set("locale", locale.toString());
|
||||
}
|
||||
}
|
||||
|
||||
addOTP() {
|
||||
this.link.searchParams.set("withOTP", "true");
|
||||
}
|
||||
|
||||
addAppName(appName?: string) {
|
||||
if (appName) {
|
||||
this.link.searchParams.set("appName", appName);
|
||||
}
|
||||
}
|
||||
|
||||
addShowConnectWalletOptions(showConnectWalletOptions: boolean) {
|
||||
this.link.searchParams.append(
|
||||
"showConnectWalletOptions",
|
||||
showConnectWalletOptions.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
addReceivingWalletType(walletType?: string) {
|
||||
this.link.searchParams.append("walletType", walletType || "Preset");
|
||||
}
|
||||
|
||||
addRecipientWalletAddress(address: string) {
|
||||
this.link.searchParams.set("recipientWalletAddress", address);
|
||||
}
|
||||
|
||||
addPayerWalletAddress(address: string) {
|
||||
this.link.searchParams.append("payerWalletAddress", address);
|
||||
}
|
||||
|
||||
addDate(date?: Date) {
|
||||
this.link.searchParams.set(
|
||||
"date",
|
||||
date ? date.toString() : Date.now().toString(),
|
||||
);
|
||||
}
|
||||
|
||||
getLink(): URL {
|
||||
return this.link;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// UNCHANGED
|
||||
/**
|
||||
* Opens a popup centered on the current window.
|
||||
* Note that modern browsers may prevent popups from opening automatically,
|
||||
* so try to handle the case where the window returned is null.
|
||||
*
|
||||
* @returns Window | null - The Window object that was opened. If null is returned, the popup failed to open.
|
||||
*/
|
||||
export const openCenteredPopup = ({
|
||||
url,
|
||||
width = 440,
|
||||
height = 700,
|
||||
}: {
|
||||
url: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}): Window | null => {
|
||||
if (!window?.top) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const y = window.top.outerHeight / 2 + window.top.screenY - height / 2;
|
||||
const x = window.top.outerWidth / 2 + window.top.screenX - width / 2;
|
||||
return window.open(
|
||||
url,
|
||||
"_blank",
|
||||
`popup=true,width=${width},height=${height},top=${y},left=${x}`,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
// Changed: Updated PaperSDKError
|
||||
import type { PaymentsSDKError } from "../interfaces/PaymentsSdkError";
|
||||
import { PayWithCryptoErrorCode } from "../interfaces/PaymentsSdkError";
|
||||
|
||||
export interface IErrorObject {
|
||||
isErrorObject: boolean;
|
||||
title: PayWithCryptoErrorCode;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export const handlePayWithCryptoError = async (
|
||||
error: Error | IErrorObject,
|
||||
onError?: (code: PaymentsSDKError) => Promise<void> | void,
|
||||
postToParent?: (errorObject: Omit<IErrorObject, "isErrorObject">) => void,
|
||||
) => {
|
||||
if ("isErrorObject" in error) {
|
||||
if (onError) {
|
||||
await onError({ code: error.title, error: new Error(error.title) });
|
||||
}
|
||||
if (postToParent) {
|
||||
postToParent({ ...error });
|
||||
}
|
||||
} else if (!("message" in error)) {
|
||||
if (onError) {
|
||||
await onError({
|
||||
code: PayWithCryptoErrorCode.ErrorSendingTransaction,
|
||||
error: new Error(JSON.stringify(error)),
|
||||
});
|
||||
}
|
||||
if (postToParent) {
|
||||
postToParent({
|
||||
description: `${error}`,
|
||||
title: PayWithCryptoErrorCode.ErrorSendingTransaction,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
error.message.includes("rejected") ||
|
||||
error.message.includes("denied transaction")
|
||||
) {
|
||||
if (onError) {
|
||||
await onError({
|
||||
code: PayWithCryptoErrorCode.TransactionCancelled,
|
||||
error,
|
||||
});
|
||||
}
|
||||
if (postToParent) {
|
||||
postToParent({
|
||||
description: "",
|
||||
title: PayWithCryptoErrorCode.TransactionCancelled,
|
||||
});
|
||||
}
|
||||
} else if (error.message.includes("insufficient funds")) {
|
||||
if (onError) {
|
||||
await onError({
|
||||
code: PayWithCryptoErrorCode.InsufficientBalance,
|
||||
error,
|
||||
});
|
||||
}
|
||||
if (postToParent) {
|
||||
postToParent({
|
||||
description:
|
||||
"Check your wallet's ETH balance to make sure you have enough!",
|
||||
title: PayWithCryptoErrorCode.InsufficientBalance,
|
||||
});
|
||||
}
|
||||
} else if (error.message.includes("Error switching chain")) {
|
||||
if (onError) {
|
||||
await onError({
|
||||
code: PayWithCryptoErrorCode.ChainSwitchUnderway,
|
||||
error,
|
||||
});
|
||||
}
|
||||
if (postToParent) {
|
||||
postToParent({
|
||||
description: "Check your wallet app",
|
||||
title: PayWithCryptoErrorCode.ChainSwitchUnderway,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (onError) {
|
||||
await onError({
|
||||
code: PayWithCryptoErrorCode.ErrorSendingTransaction,
|
||||
error,
|
||||
});
|
||||
}
|
||||
if (postToParent) {
|
||||
postToParent({
|
||||
description: `${error.message}`,
|
||||
title: PayWithCryptoErrorCode.ErrorSendingTransaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
// UNCHANGED
|
||||
export function postMessageToIframe<T>(
|
||||
frame: HTMLIFrameElement,
|
||||
eventType: string,
|
||||
data: T,
|
||||
) {
|
||||
frame.contentWindow?.postMessage({ eventType, ...data }, "*");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "@thirdweb-dev/tsconfig/sdk.json",
|
||||
"include": ["src", "types"],
|
||||
"exclude": ["dist", "build", "node_modules"],
|
||||
"compilerOptions": {
|
||||
"noUncheckedIndexedAccess": true
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,53 @@
|
||||
# @thirdweb-dev/react-core
|
||||
|
||||
## 4.2.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2119](https://github.com/thirdweb-dev/js/pull/2119) [`cf606665`](https://github.com/thirdweb-dev/js/commit/cf606665fcfdad7b08259350d39b60313278a8dc) Thanks [@MananTank](https://github.com/MananTank)! - Update Links to Docs website
|
||||
|
||||
- Updated dependencies [[`cf606665`](https://github.com/thirdweb-dev/js/commit/cf606665fcfdad7b08259350d39b60313278a8dc)]:
|
||||
- @thirdweb-dev/wallets@2.3.4
|
||||
- @thirdweb-dev/sdk@4.0.25
|
||||
- @thirdweb-dev/auth@4.1.21
|
||||
|
||||
## 4.2.1
|
||||
|
||||
## 4.2.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [[`b808e942`](https://github.com/thirdweb-dev/js/commit/b808e942fdaa81b5de61dcb3f2083081cb99ea11), [`e46dd025`](https://github.com/thirdweb-dev/js/commit/e46dd0254f157c3c4d50fe3e4f44e2e24eaf34a8)]:
|
||||
- @thirdweb-dev/sdk@4.0.24
|
||||
- @thirdweb-dev/wallets@2.3.3
|
||||
- @thirdweb-dev/auth@4.1.20
|
||||
|
||||
## 4.1.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2084](https://github.com/thirdweb-dev/js/pull/2084) [`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c) Thanks [@MananTank](https://github.com/MananTank)! - JSDoc comments Improvements
|
||||
|
||||
- [#2008](https://github.com/thirdweb-dev/js/pull/2008) [`23db97cc`](https://github.com/thirdweb-dev/js/commit/23db97cca51211df82d430fbfff4bbfbd7d4dc38) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Add hook for transferring native token
|
||||
|
||||
- Updated dependencies [[`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c), [`fed1313a`](https://github.com/thirdweb-dev/js/commit/fed1313a199011a9b52d7c5e11ad6e72fc969002), [`f369bffe`](https://github.com/thirdweb-dev/js/commit/f369bffe5a30e2e8a9df2ac62f24f93f96324186), [`81c46e22`](https://github.com/thirdweb-dev/js/commit/81c46e22984cdb5b33b2e6eb99a0ebf0e4fbdb33)]:
|
||||
- @thirdweb-dev/storage@2.0.8
|
||||
- @thirdweb-dev/wallets@2.3.2
|
||||
- @thirdweb-dev/chains@0.1.62
|
||||
- @thirdweb-dev/sdk@4.0.23
|
||||
- @thirdweb-dev/auth@4.1.19
|
||||
|
||||
## 4.1.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2082](https://github.com/thirdweb-dev/js/pull/2082) [`699f31c2`](https://github.com/thirdweb-dev/js/commit/699f31c20a76cd284dbed1629c4a19d93aca7b7f) Thanks [@iketw](https://github.com/iketw)! - Better comments
|
||||
|
||||
- Updated dependencies [[`c701c388`](https://github.com/thirdweb-dev/js/commit/c701c388c65a1e531b88991d8fd67d25f153992e)]:
|
||||
- @thirdweb-dev/sdk@4.0.22
|
||||
- @thirdweb-dev/wallets@2.3.1
|
||||
- @thirdweb-dev/auth@4.1.18
|
||||
|
||||
## 4.1.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/react-core",
|
||||
"version": "4.1.15",
|
||||
"version": "4.2.2",
|
||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-core",
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"license": "Apache-2.0",
|
||||
|
||||
@@ -35,23 +35,120 @@ type NetworkMetadata = {
|
||||
* It's important to note that some wallet apps do not support programmatic network switching and switchNetwork will be undefined.
|
||||
* For those situations, you can typically switch networks in the wallet app this hook will still work.
|
||||
*
|
||||
* Hook for getting information about the current network and switching to a different network.
|
||||
*
|
||||
* Returns an array value containing two elements.
|
||||
*
|
||||
* 1. An object containing the following properties:
|
||||
*
|
||||
* - `data` object contains information about the wallet's current and supported networks.
|
||||
* - `loading` indicates if the switch network request is in progress.
|
||||
* - `error` holds the `Error` object if there was an error when attempting to switch network.
|
||||
*
|
||||
* 2. A function to switch to a different network.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* import { useNetwork } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const App = () => {
|
||||
* const [, switchNetwork] = useNetwork();
|
||||
* function App() {
|
||||
* const [{ data, error, loading }, switchNetwork] = useNetwork();
|
||||
*
|
||||
* return (
|
||||
* // switchNetwork is undefined if the wallet does not support programmatic network switching
|
||||
* // 137 is the chainId for Polygon in this example
|
||||
* <button onClick={() => switchNetwork(137)}>
|
||||
* Switch Network
|
||||
* <button
|
||||
* onClick={async () => {
|
||||
* if (!switchNetwork) {
|
||||
* console.log("can not switch network");
|
||||
* return;
|
||||
* }
|
||||
*
|
||||
* const result = await switchNetwork(80001);
|
||||
* if (result.data) {
|
||||
* console.log("Switched to Mumbai testnet successfully");
|
||||
* } else {
|
||||
* console.log("Error switching to Mumbai testnet", result.error);
|
||||
* }
|
||||
* }}
|
||||
* >
|
||||
* Switch to Mumbai
|
||||
* </button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @deprecated - use `useChain`, `useSwitchChain`, `useChainId` instead
|
||||
* @returns
|
||||
*
|
||||
* ```ts
|
||||
* const [{ data, error, loading }, switchNetwork] = useNetwork();
|
||||
* ```
|
||||
* #### data
|
||||
*
|
||||
* If wallet is connected to a network that is one of `supportedChains` provided in `ThirdwebProvider` or one of the default supported chains, `data` object will contain the following:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* chain: Chain; // The connected network
|
||||
* chains: Chain[]; // All supported networks
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* If wallet is connected to a network that is NOT one of `supportedChains` provided in `ThirdwebProvider` or default supported, `data` object will contain the following:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* // chainId of current connected network + unsupported flag
|
||||
* chain: { chainId: number, unsupported: true };
|
||||
* // All supported networks
|
||||
* chains: Chain[];
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* If wallet is not connected, `data` object will contain the following:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* chain: undefined;
|
||||
* chains: []; // Empty array
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* #### error
|
||||
*
|
||||
* `error` contains an `Error` object if there was an error when attempting to switch network using the `switchNetwork` function
|
||||
*
|
||||
* `undefined` if there is no switch network error
|
||||
*
|
||||
* ```ts
|
||||
* Error | undefined;
|
||||
* ```
|
||||
*
|
||||
* #### loading
|
||||
*
|
||||
* `loading` is `true` when switching network using the `switchNetwork` function, and `false` otherwise.
|
||||
*
|
||||
*
|
||||
* #### switchNetwork
|
||||
*
|
||||
* `switchNetwork` is a function to switch to a different network. It takes a `chainId` as an argument and returns a promise that resolves to an object containing `data` and `error` properties.
|
||||
*
|
||||
* If switching network was successful, `data` will contain the new network information. and `error` will be `undefined`. If switching network failed, `data` will be `undefined` and `error` will contain an `Error` object.
|
||||
*
|
||||
* `switchNetwork` is `undefined` if not connected to a wallet or if the connected wallet does not allow programmatic switching.
|
||||
*
|
||||
* ```ts
|
||||
* type SwitchNetwork = undefined | (chainId: number) => Promise<
|
||||
* | {
|
||||
* data: Chain | undefined;
|
||||
* error: undefined;
|
||||
* }
|
||||
* | {
|
||||
* data: undefined;
|
||||
* error: Error;
|
||||
* }>
|
||||
* ```
|
||||
*
|
||||
* @deprecated use `useChain`, `useSwitchChain`, `useChainId` instead
|
||||
* @internal
|
||||
*/
|
||||
export function useNetwork(): [NetworkMetadata, SwitchNetwork | undefined] {
|
||||
const chain = useChain();
|
||||
|
||||
@@ -28,7 +28,10 @@ import { WalletInstance } from "../types/wallet";
|
||||
|
||||
export type WalletId = (typeof walletIds)[keyof typeof walletIds];
|
||||
|
||||
type WalletIdToWalletTypeMap = {
|
||||
/**
|
||||
* @wallet
|
||||
*/
|
||||
export type WalletIdToWalletTypeMap = {
|
||||
metamask: MetaMaskWallet;
|
||||
coin98: Coin98Wallet;
|
||||
coinbase: CoinbaseWallet;
|
||||
@@ -54,12 +57,40 @@ type WalletIdToWalletTypeMap = {
|
||||
};
|
||||
|
||||
/**
|
||||
* @returns the current active wallet instance
|
||||
* Hook to get the instance of the currently connected wallet.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useWallet } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const walletInstance = useWallet();
|
||||
* }
|
||||
* ```
|
||||
* @returns Currently connected `WalletInstance` , or `undefined` if no wallet is connected.
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useWallet(): WalletInstance | undefined;
|
||||
|
||||
/**
|
||||
* Hook to get the instance of the currently connected wallet if it matches the given `walletId`.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useWallet } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const metamaskWalletInstance = useWallet('metamask');
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns Currently connected `WalletInstance` with given `walletId` , or `undefined` if no wallet is connected or if the connected wallet does not match the given `walletId`.
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useWallet<T extends WalletId>(
|
||||
walletId: T,
|
||||
): WalletIdToWalletTypeMap[T] | undefined;
|
||||
export function useWallet(): WalletInstance | undefined;
|
||||
|
||||
export function useWallet<T extends WalletId>(walletId?: T) {
|
||||
const context = useWalletContext();
|
||||
invariant(
|
||||
@@ -86,7 +117,27 @@ export function useWallet<T extends WalletId>(walletId?: T) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns the current active wallet's configuration object
|
||||
*
|
||||
* Hook to get the `WalletConfig` object of the currently connected wallet.
|
||||
*
|
||||
* This is useful to get metadata about the connected wallet, such as the wallet name, logo, etc
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useWalletConfig } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const walletConfig = useWalletConfig();
|
||||
*
|
||||
* const walletName = walletConfig?.meta.name;
|
||||
* const walletLogo = walletConfig?.meta.iconURL;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns The current connected wallet's configuration object or `undefined` if no wallet is connected.
|
||||
*
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useWalletConfig() {
|
||||
const context = useWalletContext();
|
||||
@@ -98,7 +149,8 @@ export function useWalletConfig() {
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @internal
|
||||
* Get `supportedWallets` passed in the `<ThirdwebProvider/>`
|
||||
* @returns `supportedWallets` configured in the `<ThirdwebProvider/>`
|
||||
*/
|
||||
export function useWallets() {
|
||||
@@ -111,8 +163,55 @@ export function useWallets() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for connecting a wallet to your app.
|
||||
*
|
||||
* @returns a method to connect to a wallet class
|
||||
* The wallet also needs to be added in `ThirdwebProvider`'s `supportedWallets` prop to enable auto-connection on page load.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useConnect, metamaskWallet } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const metamaskConfig = metamaskWallet();
|
||||
*
|
||||
* function App() {
|
||||
* const connect = useConnect();
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* onClick={async () => {
|
||||
* const wallet = await connect(metamaskConfig, connectOptions);
|
||||
* console.log("connected to ", wallet);
|
||||
* }}
|
||||
* >
|
||||
* Connect to MetaMask
|
||||
* </button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function to connect a wallet
|
||||
*
|
||||
* ```ts
|
||||
* const connect = useConnect();
|
||||
*
|
||||
* function handleConnect() {
|
||||
* const wallet = await connect(walletConfig, connectOptions);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* The function accepts two arguments: `walletConfig` and `connectOptions`
|
||||
*
|
||||
* #### walletConfig
|
||||
* The wallet to connect. Must be of type `WalletConfig`.
|
||||
*
|
||||
* [Learn more about the available wallet options](https://portal.thirdweb.com/react/v4/connecting-wallets).
|
||||
*
|
||||
* #### connectOptions
|
||||
* The typeof `connectOptions` object depends on the wallet you are connecting. For some wallets, it may be optional
|
||||
*
|
||||
* If you are using typescript, `connect` will automatically infer the type of `connectOptions` based on the `walletConfig` you pass in as the first argument and will show type errors if you pass in invalid options.
|
||||
*
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useConnect() {
|
||||
const context = useWalletContext();
|
||||
@@ -124,8 +223,21 @@ export function useConnect() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for disconnecting the currently connected wallet.
|
||||
*
|
||||
* @returns a method to disconnect from the current active wallet
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useDisconnect } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const disconnect = useDisconnect();
|
||||
*
|
||||
* return <button onClick={disconnect}>Disconnect</button>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function to disconnect from current connected wallet
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useDisconnect() {
|
||||
const context = useWalletContext();
|
||||
@@ -137,15 +249,32 @@ export function useDisconnect() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for checking whether your app is connected to a wallet or not.
|
||||
*
|
||||
* @returns the connection status of the wallet
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useConnectionStatus } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const connectionStatus = useConnectionStatus();
|
||||
*
|
||||
* if (connectionStatus === "unknown") return <p> Loading... </p>;
|
||||
* if (connectionStatus === "connecting") return <p> Connecting... </p>;
|
||||
* if (connectionStatus === "connected") return <p> You are connected </p>;
|
||||
* if (connectionStatus === "disconnected")
|
||||
* return <p> You are not connected to a wallet </p>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns The wallet connection status
|
||||
*
|
||||
* It can be one of the following:
|
||||
* 1. `unknown` - when wallet connection status is not yet known
|
||||
* 2. `connecting` - when wallet is connecting
|
||||
* 3. `connected` - when wallet is connected
|
||||
* 4. `disconnected` - when wallet is disconnected
|
||||
* - `unknown`: connection status is not known yet. This is the initial state.
|
||||
* - `connecting`: wallet is being connected. Either because of a user action, or when the wallet is auto-connecting on page load.
|
||||
* - `connected`: the wallet is connected and ready to be used.
|
||||
* - `disconnected`: the wallet is not connected.
|
||||
*
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useConnectionStatus() {
|
||||
const context = useWalletContext();
|
||||
@@ -157,8 +286,54 @@ export function useConnectionStatus() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for setting the `connectionStatus` of the wallet which is returned by the `useConnectionStatus` hook
|
||||
*
|
||||
* @returns a method to create an instance of given wallet class
|
||||
* This is only useful if you are manually connecting a wallet instance as mentioned in [Build your Wallet](https://portal.thirdweb.com/wallet-sdk/v2/build)
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* import {
|
||||
* useCreateWalletInstance,
|
||||
* useSetConnectionStatus,
|
||||
* useSetConnectedWallet,
|
||||
* metamaskWallet
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const walletConfig = metamaskWallet();
|
||||
*
|
||||
* function Example() {
|
||||
* const createWalletInstance = useCreateWalletInstance();
|
||||
* const setConnectionStatus = useSetConnectionStatus();
|
||||
* const setConnectedWallet = useSetConnectedWallet();
|
||||
*
|
||||
* // Call this function to connect your wallet
|
||||
* const handleConnect = async () => {
|
||||
* // 1. create instance
|
||||
* const walletInstance = createWalletInstance(walletConfig);
|
||||
* setConnectionStatus("connecting");
|
||||
*
|
||||
* try {
|
||||
* // 2. Call `connect` method of your wallet
|
||||
* await walletInstance.connect(
|
||||
* connectOptions, // if your wallet.connect method accepts any options, specify it here
|
||||
* );
|
||||
*
|
||||
* // 3. Set connected wallet
|
||||
* setConnectedWallet(walletInstance);
|
||||
* props.close();
|
||||
* } catch (e) {
|
||||
* setConnectionStatus("disconnected");
|
||||
* console.error("failed to connect", e);
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* return <div> ... </div>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function that sets the `connectionStatus` of the wallet
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useSetConnectionStatus() {
|
||||
const context = useWalletContext();
|
||||
@@ -170,8 +345,36 @@ export function useSetConnectionStatus() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for creating a wallet instance from given `WalletConfig` object.
|
||||
*
|
||||
* @returns a method to create an instance of given wallet class
|
||||
* If you just want to connect the wallet and don't need the wallet instance before connecting the wallet, use the `useConnect` hook instead.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useConnect, metamaskWallet } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const metamaskConfig = metamaskWallet();
|
||||
*
|
||||
* function App() {
|
||||
* const createWalletInstance = useCreateWalletInstance();
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* onClick={() => {
|
||||
* const metamaskWalletInstance = createWalletInstance(metamaskConfig);
|
||||
* console.log(metamaskWalletInstance);
|
||||
* }}
|
||||
* >
|
||||
* create wallet instance
|
||||
* </button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function that creates a wallet instance for given `WalletConfig` object.
|
||||
*
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useCreateWalletInstance() {
|
||||
const context = useWalletContext();
|
||||
@@ -183,8 +386,25 @@ export function useCreateWalletInstance() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for switching to a different network.
|
||||
*
|
||||
* @returns a method to connect the wallet to network/chain with given chainId
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useSwitchChain } from "@thirdweb-dev/react";
|
||||
* import { Goerli } from "@thirdweb-dev/chains";
|
||||
*
|
||||
* function App() {
|
||||
* const switchChain = useSwitchChain();
|
||||
* return (
|
||||
* <button onClick={() => switchChain(Goerli.chainId)}>
|
||||
* Switch to Goerli
|
||||
* </button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function to switch the network in the currently connected wallet to network with given `chainId`
|
||||
* @networkConnection
|
||||
*/
|
||||
export function useSwitchChain() {
|
||||
const context = useWalletContext();
|
||||
@@ -196,8 +416,54 @@ export function useSwitchChain() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for setting a wallet instance as "connected" - once done, the wallet connection hooks like `useWallet`, `useAddress`, `useSigner`, `useConnectionStatus` etc will return the data for that wallet instance
|
||||
*
|
||||
* @returns a method to set a connected wallet instance
|
||||
* This is only useful if you are manually connecting a wallet instance as mentioned in [Build your Wallet](https://portal.thirdweb.com/wallet-sdk/v2/build)
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```ts
|
||||
* import {
|
||||
* useCreateWalletInstance,
|
||||
* useSetConnectionStatus,
|
||||
* useSetConnectedWallet,
|
||||
* metamaskWallet
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const walletConfig = metamaskWallet();
|
||||
*
|
||||
* function Example() {
|
||||
* const createWalletInstance = useCreateWalletInstance();
|
||||
* const setConnectionStatus = useSetConnectionStatus();
|
||||
* const setConnectedWallet = useSetConnectedWallet();
|
||||
*
|
||||
* // Call this function to connect your wallet
|
||||
* const handleConnect = async () => {
|
||||
* // 1. create instance
|
||||
* const walletInstance = createWalletInstance(walletConfig);
|
||||
* setConnectionStatus("connecting");
|
||||
*
|
||||
* try {
|
||||
* // 2. Call `connect` method of your wallet
|
||||
* await walletInstance.connect(
|
||||
* connectOptions, // if your wallet.connect method accepts any options, specify it here
|
||||
* );
|
||||
*
|
||||
* // 3. Set connected wallet
|
||||
* setConnectedWallet(walletInstance);
|
||||
* props.close();
|
||||
* } catch (e) {
|
||||
* setConnectionStatus("disconnected");
|
||||
* console.error("failed to connect", e);
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* return <div> ... </div>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function to set a wallet instance as "connected".
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useSetConnectedWallet() {
|
||||
const context = useWalletContext();
|
||||
|
||||
@@ -84,11 +84,10 @@ export interface ThirdwebProviderCoreProps<TChains extends Chain[]>
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export const ThirdwebProviderCore = <TChains extends Chain[]>({
|
||||
createWalletStorage = createAsyncLocalStorage,
|
||||
...props
|
||||
}: React.PropsWithChildren<ThirdwebProviderCoreProps<TChains>>) => {
|
||||
const { activeChain } = props;
|
||||
export const ThirdwebProviderCore = <TChains extends Chain[]>(
|
||||
props: React.PropsWithChildren<ThirdwebProviderCoreProps<TChains>>,
|
||||
) => {
|
||||
const { activeChain, createWalletStorage = createAsyncLocalStorage } = props;
|
||||
|
||||
const supportedChains = (props.supportedChains || defaultChains) as Chain[];
|
||||
|
||||
|
||||
@@ -48,7 +48,11 @@ type WalletConnectParams<I extends WalletInstance> = Parameters<
|
||||
I["connect"]
|
||||
>[0];
|
||||
|
||||
type ConnectionStatus = "unknown" | "connected" | "disconnected" | "connecting";
|
||||
export type ConnectionStatus =
|
||||
| "unknown"
|
||||
| "connected"
|
||||
| "disconnected"
|
||||
| "connecting";
|
||||
|
||||
type ConnectFnArgs<I extends WalletInstance> =
|
||||
// if second argument is optional
|
||||
@@ -597,6 +601,9 @@ export function useWalletContext() {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get WalletConnect handler instance
|
||||
*/
|
||||
export function useWalletConnectHandler() {
|
||||
const ctx = useWalletContext();
|
||||
if (!ctx) {
|
||||
|
||||
@@ -2,20 +2,19 @@ import type { AbstractClientWallet, Chain } from "@thirdweb-dev/wallets";
|
||||
import { WalletOptions as WalletOptions_ } from "@thirdweb-dev/wallets";
|
||||
|
||||
// these are extra options provided by the react-core package
|
||||
export type ExtraCoreWalletOptions = {
|
||||
|
||||
export type WalletOptions = WalletOptions_<{
|
||||
chain: Chain;
|
||||
};
|
||||
|
||||
export type WalletOptions = WalletOptions_<ExtraCoreWalletOptions>;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* @wallet
|
||||
*/
|
||||
export type WalletInstance = AbstractClientWallet;
|
||||
|
||||
export type WalletClass<I extends WalletInstance = WalletInstance> = {
|
||||
id: string;
|
||||
new (options: WalletOptions): I;
|
||||
meta: (typeof AbstractClientWallet)["meta"];
|
||||
};
|
||||
|
||||
/**
|
||||
* @wallet
|
||||
*/
|
||||
export type WalletConfig<I extends WalletInstance = WalletInstance> = {
|
||||
category?: "socialLogin" | "walletLogin";
|
||||
id: string;
|
||||
@@ -56,6 +55,9 @@ export type WalletConfig<I extends WalletInstance = WalletInstance> = {
|
||||
isHeadless?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* @wallet
|
||||
*/
|
||||
export type ConnectUIProps<I extends WalletInstance = WalletInstance> = {
|
||||
/**
|
||||
* temporarily hide the ConnectModal
|
||||
@@ -156,11 +158,14 @@ export type ConnectUIProps<I extends WalletInstance = WalletInstance> = {
|
||||
/**
|
||||
* Called when the wallet is connected but it's
|
||||
* part of another wallet's connection flow.
|
||||
* @param walleInstance - the instance of the connected wallet
|
||||
* @param walleInstance - The instance of the connected wallet
|
||||
*/
|
||||
onLocallyConnected?: (walleInstance: WalletInstance) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* @wallet
|
||||
*/
|
||||
export type SelectUIProps<I extends WalletInstance = WalletInstance> = {
|
||||
/**
|
||||
* Call this function to "select" your wallet and render the screen for connecting the wallet
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
/**
|
||||
* Secure storage interface for storing auth tokens.
|
||||
*
|
||||
* The implementation of this interface should provide a secure way to store values. Either by encrypting the values or by storing them in a secure location.
|
||||
* @auth
|
||||
*/
|
||||
export interface ISecureStorage {
|
||||
getItem(key: string): Promise<string | null>;
|
||||
setItem(key: string, value: string): Promise<void>;
|
||||
@@ -7,8 +13,8 @@ export interface ISecureStorage {
|
||||
}
|
||||
|
||||
/**
|
||||
* The configuration to use the react SDK with an [auth](https://portal.thirdweb.com/auth) server.
|
||||
*
|
||||
* The configuration to use by the React and React Native SDKs with an [auth](https://portal.thirdweb.com/wallets/auth) server.
|
||||
* @auth
|
||||
*/
|
||||
export interface ThirdwebAuthConfig {
|
||||
/**
|
||||
@@ -41,6 +47,10 @@ export const ThirdwebAuthContext = /* @__PURE__ */ createContext<
|
||||
ThirdwebAuthContext | undefined
|
||||
>(undefined);
|
||||
|
||||
/**
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useThirdwebAuthContext() {
|
||||
return useContext(ThirdwebAuthContext);
|
||||
}
|
||||
|
||||
@@ -117,6 +117,10 @@ export const ThirdwebConnectedWalletProvider: React.FC<
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useThirdwebConnectedWalletContext() {
|
||||
const context = useContext(ThirdwebConnectedWalletContext);
|
||||
invariant(
|
||||
|
||||
@@ -30,10 +30,10 @@ import invariant from "tiny-invariant";
|
||||
* const { data: accounts, isLoading, error } = useAccounts(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account factory contract
|
||||
* @returns a response object that includes an array of all accounts with their associated admin
|
||||
* @param contract - Instance of a account factory contract
|
||||
* @returns Query result object that includes an array of all accounts with their associated admin
|
||||
* @twfeature AccountFactory
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useaccounts?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useAccounts(
|
||||
contract: RequiredParam<SmartContract>,
|
||||
@@ -61,10 +61,12 @@ export function useAccounts(
|
||||
* const { data: accountsForAddress, isLoading, error } = useAccountsForAddress(contract, "{{account_address}}");
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account factory contract
|
||||
* @returns a response object that includes an array of all accounts associated with the address
|
||||
* @param contract - Instance of a account factory contract
|
||||
* @param address - The address to get associated accounts for
|
||||
* @returns Query result object that includes an array of all accounts associated with the address
|
||||
*
|
||||
* @twfeature AccountFactory
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useaccountsforaddress?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useAccountsForAddress(
|
||||
contract: RequiredParam<SmartContract>,
|
||||
@@ -89,17 +91,17 @@ export function useAccountsForAddress(
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a account has been deployed for the given admin
|
||||
* Check if a account has been deployed for the given admin in the account factory contract
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: isAccountDeployed, isLoading, error } = useIsAccountDeployed(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account factory contract
|
||||
* @returns a boolean indicating if a account has been deployed for the given admin
|
||||
* @param contract - Instance of a account factory contract
|
||||
* @returns A boolean indicating if a account has been deployed for the given admin
|
||||
* @twfeature AccountFactory
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useisaccountdeployed?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useIsAccountDeployed(
|
||||
contract: RequiredParam<SmartContract>,
|
||||
@@ -126,7 +128,7 @@ export function useIsAccountDeployed(
|
||||
/** WRITE HOOKS **/
|
||||
/** **********************/
|
||||
/**
|
||||
* Create a account
|
||||
* Create a account in the account factory contract
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
@@ -153,10 +155,10 @@ export function useIsAccountDeployed(
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account factory contract
|
||||
* @returns a mutation object that can be used to create a account
|
||||
* @param contract - Instance of a account factory contract
|
||||
* @returns A mutation object to create a account
|
||||
* @twfeature AccountFactory
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecreateaccount?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useCreateAccount(contract: RequiredParam<SmartContract>) {
|
||||
const activeChainId = useSDKChainId();
|
||||
|
||||
@@ -31,10 +31,10 @@ import { useWallet } from "../../../core/hooks/wallet-hooks";
|
||||
* const { data: accounts, isLoading, error } = useAccountSigners(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account
|
||||
* @returns a response object that includes an array of all signers of the provided account
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @returns hook's `data` property contains an array of all signers
|
||||
* @twfeature Account
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useaccountsigners?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useAccountSigners(
|
||||
contract: RequiredParam<SmartContract>,
|
||||
@@ -55,17 +55,17 @@ export function useAccountSigners(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all admins of account
|
||||
* Get all the admins on a smart wallet account
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: accounts, isLoading, error } = useAccountSigners(contract);
|
||||
* const { data: accounts, isLoading, error } = useAccountAdmins(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account
|
||||
* @returns a response object that includes an array of all admins of the provided account
|
||||
* @param contract - Instance of `SmartContract`
|
||||
* @returns The hook's `data` property, once loaded, contains an array of all admins of the provided account
|
||||
* @twfeature Account
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useaccountadmins?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useAccountAdmins(
|
||||
contract: RequiredParam<SmartContract>,
|
||||
@@ -86,17 +86,19 @@ export function useAccountAdmins(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all signers and admins of account
|
||||
* Get all signers and admins on a smart wallet account.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: accounts, isLoading, error } = useAccountSigners(contract);
|
||||
* ```jsx
|
||||
* import { useAccountAdminsAndSigners } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const { data: accounts, isLoading, error } = useAccountAdminsAndSigners(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a account
|
||||
* @returns a response object that includes an array of all admins of the provided account
|
||||
* @param contract - Instance of `SmartContract`
|
||||
* @returns hook's `data` property containing an array of all admins and signers
|
||||
*
|
||||
* @twfeature Account
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useaccountadmins?utm_source=sdk | Documentation}
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useAccountAdminsAndSigners(
|
||||
contract: RequiredParam<SmartContract>,
|
||||
@@ -127,41 +129,67 @@ export type CreateSessionKeyInput = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Create and add a session key for the smart wallet
|
||||
* Create and add a session key for the smart wallet account
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const {
|
||||
* mutate: createSessionKey,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useCreateSessionKey();
|
||||
* const Component = () => {
|
||||
* const {
|
||||
* mutate: createSessionKey,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useCreateSessionKey();
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to create session key", error);
|
||||
* }
|
||||
* if (error) {
|
||||
* console.error("failed to create session key", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => createSessionKey(
|
||||
* "0x...",
|
||||
* {
|
||||
* approvedCallTargets: ["0x..."], // the addresses of contracts that the session key can call
|
||||
* nativeTokenLimitPerTransaction: 0.1, // the maximum amount of native token (in ETH) that the session key can spend per transaction
|
||||
* startDate: new Date(), // the date when the session key becomes active
|
||||
* expirationDate = new Date(Date.now() + 24 * 60 * 60 * 1000); // the date when the session key expires
|
||||
* }
|
||||
* )}
|
||||
* >
|
||||
* Create Session Key
|
||||
* </button>
|
||||
* );
|
||||
* };
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => createSessionKey(
|
||||
* keyAddress,
|
||||
* {
|
||||
* approvedCallTargets: ["0x..."], // the addresses of contracts that the session key can call
|
||||
* nativeTokenLimitPerTransaction: 0.1, // the maximum amount of native token (in ETH) that the session key can spend per transaction
|
||||
* startDate: new Date(), // the date when the session key becomes active
|
||||
* expirationDate = new Date(Date.now() + 24 * 60 * 60 * 1000); // the date when the session key expires
|
||||
* }
|
||||
* )}
|
||||
* >
|
||||
* Create Session Key
|
||||
* </button>
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @twfeature Account
|
||||
*
|
||||
* @returns Mutation object to create and add a session key for the smart wallet
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useCreateSessionKey();
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object with the following properties as argument:
|
||||
*
|
||||
* #### address
|
||||
* The address to add as an admin on the account as a `string`.
|
||||
*
|
||||
* #### approvedCallTargets
|
||||
* An array of addresses that the session key can call as a `string[]`.
|
||||
*
|
||||
* #### nativeTokenLimitPerTransaction
|
||||
* The maximum amount of native token (in ETH) that the session key can spend per transaction as a `number`.
|
||||
*
|
||||
* #### startDate
|
||||
* The date when the session key becomes active as a `Date`.
|
||||
*
|
||||
* #### startDate
|
||||
* The date when the session key expires as a `Date`.
|
||||
*
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useCreateSessionKey(): UseMutationResult<
|
||||
TransactionResult,
|
||||
@@ -176,26 +204,24 @@ export function useCreateSessionKey(): UseMutationResult<
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a session key on the smart wallet
|
||||
* Revoke a session key (or signer) on the smart wallet account
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useRevokeSessionKey } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // Your ERC20 token smart contract address
|
||||
* const keyAddress = "{{key_address}}";
|
||||
*
|
||||
* const Component = () => {
|
||||
* const {
|
||||
* mutate: revokeSessionKey,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useRevokeSessionKey();
|
||||
* const { mutate: revokeSessionKey, isLoading, error } = useRevokeSessionKey();
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to revoke session key", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => revokeSessionKey("0x...")}
|
||||
* >
|
||||
* <button disabled={isLoading} onClick={() => revokeSessionKey(keyAddress)}>
|
||||
* Revoke Session Key
|
||||
* </button>
|
||||
* );
|
||||
@@ -203,6 +229,16 @@ export function useCreateSessionKey(): UseMutationResult<
|
||||
* ```
|
||||
*
|
||||
* @twfeature Account
|
||||
* @returns
|
||||
* Mutation object to revoke a session key (or signer) on the smart wallet
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useRevokeSessionKey();
|
||||
* ```
|
||||
*
|
||||
* The mutation function takes an address of type `string` to remove as an admin.
|
||||
*
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useRevokeSessionKey(): UseMutationResult<
|
||||
TransactionResult,
|
||||
@@ -217,33 +253,33 @@ export function useRevokeSessionKey(): UseMutationResult<
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an additional admin on the smart wallet
|
||||
* Add an additional admin on the smart wallet account
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useAddAdmin } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const adminAddress = "{{admin_address}}";
|
||||
*
|
||||
* const Component = () => {
|
||||
* const {
|
||||
* mutate: addAdmin,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useAddAdmin();
|
||||
* const { mutate: addAdmin, isLoading, error } = useAddAdmin();
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to add admin", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => addAdmin("0x...")}
|
||||
* >
|
||||
* <button disabled={isLoading} onClick={() => addAdmin(adminAddress)}>
|
||||
* Add admin
|
||||
* </button>
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @returns mutation object to add given address as an admin
|
||||
*
|
||||
* @twfeature Account
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useAddAdmin(): UseMutationResult<
|
||||
TransactionResult,
|
||||
@@ -258,26 +294,22 @@ export function useAddAdmin(): UseMutationResult<
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an additional admin on the smart wallet
|
||||
* Remove an admin on the smart wallet account. This action has to be performed by an admin on the account.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useRemoveAdmin } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const adminAddress = "{{admin_address}}";
|
||||
*
|
||||
* const Component = () => {
|
||||
* const {
|
||||
* mutate: removeAdmin,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useRemoveAdmin();
|
||||
* const { mutate: removeAdmin, isLoading, error } = useRemoveAdmin();
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to remove admin", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => removeAdmin("0x...")}
|
||||
* >
|
||||
* <button disabled={isLoading} onClick={() => removeAdmin(adminAddress)}>
|
||||
* Remove admin
|
||||
* </button>
|
||||
* );
|
||||
@@ -285,6 +317,8 @@ export function useAddAdmin(): UseMutationResult<
|
||||
* ```
|
||||
*
|
||||
* @twfeature Account
|
||||
* @returns mutation object to remove given address as an admin
|
||||
* @smartWallet
|
||||
*/
|
||||
export function useRemoveAdmin(): UseMutationResult<
|
||||
TransactionResult,
|
||||
|
||||
@@ -18,16 +18,17 @@ import type { providers } from "ethers";
|
||||
import invariant from "tiny-invariant";
|
||||
|
||||
/**
|
||||
* Get App URI
|
||||
* Get App URI of the contract
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: contractMetadata, isLoading, error } = useAppURI(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - the {@link SmartContract} instance of the contract to get the appURI of
|
||||
* @returns a response object that includes the appURI of the contract
|
||||
* @param contract - The `SmartContract` instance of the contract to get the appURI of
|
||||
* @returns Query result object that includes the appURI of the contract
|
||||
* @twfeature AppURI
|
||||
* @appURI
|
||||
*/
|
||||
export function useAppURI<TContract extends ValidContractInstance>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -46,7 +47,7 @@ export function useAppURI<TContract extends ValidContractInstance>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Set App URI
|
||||
* Set App URI of the contract
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
@@ -71,9 +72,11 @@ export function useAppURI<TContract extends ValidContractInstance>(
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to update the appURI of a contract
|
||||
* @twfeature AppUR
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @returns A mutation object to update the appURI of a contract
|
||||
*
|
||||
* @twfeature AppURI
|
||||
* @appURI
|
||||
*/
|
||||
export function useSetAppURI(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
|
||||
@@ -28,8 +28,8 @@ import { constants, utils } from "ethers";
|
||||
import invariant from "tiny-invariant";
|
||||
|
||||
/**
|
||||
* The options to be passed as the second parameter to the {@link useClaimIneligibilityReasons} hook.
|
||||
*
|
||||
* The options to be passed as the second parameter to the `useClaimIneligibilityReasons` hook.
|
||||
* @claimConditions
|
||||
*/
|
||||
export type ClaimIneligibilityParams = {
|
||||
// the wallet address to check claim eligibility for
|
||||
@@ -40,10 +40,22 @@ export type ClaimIneligibilityParams = {
|
||||
|
||||
/**
|
||||
* The params for the {@link useSetClaimConditions} hook mutation.
|
||||
*
|
||||
* @claimConditions
|
||||
*/
|
||||
export type SetClaimConditionsParams = {
|
||||
/**
|
||||
* An array of phases that occur in chronological order.
|
||||
*/
|
||||
phases: ClaimConditionInput[];
|
||||
/**
|
||||
* A boolean value that determines whether to reset the claim conditions or to keep the existing state.
|
||||
* By resetting them, any previous claims that were made will be ignored by the claim condition restrictions.
|
||||
*
|
||||
* For example, if you had a limit of 1 token per wallet, and a user claimed a token, then you reset the claim conditions, that user will be able to claim another token.
|
||||
*
|
||||
* Default value is `false`.
|
||||
*
|
||||
*/
|
||||
reset?: boolean;
|
||||
};
|
||||
|
||||
@@ -52,18 +64,73 @@ export type SetClaimConditionsParams = {
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Get the active claim condition
|
||||
* Hook for getting the active claim condition for a given drop contract.
|
||||
*
|
||||
* Available for contracts that implement the "ClaimConditions" interface;
|
||||
* such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: activeClaimCondition, isLoading, error } = useActiveClaimCondition(contract);
|
||||
* import { useActiveClaimCondition, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useActiveClaimCondition(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension.
|
||||
* @param tokenId - the id of the token to fetch the claim conditions for (if the contract is an ERC1155 contract)
|
||||
* @returns a response object with the currently active claim condition
|
||||
* @param contract -
|
||||
* Instance of contract that implement the "ClaimConditions" interface;
|
||||
* such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* @param tokenId -
|
||||
* When using the hook with ERC1155 contracts such as the [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), pass the `tokenId` as the second parameter; as each token can have unique claim conditions.
|
||||
*
|
||||
* Pass `undefined`, or leave this field out if you are using ERC721 or ERC20 drop contracts.
|
||||
*
|
||||
* ```tsx
|
||||
* import { useActiveClaimCondition, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
*
|
||||
* // "data" now includes a "snapshot" property that contains the allowlist.
|
||||
* const { data, isLoading, error } = useActiveClaimCondition(
|
||||
* contract,
|
||||
* 0, // Token ID required for ERC1155 contracts here.
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param options - Additional options to pass to the claim condition fetch
|
||||
*
|
||||
* #### withAllowlist
|
||||
*
|
||||
* By default, the hook will not include the allowlist or "snapshot" in the returned data. To include the allowlist in the returned data, pass `withAllowlist: true` in options object.
|
||||
*
|
||||
* This will add a snapshot property to the returned data, which contains the allowlist in an array.
|
||||
*
|
||||
* ```tsx
|
||||
* import { useActiveClaimCondition, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
*
|
||||
* // "data" now includes a "snapshot" property that contains the allowlist.
|
||||
* const { data, isLoading, error } = useActiveClaimCondition(
|
||||
* contract,
|
||||
* undefined, // Token ID required for ERC1155 contracts here.
|
||||
* {
|
||||
* withAllowlist: true,
|
||||
* },
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A query result object with the currently active claim condition
|
||||
*
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useactiveclaimcondition?utm_source=sdk | Documentation}
|
||||
* @claimConditions
|
||||
*/
|
||||
export function useActiveClaimCondition(
|
||||
contract: RequiredParam<DropContract>,
|
||||
@@ -105,27 +172,63 @@ export function useActiveClaimCondition(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get claimer proofs
|
||||
* Hook to get the claimer proofs for an address for [ERC20](https://portal.thirdweb.com/contracts/build/base-contracts/erc-20/drop), [ERC721](https://portal.thirdweb.com/contracts/build/base-contracts/erc-721/drop), and [ERC1155](https://portal.thirdweb.com/contracts/build/base-contracts/erc-1155/drop) drop contracts.
|
||||
*
|
||||
* A claimer proof is a set of data about a claimer's claim condition, including the claimer's address, the claimer's proof, and the claimer's max claimable amount, price, and currency address.
|
||||
*
|
||||
* This is available for available for contracts that implement the "ClaimConditions" interface; such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: claimerProofs, isLoading, error } = useClaimerProofs(contract);
|
||||
* import { useClaimerProofs, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
*
|
||||
* const {
|
||||
* data: proof,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useClaimerProofs(contract, "{{claimer_address}}");
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension.
|
||||
* @param claimerAddress - the address of the claimer to fetch the claimer proofs for
|
||||
* @param tokenId - the id of the token to fetch the claimer proofs for (if the contract is an ERC1155 contract)
|
||||
* @param claimConditionId - optional the claim condition id to get the proofs for
|
||||
* @returns a response object with the snapshot for the provided address
|
||||
* @param contract -
|
||||
* Instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the "ClaimConditions" extension.
|
||||
*
|
||||
* @param claimerAddress -
|
||||
* This is the address of the user you want to get the proof for.
|
||||
*
|
||||
* Likely, you will want to check proofs of the currently connected wallet address. You can use the `useAddress` hook to get this value.
|
||||
*
|
||||
* @param tokenId -
|
||||
* When using the hook with ERC1155 contracts, pass the `tokenId`; as each token can have unique claim conditions.
|
||||
*
|
||||
* Pass `undefined`, or leave this field out if you are using ERC721 or ERC20 drop contracts.
|
||||
*
|
||||
* @param claimConditionId -
|
||||
* This is the ID of the claim condition you want to get the proof for.
|
||||
*
|
||||
* @returns Query result object with the snapshot for the provided address
|
||||
*
|
||||
* @claimConditions
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimerproofs?utm_source=sdk | Documentation}
|
||||
*/
|
||||
export function useClaimerProofs(
|
||||
contract: RequiredParam<DropContract>,
|
||||
claimerAddress: string,
|
||||
tokenId?: BigNumberish,
|
||||
claimConditionId?: BigNumberish,
|
||||
) {
|
||||
): UseQueryResult<
|
||||
{
|
||||
address: string;
|
||||
proof: string[];
|
||||
maxClaimable: string;
|
||||
price?: string | undefined;
|
||||
currencyAddress?: string | undefined;
|
||||
} | null,
|
||||
unknown
|
||||
> {
|
||||
const contractAddress = contract?.getAddress();
|
||||
const { erc1155, erc721, erc20 } = getErcs(contract);
|
||||
|
||||
@@ -170,18 +273,69 @@ export function useClaimerProofs(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all claim conditions
|
||||
* Hook for fetching all claim conditions for a given drop contract.
|
||||
*
|
||||
* This is available for available for contracts that implement the "ClaimConditions" interface; such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: claimConditions, isLoading, error } = useClaimConditions(contract);
|
||||
* import { useClaimConditions, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useClaimConditions(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension.
|
||||
* @param tokenId - the id of the token to fetch the claim conditions for (if the contract is an ERC1155 contract)
|
||||
* @returns a response object with the list of claim conditions
|
||||
* @param contract - Instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the "ClaimConditions" extension.
|
||||
*
|
||||
* @param tokenId -
|
||||
* When using the hook with ERC1155 contracts, pass the `tokenId` parameter; as each token can have unique claim conditions.
|
||||
*
|
||||
* Pass `undefined`, or leave this field out if you are using ERC721 or ERC20 drop contracts.
|
||||
*
|
||||
* ```tsx
|
||||
* import { useClaimConditions, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
*
|
||||
* const { data, isLoading, error } = useClaimConditions(
|
||||
* contract,
|
||||
* 0, // Token ID required for ERC1155 contracts here.
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param options - additional options to pass to the claim condition fetch
|
||||
*
|
||||
* #### withAllowlist
|
||||
*
|
||||
* By default, the hook will not include the allowlist in the returned data. To include the allowlist in the returned data, set the `withAllowlist` option to true.
|
||||
*
|
||||
* This will add a `snapshot` property to the returned data, which contains the allowlist in an array.
|
||||
*
|
||||
* ```tsx
|
||||
* import { useClaimConditions, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
*
|
||||
* // "data" now includes a "snapshot" property that contains the allowlist.
|
||||
* const { data, isLoading, error } = useClaimConditions(
|
||||
* contract,
|
||||
* undefined, // Token ID required for ERC1155 contracts here.
|
||||
* {
|
||||
* withAllowlist: true,
|
||||
* },
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns Query Result object with the list of claim conditions
|
||||
*
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimconditions?utm_source=sdk | Documentation}
|
||||
* @claimConditions
|
||||
*/
|
||||
export function useClaimConditions(
|
||||
contract: RequiredParam<DropContract>,
|
||||
@@ -223,19 +377,58 @@ export function useClaimConditions(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the reasons why a specific wallet can't claim
|
||||
* Hook for fetching the reasons a wallet is not eligible to claim tokens from a drop, if any.
|
||||
*
|
||||
* This is available for available for contracts that implement the "ClaimConditions" interface; such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: claimIneligibilityReasons, isLoading, error } = useClaimIneligibilityReasons(contract, { walletAddress: "{{wallet_address}}" });
|
||||
* import { useClaimIneligibilityReasons, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useClaimIneligibilityReasons(contract, {
|
||||
* walletAddress: "0x123...", // Use useAddress hook to get the user's wallet address
|
||||
* quantity: 1, // Quantity to check eligibility for
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC20, ERC721 or ERC1155 spec and implements the `claimConditions` extension.
|
||||
* @param eligibilityParams - the parameters for the eligibility check, see: {@link ClaimIneligibilityParams}
|
||||
* @param tokenId - the id of the token to fetch the claim conditions for (if the contract is an ERC1155 contract)
|
||||
* @returns a response object with the reasons for the claim ineligibility
|
||||
* @param contract - Instance of a contract that extends the ERC20, ERC721 or ERC1155 spec and implements the "ClaimConditions" extension.
|
||||
*
|
||||
* @param params -
|
||||
* The conditions to check eligibility for. The `walletAddress` and `quantity` properties are required.
|
||||
*
|
||||
* Use the `useAddress` hook to get the connected wallet address.
|
||||
*
|
||||
* @param tokenId -
|
||||
* When using ERC1155 contracts, provide a third argument to specify the token ID.
|
||||
*
|
||||
* ```tsx
|
||||
* import { useClaimIneligibilityReasons, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useClaimIneligibilityReasons(
|
||||
* contract,
|
||||
* {
|
||||
* walletAddress: "0x123..",
|
||||
* quantity: 1,
|
||||
* },
|
||||
* tokenId,
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, contains an array of `ClaimEligibility` strings, which may be empty.
|
||||
*
|
||||
* For example, if the user is not in the allowlist, this hook will return `["This address is not on the allowlist."]`.
|
||||
*
|
||||
* If the user is eligible to claim tokens, the hook will return an empty array.
|
||||
*
|
||||
* @claimConditions
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimineligibilityreasons?utm_source=sdk | Documentation}
|
||||
*/
|
||||
export function useClaimIneligibilityReasons(
|
||||
contract: RequiredParam<DropContract>,
|
||||
@@ -292,19 +485,50 @@ export function useClaimIneligibilityReasons(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the active claim condition for a specific wallet
|
||||
* Hook for getting the active claim condition on a drop contract for a specific wallet address.
|
||||
*
|
||||
* Each wallet address can have unique claim conditions at any given time. This hook allows you to get the active claim condition for a specific wallet address at this time.
|
||||
*
|
||||
* This is available for available for contracts that implement the "ClaimConditions" interface; such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* ---
|
||||
*
|
||||
* - Returns the claim condition specific to the wallet address if found in the claimer snapshot.
|
||||
* - Returns the default claim condition on the contract if the address is not found in the claimer snapshot.
|
||||
* - Populates the error field if there is no active claim condition on the contract.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: activeClaimConditionForWallet, isLoading, error } = useActiveClaimConditionForWallet(contract, "{{wallet_address}}");
|
||||
* import {
|
||||
* useActiveClaimConditionForWallet,
|
||||
* useContract,
|
||||
* useAddress,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const address = useAddress();
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useActiveClaimConditionForWallet(
|
||||
* contract,
|
||||
* address,
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC20, ERC721 or ERC1155 spec and implements the `claimConditions` extension.
|
||||
* @param walletAddress - the wallet address to check the active claim condition for
|
||||
* @param tokenId - the id of the token to fetch the claim conditions for (if the contract is an ERC1155 contract)
|
||||
* @returns the active claim condition for the wallet address or null if there is no active claim condition
|
||||
* @param contract - Instance of a contract that extends the ERC20, ERC721 or ERC1155 spec and implements the "ClaimConditions" extension.
|
||||
*
|
||||
* @param walletAddress -
|
||||
* The wallet address to check the active claim condition for. You can use the `useAddress` hook to get the currently connected wallet's address.
|
||||
*
|
||||
* @param tokenId -
|
||||
* When using the hook with ERC1155 contracts, pass the `tokenId` as the third parameter; as each token can have unique claim conditions.
|
||||
*
|
||||
* Pass `undefined`, or leave this field out if you are using ERC721 or ERC20 drop contracts.
|
||||
*
|
||||
* @returns The active claim condition for the wallet address or `null` if there is no active claim condition
|
||||
*
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useactiveclaimconditionforwallet?utm_source=sdk | Documentation}
|
||||
* @claimConditions
|
||||
*/
|
||||
export function useActiveClaimConditionForWallet(
|
||||
contract: RequiredParam<DropContract>,
|
||||
@@ -429,37 +653,177 @@ export function useActiveClaimConditionForWallet(
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Set claim conditions
|
||||
* Hook for setting claim conditions on a drop contract.
|
||||
*
|
||||
* This is available for available for contracts that implement the "ClaimConditions" interface; such as [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721), [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155), and [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* When using an ERC1155 contract, you must also provide the token ID of the NFT you want to set claim conditions on as the second parameter to the hook.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* ```tsx
|
||||
* import {
|
||||
* useSetClaimConditions,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: setClaimConditions,
|
||||
* mutateAsync: setClaimConditions,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useSetClaimConditions(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to set claim conditions", error);
|
||||
* const claimConditions = {
|
||||
* phases: [
|
||||
* {
|
||||
* metadata: {
|
||||
* name: "Phase 1", // The name of the phase
|
||||
* },
|
||||
* currencyAddress: "0x...", // The address of the currency you want users to pay in
|
||||
* price: 1, // The price of the token in the currency specified above
|
||||
* maxClaimablePerWallet: 1, // The maximum number of tokens a wallet can claim
|
||||
* maxClaimableSupply: 100, // The total number of tokens that can be claimed in this phase
|
||||
* startTime: new Date(), // When the phase starts (i.e. when users can start claiming tokens)
|
||||
* waitInSeconds: 60 * 60 * 24 * 7, // The period of time users must wait between repeat claims
|
||||
* snapshot: [
|
||||
* {
|
||||
* address: "0x...", // The address of the wallet
|
||||
* currencyAddress: "0x...", // Override the currency address this wallet pays in
|
||||
* maxClaimable: 5, // Override the maximum number of tokens this wallet can claim
|
||||
* price: 0.5, // Override the price this wallet pays
|
||||
* },
|
||||
* ],
|
||||
* merkleRootHash: "0x...", // The merkle root hash of the snapshot
|
||||
* },
|
||||
* ],
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => setClaimConditions({ phases: [{ price: 2, maxClaimableSupply: 100 }] })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() => setClaimConditions(claimConditions)}
|
||||
* >
|
||||
* Set Claim Conditions!
|
||||
* </button>
|
||||
* Set Claim Conditions
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link DropContract}
|
||||
* @returns a mutation object that can be used to set claim conditions
|
||||
* @param contract - Instance of a {@link DropContract}
|
||||
* @returns
|
||||
*
|
||||
* A Mutation object to set claim conditions
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useSetClaimConditions(contract);
|
||||
*
|
||||
* function setPhases(phases) {
|
||||
* mutateAsync({
|
||||
* phases,
|
||||
* });
|
||||
* }
|
||||
*
|
||||
* function reset() {
|
||||
* mutateAsync({
|
||||
* reset: true,
|
||||
* })
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an object with two possible properties:
|
||||
*
|
||||
* 1. `reset` - A boolean that determines whether to reset the claim conditions. This means you reset any previous claim conditions that existed and allow users to claim again as if the drop had just started.
|
||||
* 2. `phases` - An array of claim phases that occur in chronological order. You can only have one phase occur at a time. All properties of a phase are optional, with the default being a free, open, unlimited claim, in the native currency, starting immediately.
|
||||
*
|
||||
* ---
|
||||
*
|
||||
* #### reset (optional)
|
||||
*
|
||||
* A boolean value that determines whether to reset the claim conditions or to keep the existing state.
|
||||
*
|
||||
* By resetting them, any previous claims that were made will be ignored by the claim condition restrictions.
|
||||
*
|
||||
* For example, if you had a limit of 1 token per wallet, and a user claimed a token, then you reset the claim conditions, that user will be able to claim another token.
|
||||
*
|
||||
* Default value is `false`.
|
||||
*
|
||||
* ---
|
||||
*
|
||||
* #### phases (required)
|
||||
*
|
||||
* Provide an array of phases that occur in chronological order. All properties of a phase are optional and are described below:
|
||||
*
|
||||
* ##### metadata
|
||||
*
|
||||
* An object representing the metadata of the phase. This is only for display purposes in the dashboard and isn’t used elsewhere.
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* name: string;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ##### currencyAddress
|
||||
*
|
||||
* The address of the currency you want users to pay in.
|
||||
*
|
||||
* This can be any ERC20 token value. If you want users to pay in the native currency (e.g. Ether on Ethereum), you can import the `NATIVE_TOKEN_ADDRESS` constant from `@thirdweb-dev/sdk`. The default value is `NATIVE_TOKEN_ADDRESS`.
|
||||
*
|
||||
* ##### price
|
||||
*
|
||||
* The price per token in the currency specified above. The default value is `0`.
|
||||
*
|
||||
* ##### maxClaimablePerWallet
|
||||
*
|
||||
* The maximum number of tokens a wallet can claim. The default value is `"unlimited"`
|
||||
*
|
||||
* ##### maxClaimableSupply
|
||||
*
|
||||
* The total number of tokens that can be claimed in this phase.
|
||||
*
|
||||
* For example, if you lazy mint 1000 tokens and set the `maxClaimableSupply` to 100, then only 100 tokens will be claimable in this phase, leaving 900 tokens to be claimed in the next phases (if you have any).
|
||||
*
|
||||
* This is useful for "early bird" use cases, where you allow users to claim a limited number of tokens at a discounted price during the first X amount of time.
|
||||
*
|
||||
* ##### startTime
|
||||
*
|
||||
* When the phase starts (i.e. when users can start claiming tokens).
|
||||
*
|
||||
* The default value is `"immediately"`.
|
||||
*
|
||||
* ##### waitInSeconds
|
||||
*
|
||||
* The amount of time between claims a wallet must wait before they can claim again.
|
||||
*
|
||||
* The default value is `0`, meaning users can claim again immediately after claiming.
|
||||
*
|
||||
* ##### snapshot
|
||||
*
|
||||
* A list of wallets that you want to override the default claim conditions for.
|
||||
*
|
||||
* Wallet addresses within this list can be set to pay in a different currency, have a different price, and have a different maximum claimable amount.
|
||||
*
|
||||
* ```jsx
|
||||
* {
|
||||
* address: string;
|
||||
* currencyAddress?: string;
|
||||
* maxClaimable?: number;
|
||||
* price?: number;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* [Learn more about improving claim conditions](https://blog.thirdweb.com/announcing-improved-claim-conditions/)
|
||||
*
|
||||
* ##### merkleRootHash
|
||||
*
|
||||
* If you want to provide your own merkle tree for your snapshot, provide the merkle root hash here. This is only recommended for advanced use cases.
|
||||
*
|
||||
* @claimConditions
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usesetclaimconditions?utm_source=sdk | Documentation}
|
||||
*/
|
||||
export function useSetClaimConditions(
|
||||
contract: RequiredParam<DropContract>,
|
||||
@@ -508,36 +872,45 @@ export function useSetClaimConditions(
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset claim conditions
|
||||
* Hook for resetting the claim conditions on a drop contract.
|
||||
*
|
||||
* Available to use on contracts that implement
|
||||
* [`ERC721ClaimableWithConditions`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721ClaimConditions),
|
||||
* [`ERC1155ClaimableWithConditions`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155ClaimConditions) or
|
||||
* [`ERC20ClaimableWithConditions`](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20ClaimConditions).
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import {
|
||||
* useContract,
|
||||
* useResetClaimConditions,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* // Contract must be a drop contract that implements claim conditions
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: resetClaimConditions,
|
||||
* mutateAsync: resetClaimConditions,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useResetClaimConditions(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to reset claim conditions", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={resetClaimConditions}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() => resetClaimConditions()}
|
||||
* >
|
||||
* Reset Claim Conditions
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link DropContract}
|
||||
* @returns a mutation object that can be used to reset claim conditions
|
||||
* @param contract - Instance of a `DropContract`
|
||||
* @param tokenId - For ERC1155 NFTs, provide the token ID of the NFT as the second argument to the hook.
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useResetClaimConditions(
|
||||
contract: RequiredParam<DropContract>,
|
||||
|
||||
@@ -25,18 +25,26 @@ import invariant from "tiny-invariant";
|
||||
// primary sales
|
||||
|
||||
/**
|
||||
* Get the primary sale recipient
|
||||
* Hook for getting the primary sales recipient of a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [`PrimarySale`](https://portal.thirdweb.com/contracts/build/extensions/general/PrimarySale) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const { data: primarySaleRecipient, isLoading, error } = usePrimarySalesRecipient(contract);
|
||||
* import { useContract, usePrimarySaleRecipient } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = usePrimarySaleRecipient(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Use this to get the primary sales recipient of your {@link SmartContract}
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns the wallet address of the primary sales recipient
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns The hook's `data` property, once loaded, is a `string` with the wallet address of the primary sales recipient.
|
||||
*
|
||||
* @twfeature PrimarySale
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useprimarysalerecipient?utm_source=sdk | Documentation}
|
||||
* @platformFees
|
||||
*/
|
||||
export function usePrimarySaleRecipient(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -57,37 +65,56 @@ export function usePrimarySaleRecipient(
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the primary sale recipient
|
||||
* Hook for updating the primary sale recipient on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`PrimarySale`](https://portal.thirdweb.com/contracts/build/extensions/general/PrimarySale) interface.
|
||||
*
|
||||
* The wallet that initiates this transaction must have the required permissions to change the primary sale recipient (defaults to `"admin"` level).
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import {
|
||||
* useUpdatePrimarySaleRecipient,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: updatePrimarySalesRecipient,
|
||||
* mutateAsync: updatePrimarySaleRecipient,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useUpdatePrimarySaleRecipient(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to update recipient", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => updatePrimarySalesRecipient({ newRecipient: "{{wallet_address}}" })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() => updatePrimarySaleRecipient("{{wallet_address}}")}
|
||||
* >
|
||||
* Update Recipient
|
||||
* </button>
|
||||
* Update Primary Sale Recipient
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to update the primary sales recipient
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @returns A mutation object to update the primary sales recipient
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useUpdatePrimarySaleRecipient(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes a `walletAddress` as argument:
|
||||
*
|
||||
* #### walletAddress
|
||||
*
|
||||
* The wallet address to set as the primary sale recipient.
|
||||
*
|
||||
* @twfeature PrimarySale
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useupdateprimarysalerecipient?utm_source=sdk | Documentation}
|
||||
* @platformFees
|
||||
*/
|
||||
export function useUpdatePrimarySaleRecipient(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -127,21 +154,48 @@ export function useUpdatePrimarySaleRecipient(
|
||||
// royalties
|
||||
|
||||
/**
|
||||
* Get the royalty recipient and fee
|
||||
* Hook for retrieving royalty settings of a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [`Royalty`](https://portal.thirdweb.com/contracts/build/extensions/general/Royalty) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const { data: settings, isLoading, error } = useRoyaltySettings(contract);
|
||||
* import { useContract, useRoyaltySettings } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useRoyaltySettings(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns an object containing recipient address and the royalty basis points
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, is an object with two properties:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* seller_fee_basis_points: number;
|
||||
* fee_recipient: string;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* - The `seller_fee_basis_points` is the royalty amount (in basis points) that the seller
|
||||
* will receive for each token sale on secondary markets.
|
||||
* - The `fee_recipient` is the wallet address that will receive the royalty payments.
|
||||
*
|
||||
* @twfeature Royalty
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useroyaltysettings?utm_source=sdk | Documentation}
|
||||
* @platformFees
|
||||
*/
|
||||
export function useRoyaltySettings(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
) {
|
||||
): UseQueryResult<
|
||||
{
|
||||
seller_fee_basis_points: number;
|
||||
fee_recipient: string;
|
||||
},
|
||||
unknown
|
||||
> {
|
||||
const contractAddress = contract?.getAddress();
|
||||
return useQueryWithNetwork(
|
||||
cacheKeys.extensions.royalties.getDefaultRoyaltyInfo(contractAddress),
|
||||
@@ -158,37 +212,67 @@ export function useRoyaltySettings(
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the royalty recipient and fee
|
||||
* Hook for updating royalty settings on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`Royalty`](https://portal.thirdweb.com/contracts/build/extensions/general/Royalty) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import {
|
||||
* useUpdateRoyaltySettings,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: updateRoyaltySettings,
|
||||
* mutateAsync: updateRoyaltySettings,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useUpdateRoyaltySettings(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to update royalty settings", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => updateRoyaltySettings({ updatePayload: { fee_recipient: "{{wallet_address}}", seller_fee_basis_points: 5_00 } })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* updateRoyaltySettings({
|
||||
* seller_fee_basis_points: 0,
|
||||
* fee_recipient: "{{wallet_address}}",
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Update Royalty Settings
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to update the royalty settings
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns
|
||||
* A mutation object to update the royalty settings
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useUpdateRoyaltySettings(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an object with below properties:
|
||||
*
|
||||
* #### seller_fee_basis_points
|
||||
*
|
||||
* The `seller_fee_basis_points` property is a `number` between `0` - `10000` that defines the fee rate.
|
||||
*
|
||||
* This number is in percentage points. i.e. `100` is a 1% fee and `10000` is a 100% fee.
|
||||
*
|
||||
* #### fee_recipient
|
||||
*
|
||||
* The `fee_recipient` property is the address of the wallet that will receive the fees.
|
||||
*
|
||||
* @twfeature Royalty
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useupdateroyaltysettings?utm_source=sdk | Documentation}
|
||||
* @platformFees
|
||||
*/
|
||||
export function useUpdateRoyaltySettings(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -224,21 +308,50 @@ export function useUpdateRoyaltySettings(
|
||||
// platformFees
|
||||
|
||||
/**
|
||||
* Get the platform fee recipient and basis points
|
||||
* Hook for getting the platform fee settings of a contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [`PlatformFee`](https://portal.thirdweb.com/contracts/build/extensions/general/PlatformFee) interface.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* const { data: platformFees, isLoading, error } = usePlatformFees(contract);
|
||||
* import { useContract, usePlatformFees } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = usePlatformFees(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, is an object containing two fields:
|
||||
*
|
||||
* - `platform_fee_basis_points`: the platform fee basis points set on the contract
|
||||
* - `platform_fee_recipient`: the wallet address of the platform fee recipient
|
||||
*
|
||||
* _Note_: The basis points are in percentage format, meaning that a value of `500` is equivalent to a `5%` fee.
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* platform_fee_basis_points: number;
|
||||
* platform_fee_recipient: string;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns an object containing the platform fee basis points and the fee recipient address
|
||||
* @twfeature PlatformFee
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useplatformfees?utm_source=sdk | Documentation}
|
||||
* @platformFees
|
||||
*/
|
||||
export function usePlatformFees(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
) {
|
||||
): UseQueryResult<
|
||||
{
|
||||
platform_fee_basis_points: number;
|
||||
platform_fee_recipient: string;
|
||||
},
|
||||
unknown
|
||||
> {
|
||||
const contractAddress = contract?.getAddress();
|
||||
return useQueryWithNetwork(
|
||||
cacheKeys.extensions.platformFees.get(contractAddress),
|
||||
@@ -255,36 +368,67 @@ export function usePlatformFees(
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the platform fee recipient and basis points
|
||||
* Hook for updating platform fees on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`PlatformFee`](https://portal.thirdweb.com/contracts/build/extensions/general/PlatformFee) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import {
|
||||
* useUpdatePlatformFees,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: updatePlatformFees,
|
||||
* mutateAsync: updatePlatformFees,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useUpdatePlatformFees(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to update platform fees", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => updatePlatformFees({ updatePayload: { fee_recipient: "{{wallet_address}}", platform_fee_basis_points: 5_00 } })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* updatePlatformFees({
|
||||
* platform_fee_basis_points: 0,
|
||||
* fee_recipient: "{{wallet_address}}",
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Update Platform fees
|
||||
* </button>
|
||||
* Update Platform Fees
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to update the platform fees settings
|
||||
*
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns A mutation object to update the platform fees settings
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useUpdatePlatformFees(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an object with below properties:
|
||||
*
|
||||
* #### platform_fee_basis_points
|
||||
*
|
||||
* The `platform_fee_basis_points` property is a `number` between `0` - `10000` that defines the fee rate.
|
||||
*
|
||||
* This number is in percentage points. i.e. `100` is a 1% fee and `10000` is a 100% fee.
|
||||
*
|
||||
* #### fee_recipient
|
||||
*
|
||||
* The `fee_recipient` property is the address of the wallet that will receive the fees.
|
||||
*
|
||||
* Use the `useAddress` hook to get the current wallet address.
|
||||
*
|
||||
* @twfeature PlatformFee
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useupdateplatformfees?utm_source=sdk | Documentation}
|
||||
* @platformFees
|
||||
*/
|
||||
export function useUpdatePlatformFees(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -320,16 +464,44 @@ export function useUpdatePlatformFees(
|
||||
// metadata
|
||||
|
||||
/**
|
||||
* Get the metadata of this contract
|
||||
* Hook for getting the metadata associated with a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [Contract Metadata](https://portal.thirdweb.com/contracts/build/extensions/general/ContractMetadata) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const { data: metadata, isLoading, error } = useMetadata(contract);
|
||||
* import { useContract, useMetadata } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useMetadata(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a {@link CustomContractMetadata} object containing the metadata
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usemetadata?utm_source=sdk | Documentation}
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @returns
|
||||
* A `CustomContractMetadata` object containing the metadata
|
||||
*
|
||||
* The hook's `data` property, once loaded, is an object containing the contract's metadata.
|
||||
*
|
||||
* ```ts
|
||||
* CustomContractMetadata | undefined;
|
||||
* ```
|
||||
*
|
||||
* ```ts
|
||||
* interface CustomContractMetadata {
|
||||
* // The name of the contract.
|
||||
* name: string;
|
||||
* // A description of the contract.
|
||||
* description?: string;
|
||||
* // The image associated with the contract.
|
||||
* image?: any;
|
||||
* // An external link associated with the contract.
|
||||
* external_link?: string;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @metadata
|
||||
*/
|
||||
export function useMetadata(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -351,38 +523,59 @@ export function useMetadata(
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the metadata of this contract
|
||||
* Hook for updating the metadata of a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the `ContractMetadata` interface.
|
||||
*
|
||||
* The wallet initiating this transaction must have the required permissions to update the metadata, (`admin` permissions required by default).
|
||||
*
|
||||
* Provide your contract instance from the `useContract` hook as the first argument, and
|
||||
* an object fitting the [contract-level metadata standards](https://docs.opensea.io/docs/contract-level-metadata) of
|
||||
* the new metadata as the second argument, including:
|
||||
*
|
||||
* - `name`: A `string` for the name of the smart contract (required).
|
||||
* - `description`: A `string` to describe the smart contract (optional).
|
||||
* - `image`: A `string` or `File` object containing the URL or file data of an image to associate with the contract (optional).
|
||||
* - `external_link`: A `string` containing a URL to view the smart contract on your website (optional).
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import {
|
||||
* useUpdateMetadata,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: updateMetadata,
|
||||
* mutateAsync: updateMetadata,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useUpdateMetadata(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to update metadata", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => updateMetadata({
|
||||
* name: "My Contract",
|
||||
* description: "This is my contract"
|
||||
* })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* updateMetadata({
|
||||
* name: "My App",
|
||||
* description: "My awesome Ethereum App",
|
||||
* image: "/path/to/image.jpg", // URL, URI, or File object
|
||||
* external_link: "https://myapp.com",
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Update Contract Metadata
|
||||
* </button>
|
||||
* Update Metadata
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to update the metadata
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useupdatemetadata?utm_source=sdk | Documentation}
|
||||
*
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @returns Mutation object that to update the metadata
|
||||
* @metadata
|
||||
*/
|
||||
export function useUpdateMetadata(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
|
||||
@@ -56,6 +56,24 @@ async function fetchContractType(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for determining the type of contract for a contract address.
|
||||
*
|
||||
* This is useful if you want to determine if a contract is a [prebuilt contract](https://portal.thirdweb.com/pre-built-contracts).
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useContractType } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { data, isLoading, error } = useContractType(contractAddress);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contractAddress - The address of the contract
|
||||
* @returns Query result containing the type of the contract in the `data` property
|
||||
* @metadata
|
||||
*/
|
||||
export function useContractType(
|
||||
contractAddress: RequiredParam<ContractAddress>,
|
||||
) {
|
||||
@@ -107,6 +125,25 @@ function fetchCompilerMetadata(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for retrieving information such as the ABI, license, and metadata of a smart contract using it's contract address.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useCompilerMetadata } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { data, isLoading, error } = useCompilerMetadata(contractAddress);
|
||||
* }
|
||||
*
|
||||
* export default App;
|
||||
* ```
|
||||
*
|
||||
* @param contractAddress - The address of the deployed contract
|
||||
* @returns Query result containing the compiler metadata of the deployed contract in the `data` property
|
||||
*
|
||||
* @metadata
|
||||
*/
|
||||
export function useCompilerMetadata(
|
||||
contractAddress: RequiredParam<ContractAddress>,
|
||||
): UseQueryResult<PublishedMetadata | null> {
|
||||
@@ -144,51 +181,69 @@ export const compilerMetadata = {
|
||||
|
||||
// useContract
|
||||
|
||||
/**
|
||||
* @contract
|
||||
*/
|
||||
export type UseContractResult<
|
||||
TContract extends ValidContractInstance = SmartContract,
|
||||
> = UseQueryResult<TContract | undefined> & {
|
||||
contract: TContract | undefined;
|
||||
};
|
||||
|
||||
export function useContract<
|
||||
TContractAddress extends ContractAddress | GeneratedContractAddress,
|
||||
>(
|
||||
contractAddress: RequiredParam<TContractAddress>,
|
||||
): UseContractResult<
|
||||
TContractAddress extends GeneratedContractAddress
|
||||
? SmartContract<BaseContractForAddress<TContractAddress>>
|
||||
: SmartContract
|
||||
>;
|
||||
|
||||
/**
|
||||
* Use this resolve a contract address to a smart contract instance.
|
||||
* Hook for connecting to a smart contract.
|
||||
*
|
||||
* Provide your smart contract address as the first parameter. Once connected, the `contract` will be an instance of your smart contract.
|
||||
*
|
||||
* The ABI of the smart contract is resolved automatically for contracts deployed or imported using the [thirdweb dashboard](https://thirdweb.com/dashboard).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract, isLoading, error } = useContract("{{contract_address}}");
|
||||
* const { contract, isLoading, error } = useContract(contractAddress);
|
||||
* ```
|
||||
*
|
||||
* @param contractAddress - the address of the deployed contract
|
||||
* @returns a response object that includes the contract once it is resolved
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecontract?utm_source=sdk | Documentation}
|
||||
* @public
|
||||
* @remarks
|
||||
*
|
||||
* To cache the ABI of the smart contract, use [thirdweb generate](https://portal.thirdweb.com/cli/generate). This is recommended to improve performance and provide type-safety when interacting with your smart contract.
|
||||
*
|
||||
*
|
||||
* @param contractAddress - The address of the deployed contract
|
||||
* @returns Query result object that includes the contract once it is resolved
|
||||
* @contract
|
||||
*/
|
||||
export function useContract(
|
||||
contractAddress: RequiredParam<ContractAddress>,
|
||||
): UseContractResult<SmartContract>;
|
||||
|
||||
/**
|
||||
* Use this resolve a contract address to a smart contract instance.
|
||||
* If your contract is a prebuilt contract, it is strongly recommended you provide the contract's name as the second argument to gain access to improved top-level functions and type inference.
|
||||
*
|
||||
* Available contract types are:
|
||||
* - `"nft-drop"`
|
||||
* - `"signature-drop"`
|
||||
* - `"edition-drop"`
|
||||
* - `"nft-collection"`
|
||||
* - `"edition"`
|
||||
* - `"multiwrap"`
|
||||
* - `"pack"`
|
||||
* - `"token-drop"`
|
||||
* - `"token"`
|
||||
* - `"marketplace"`
|
||||
* - `"marketplace-v3"`
|
||||
* - `"split"`
|
||||
* - `"vote"`
|
||||
*
|
||||
* When a contract type is provided, the contract object will be typed as the contract's class.
|
||||
* For example, if you provide the contract type `"pack"`, the contract object will be returned typed as an instance of the `Pack` class, unlocking all of the top-level functions specific to the pack.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract, isLoading, error } = useContract("{{contract_address}}", "nft-drop");
|
||||
* const { contract, isLoading, error } = useContract(contractAddress, "pack");
|
||||
* ```
|
||||
*
|
||||
* @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
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecontract?utm_source=sdk | Documentation}
|
||||
* @param contractAddress - The address of the deployed contract
|
||||
* @param _contractType - The type of the contract
|
||||
* @returns Query result object that includes the contract once it is resolved
|
||||
* @public
|
||||
*/
|
||||
export function useContract<TContractType extends ContractType>(
|
||||
@@ -201,18 +256,20 @@ export function useContract<TContractType extends ContractType>(
|
||||
>;
|
||||
|
||||
/**
|
||||
* Use this resolve a contract address to a smart contract instance.
|
||||
* Optionally, (if you don’t want to use the dashboard import feature),
|
||||
* you can provide your smart contract’s ABI to the second parameter of the useContract hook.
|
||||
* This is useful when developing on a local node, where it may be faster to use the ABI than to import the contract using the dashboard.
|
||||
*
|
||||
* The ABI is only necessary if you have not deployed your contract with, or imported your contract to the [thirdweb dashboard](https://thirdweb.com/dashboard).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract, isLoading, error } = useContract("{{contract_address}}", ABI);
|
||||
* const { contract, isLoading, error } = useContract(contractAddress, contractAbi);
|
||||
* ```
|
||||
*
|
||||
* @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
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecontract?utm_source=sdk | Documentation}
|
||||
* @public
|
||||
* @param contractAddress - The address of the deployed contract
|
||||
* @param _abi - The ABI of the contract to use
|
||||
* @returns Query result object that includes the contract once it is resolved
|
||||
*/
|
||||
|
||||
export function useContract(
|
||||
@@ -220,6 +277,17 @@ export function useContract(
|
||||
_abi: ContractInterface,
|
||||
): UseContractResult<SmartContract>;
|
||||
|
||||
// TODO: add JSDoc for this signature
|
||||
export function useContract<
|
||||
TContractAddress extends ContractAddress | GeneratedContractAddress,
|
||||
>(
|
||||
contractAddress: RequiredParam<TContractAddress>,
|
||||
): UseContractResult<
|
||||
TContractAddress extends GeneratedContractAddress
|
||||
? SmartContract<BaseContractForAddress<TContractAddress>>
|
||||
: SmartContract
|
||||
>;
|
||||
|
||||
export function useContract(
|
||||
contractAddress: RequiredParam<ContractAddress>,
|
||||
contractTypeOrABI?: ContractType | ContractInterface,
|
||||
@@ -303,16 +371,17 @@ export function useContract(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the metadata of this contract
|
||||
* Get the metadata of given contract
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: contractMetadata, isLoading } = useContractMetadata(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - the {@link ValidContractInstance} instance of the contract to get the metadata for
|
||||
* @returns a response object that includes the contract metadata of the deployed contract
|
||||
* @param contract - The `ValidContractInstance` instance of the contract to get the metadata for
|
||||
* @returns A Query result object that includes the contract metadata of the deployed contract
|
||||
* @twfeature ContractMetadata
|
||||
* @metadata
|
||||
*/
|
||||
export function useContractMetadata<TContract extends ValidContractInstance>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -334,7 +403,7 @@ export function useContractMetadata<TContract extends ValidContractInstance>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the metadata of this contract
|
||||
* Update the metadata of the given contract
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
@@ -361,9 +430,10 @@ export function useContractMetadata<TContract extends ValidContractInstance>(
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @param contract - the {@link ValidContractInstance} instance of the contract to get the metadata for
|
||||
* @returns a response object that includes the contract metadata of the deployed contract
|
||||
* @param contract - The `ValidContractInstance` instance of the contract to get the metadata for
|
||||
* @returns Mutation object to update the contract metadata
|
||||
* @twfeature ContractMetadata
|
||||
* @metadata
|
||||
*/
|
||||
export function useContractMetadataUpdate(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -409,18 +479,66 @@ export function useContractMetadataUpdate(
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get or subscribe to contract events
|
||||
* Hook for reading events emitted by a smart contract, including new events as they are emitted (optional).
|
||||
*
|
||||
* By default, it reads all events emitted by the smart contract.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: contractEvents, isLoading } = useContractEvents(contract);
|
||||
* ```tsx
|
||||
* import { useContractEvents, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useContractEvents(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - the {@link ValidContractInstance} instance of the contract to listen to events for
|
||||
* @param eventName - the name of the event to query for (omit this or pass `undefined` to query for all events)
|
||||
* @param options - options includes the filters ({@link QueryAllEvents}) for the query as well as if you want to subscribe to real-time updates (default: true)
|
||||
* @returns a response object that includes the contract events
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecontractevents?utm_source=sdk | Documentation}
|
||||
* @param contract - The contract instance of the contract to listen to events for
|
||||
*
|
||||
* @param eventName -
|
||||
* The name of the event to query for.
|
||||
*
|
||||
* For example, if your smart contract emits an event called `MyEvent`, you would pass `"MyEvent"` to this parameter.
|
||||
*
|
||||
* Omit this parameter or provide undefined to query for all events emitted by the smart contract.
|
||||
*
|
||||
* @param options -
|
||||
* An object containing options to filter the events being queried.
|
||||
*
|
||||
* Available options include
|
||||
* - `queryFilter` to refine which events you want to read,
|
||||
* - a boolean `subscribe` flag to subscribe to new events as they are emitted.
|
||||
*
|
||||
* ### Example
|
||||
* ```tsx
|
||||
* import {
|
||||
* useContractEvents,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useContractEvents(
|
||||
* contract,
|
||||
* "MyEvent",
|
||||
* {
|
||||
* queryFilter: {
|
||||
* filters: {
|
||||
* tokenId: 123, // e.g. Only events where tokenId = 123
|
||||
* },
|
||||
* fromBlock: 0, // Events starting from this block
|
||||
* toBlock: 100, // Events up to this block
|
||||
* order: "asc", // Order of events ("asc" or "desc")
|
||||
* },
|
||||
* subscribe: true, // Subscribe to new events
|
||||
* },
|
||||
* );
|
||||
* ```
|
||||
*
|
||||
* @returns The hook's `data` property, once loaded, contains an array of `ContractEvent` objects
|
||||
* @contract
|
||||
*
|
||||
*/
|
||||
export function useContractEvents(
|
||||
contract: RequiredParam<ValidContractInstance>,
|
||||
@@ -505,19 +623,50 @@ export function useContractEvents(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get data from a contract read-function call
|
||||
* Generic hook for reading any data from a smart contract via it’s function/view/variable name.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const { data, isLoading, error } = useContractRead(contract, "functionName", ...args);
|
||||
*```
|
||||
* const { data, isLoading, error } = useContractRead(contract, "functionName", args);
|
||||
* ```
|
||||
*
|
||||
* @param contract - the contract instance of the contract to call a function on
|
||||
* @param functionName - the name of the function to call
|
||||
* @param args - The arguments to pass to the function (if any), with optional call arguments as the last parameter
|
||||
* @returns a response object that includes the data returned by the function call
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecontractread?utm_source=sdk | Documentation}
|
||||
* @example
|
||||
* Provide your smart contract instance from `useContract`, a function name and the arguments to pass to the function (if any).
|
||||
*
|
||||
* For example, to read the value of a view on your smart contract called `getName` you would do the following:
|
||||
*
|
||||
* ```tsx
|
||||
* import { useContractRead, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useContractRead(contract, "getName");
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
* If you have cached the ABI of your smart contract using [thirdweb generate](https://portal.thirdweb.com/cli/generate), the functionName and args parameters are strongly typed according to your smart contract’s ABI.
|
||||
*
|
||||
* @param contract - The contract instance of the contract to call a function on
|
||||
*
|
||||
* @param functionName - The name of the function to call in the smart contract. This can be any function, view, variable, etc. that does not require a transaction to occur.
|
||||
*
|
||||
* @param args - The arguments to pass to the function (if any)
|
||||
*
|
||||
* @param overrides -
|
||||
* `CallOverrides` object to send with your request.
|
||||
*
|
||||
* To include the sender's address (msg.sender) when calling view functions within your smart contract, include the property `{from: 0X123}` passing the relevant address.
|
||||
*
|
||||
* ```ts
|
||||
* const { data, isLoading, error } = useContractRead(contract, "getName", ["arg1", "arg2"], {
|
||||
* blockTag: 123,
|
||||
* from: "0x123",
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @returns Query result object that includes the data returned by the function call
|
||||
* @contract
|
||||
*/
|
||||
export function useContractRead<
|
||||
TContractAddress extends GeneratedContractAddress | ContractAddress,
|
||||
@@ -579,21 +728,48 @@ export function useContractRead<
|
||||
}
|
||||
|
||||
/**
|
||||
* Mke a write call to your contract
|
||||
* Generic hook for calling any smart contract function that requires a transaction to take place.
|
||||
*
|
||||
* Provide your smart contract instance returned from the `useContract` hook, along with the name of the function you wish to call on your smart contract as arguments to the hook.
|
||||
*
|
||||
* Then call the `mutate` or `mutateAsync` function returned by the hook, providing an array of arguments to send to your smart contract function.
|
||||
*
|
||||
* If you provide too many or too few arguments, the `error` property will be populated with an error message.
|
||||
*
|
||||
* If your function has no arguments, provide an empty array by calling the function with `{ args: [] }`
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const { mutate: myFunction, isLoading, error } = useContractWrite(contract, "myFunction");
|
||||
* import { useContractWrite, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // the function can be called as follows:
|
||||
* // myFunction(["param 1", "param 2", ...])
|
||||
*```
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync, isLoading, error } = useContractWrite(
|
||||
* contract,
|
||||
* "setName",
|
||||
* );
|
||||
*
|
||||
* @param contract - the contract instance of the contract to call a function on
|
||||
* @param functionName - the name of the function to call
|
||||
* @returns a response object that includes the write function to call
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usecontractwrite?utm_source=sdk | Documentation}
|
||||
* return (
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* // Calls the "setName" function on your smart contract with "My Name" as the first argument
|
||||
* action={() => mutateAsync({ args: ["My Name"] })}
|
||||
* >
|
||||
* Send Transaction
|
||||
* </Web3Button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* If you have cached the ABI of your smart contract using [thirdweb generate](https://portal.thirdweb.com/cli/generate), the functionName and args parameters are strongly typed according to your smart contract’s ABI.
|
||||
*
|
||||
*
|
||||
* @param contract - The contract instance of the contract to call a function on
|
||||
* @param functionName - The name of the function to call in the smart contract.
|
||||
* @returns A mutation object that includes the write function to call
|
||||
* @contract
|
||||
*/
|
||||
export function useContractWrite<
|
||||
TContractAddress extends GeneratedContractAddress | ContractAddress,
|
||||
|
||||
@@ -40,18 +40,49 @@ import invariant from "tiny-invariant";
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Get all unclaimed NFTs
|
||||
* Hook for fetching information about all NFTs that haven't been claimed yet from an NFT Drop contract.
|
||||
*
|
||||
* Available to use on contracts that extends the ERC721 spec
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: unclaimedNfts, isLoading, error } = useUnclaimedNFTs(contract, { start: 0, count: 100 });
|
||||
*
|
||||
* ```jsx
|
||||
* import { useUnclaimedNFTs, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useUnclaimedNFTs(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
* @param queryParams - query params to pass to the query for the sake of pagination
|
||||
* @returns a response object that includes an array of NFTs that are unclaimed
|
||||
* @param contract - Instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
*
|
||||
* @param queryParams -
|
||||
* query params to pass to the query for the sake of pagination
|
||||
* By default, the hook returns the first 100 unclaimed NFTs from the contract.
|
||||
*
|
||||
* Paginate the results by providing a `queryParams` object as the second argument.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useUnclaimedNFTs, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useUnclaimedNFTs(
|
||||
* contract,
|
||||
* {
|
||||
* count: 10, // Limit the number of results
|
||||
* start: 0, // Start from the nth result (useful for pagination)
|
||||
* },
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, contains an array of `NFT` objects.
|
||||
*
|
||||
* @twfeature ERC721LazyMintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useunclaimednfts?utm_source=sdk | Documentation}
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useUnclaimedNFTs(
|
||||
contract: RequiredParam<NFTDrop>,
|
||||
@@ -74,20 +105,49 @@ export function useUnclaimedNFTs(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all claimed NFTs
|
||||
* Hook for fetching all claimed NFTs from a given NFT Drop contract.
|
||||
*
|
||||
* @remarks Equivalent to using {@link useNFTs}.
|
||||
* Available to use on contracts that implement [`ERC721Claimable`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721Claimable),
|
||||
* such as the [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: claimedNFTs, isLoading, error } = useClaimedNFTs(contract, { start: 0, count: 100 });
|
||||
*
|
||||
* ```jsx
|
||||
* import { useClaimedNFTs, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress, "nft-drop");
|
||||
* const { data: nfts, isLoading, error } = useClaimedNFTs(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
* @param queryParams - query params to pass to the query for the sake of pagination
|
||||
* @returns a response object that includes an array of NFTs that are claimed
|
||||
* @param contract - Instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
*
|
||||
* @param queryParams -
|
||||
* By default, the hook will return the first `100` claimed NFTs
|
||||
*
|
||||
* You can use the `queryParams` argument to paginate the NFTs that are returned.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useClaimedNFTs, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress, "nft-drop");
|
||||
* const { data, isLoading, error } = useClaimedNFTs(
|
||||
* contract,
|
||||
* {
|
||||
* // For example, to only return the first 50 claimed NFTs in the collection
|
||||
* // in order of token ID
|
||||
* count: 50,
|
||||
* start: 0,
|
||||
* },
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns Query Result object that includes an array of NFTs that are claimed in the `data` property
|
||||
* @twfeature ERC721LazyMintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimednfts?utm_source=sdk | Documentation}
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useClaimedNFTs(
|
||||
contract: RequiredParam<NFTDrop>,
|
||||
@@ -110,11 +170,33 @@ export function useClaimedNFTs(
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for fetching the number of unclaimed NFTs from an NFT/Edition Drop contract.
|
||||
*
|
||||
* Unclaimed NFTs are tokens that were lazy-minted but have not yet been claimed by a user.
|
||||
*
|
||||
* Available to use on contracts that implement the [`LazyMint`](https://portal.thirdweb.com/contracts/build/extensions/general/LazyMint) extension;
|
||||
* such as the [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721) contract.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useUnclaimedNFTSupply, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress, "nftDrop");
|
||||
* const { data, isLoading, error } = useUnclaimedNFTSupply(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, contains a `BigNumber` representing the number of unclaimed NFTs.
|
||||
*
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
* @returns a response object that includes the number of NFTs that are unclaimed
|
||||
* @twfeature ERC721LazyMintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useunclaimednftsupply?utm_source=sdk | Documentation}
|
||||
*
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useUnclaimedNFTSupply(
|
||||
contract: RequiredParam<NFTDrop | SignatureDrop | SmartContract | null>,
|
||||
@@ -136,12 +218,28 @@ export function useUnclaimedNFTSupply(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the total number of claimed NFTs
|
||||
* Hook for retrieving the total supply of NFTs claimed from an NFT Drop contract.
|
||||
*
|
||||
* Available to use on contracts that implement [`ERC721Claimable`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721Claimable).
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useClaimedNFTSupply, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading } = useClaimedNFTSupply(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, is a `BigNumber` representing the total supply of NFTs claimed from the NFT drop contract so far.
|
||||
*
|
||||
* @param contract - an instance of a contract that extends the ERC721 spec (NFT drop, Signature Drop, or any custom contract that extends the ERC721 spec)
|
||||
* @returns a response object that includes the number of NFTs that are claimed
|
||||
* @twfeature ERC721LazyMintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimednftsupply?utm_source=sdk | Documentation}
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useClaimedNFTSupply(
|
||||
contract: RequiredParam<NFTDrop | SignatureDrop | SmartContract | null>,
|
||||
@@ -162,12 +260,39 @@ export function useClaimedNFTSupply(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all unrevealed batches
|
||||
* Hook for fetching batches of lazy-minted NFTs that were set to be revealed at a later date, but have not yet been revealed.
|
||||
*
|
||||
* Available to use on contracts that implement the [ERC721Revealable](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721Revealable)
|
||||
* or [ERC1155Revealable](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155Revealable) interfaces,
|
||||
* such as the [NFT Drop](https://thirdweb.com/thirdweb.eth/DropERC721)
|
||||
* and [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155) smart contracts.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* import { useBatchesToReveal, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data: batches, isLoading, error } = useBatchesToReveal(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a `RevealableContract`
|
||||
*
|
||||
* @returns The hook's `data` property, once loaded, contains an array of batches that need to be revealed.
|
||||
*
|
||||
* Each batch is an object with the following properties:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* batchId: BigNumber;
|
||||
* batchUri: string;
|
||||
* placeholderMetadata: NFTMetadata;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link RevealableContract}
|
||||
* @returns a response object that gets the batches to still be revealed
|
||||
* @twfeature ERC721Revealable | ERC1155Revealable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usebatchestoreveal?utm_source=sdk | Documentation}
|
||||
* @delayedReveal
|
||||
*/
|
||||
export function useBatchesToReveal<TContract extends RevealableContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -193,37 +318,103 @@ export function useBatchesToReveal<TContract extends RevealableContract>(
|
||||
/** WRITE HOOKS **/
|
||||
/** **********************/
|
||||
/**
|
||||
* Claim an NFT to a specific wallet
|
||||
* Hook for claiming an NFT from a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement a `Claimable` interface, and follow either the `ERC721`or `ERC1155` standard.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: claimNFT,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useClaimNFT(contract);
|
||||
* import { useContract, useClaimNFT, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to claim nft", error);
|
||||
* }
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: claimNft, isLoading, error } = useClaimNFT(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => claimNFT({ to: "{{wallet_address}}", quantity: 1 })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* claimNft({
|
||||
* to: "{{wallet_address}}", // Use useAddress hook to get current wallet address
|
||||
* quantity: 1,
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Claim NFT!
|
||||
* </button>
|
||||
* Claim NFT
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a `DropContract`
|
||||
*
|
||||
* @returns A mutation object to claim a NFT to the wallet specified in the params
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useClaimNFT(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an object as argument with below properties:
|
||||
*
|
||||
* #### to
|
||||
*
|
||||
* The wallet address to mint the NFT(s) to.
|
||||
*
|
||||
* Use the `useAddress` hook to get the currently connected wallet address.
|
||||
*
|
||||
* #### quantity
|
||||
*
|
||||
* The number of NFTs you wish to claim.
|
||||
*
|
||||
* - With ERC721 contracts, this represents the number of unique tokens you wish to claim.
|
||||
* - With ERC1155 contracts, this represents the quantity of the specific `tokenId` you wish to claim.
|
||||
*
|
||||
* #### tokenId
|
||||
*
|
||||
* For ERC1155 contracts, you must specify a specific `tokenId` to claim.
|
||||
*
|
||||
* #### options (optional)
|
||||
*
|
||||
* Customizable `ClaimOptions` object to override the default behaviour of the hook.
|
||||
*
|
||||
* There are three options available:
|
||||
*
|
||||
* - `checkERC20Allowance` - Whether to check the ERC20 allowance of the sender, defaults to true.
|
||||
* - `currencyAddress` - The currency to pay for each token claimed, defaults to `NATIVE_TOKEN_ADDRESS` for native currency.
|
||||
* - `pricePerToken` - The price to pay for each token claimed. Not relevant when using claim conditions.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useContract, useClaimNFT, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutate: claimNft, isLoading, error } = useClaimNFT(contract);
|
||||
*
|
||||
* return (
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* claimNft({
|
||||
* to: "{{wallet_address}}",
|
||||
* quantity: 1,
|
||||
* options: {
|
||||
* checkERC20Allowance: true,
|
||||
* currencyAddress: "{{erc20_address}}",
|
||||
* pricePerToken: 0,
|
||||
* },
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Claim NFT
|
||||
* </Web3Button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link DropContract}
|
||||
* @returns a mutation object that can be used to claim a NFT to the wallet specificed in the params
|
||||
* @twfeature ERC721Claimable | ERC1155Claimable | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimnft?utm_source=sdk | Documentation}
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useClaimNFT<TContract extends DropContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -281,38 +472,95 @@ export function useClaimNFT<TContract extends DropContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy mint NFTs
|
||||
* Hook for lazy minting a batch of NFTs on a drop contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the "Drop" extension, and
|
||||
* follow either the `ERC721` or `ERC1155` standard.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: lazyMint,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useLazyMint(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to lazy mint NFT", error);
|
||||
* }
|
||||
* Provide your drop contract (ERC721 or ERC1155) as the argument to the hook, and an array
|
||||
* of metadata objects to lazy-mint.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useContract, useLazyMint, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: lazyMint, isLoading, error } = useLazyMint(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => lazyMint({ metadatas: [{ name: "My NFT!"}] })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* lazyMint({
|
||||
* // Metadata of the NFTs to upload
|
||||
* metadatas: [
|
||||
* {
|
||||
* name: "My NFT",
|
||||
* description: "An example NFT",
|
||||
* image: "{{image_url}}",
|
||||
* },
|
||||
* ],
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Lazy mint NFT!
|
||||
* </button>
|
||||
* Lazy Mint NFTs
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a `NFTContract` with the drop extension
|
||||
*
|
||||
* @param onProgress - Optional callback that will be called with the progress of the upload
|
||||
*
|
||||
* @returns A mutation object to lazy mint a batch of NFTs
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useLazyMint(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an object as argument with below properties:
|
||||
*
|
||||
* #### metadatas
|
||||
* An array of objects containing the metadata of the NFTs to lazy mint.
|
||||
*
|
||||
* Your metadata objects must follow the [Metadata standards](https://docs.opensea.io/docs/metadata-standards#metadata-structure).
|
||||
*
|
||||
* ```jsx
|
||||
* import { useContract, useLazyMint, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: lazyMint, isLoading, error } = useLazyMint(contract);
|
||||
*
|
||||
* return (
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* lazyMint({
|
||||
* // Metadata of the NFTs to upload
|
||||
* metadatas: [
|
||||
* {
|
||||
* name: "My NFT",
|
||||
* description: "An example NFT",
|
||||
* image: "{{image_url}}",
|
||||
* },
|
||||
* ],
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Lazy Mint NFTs
|
||||
* </Web3Button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract} with the drop extension
|
||||
* @param onProgress - an optional callback that will be called with the progress of the upload
|
||||
* @returns a mutation object that can be used to lazy mint a batch of NFTs
|
||||
* @twfeature ERC721LazyMintable | ERC1155LazyMintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.uselazymint?utm_source=sdk | Documentation}
|
||||
* @nftDrop
|
||||
*/
|
||||
export function useLazyMint<TContract extends DropContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -353,38 +601,78 @@ export function useLazyMint<TContract extends DropContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy mint NFTs with delayed reveal
|
||||
* Hook to lazy-mint a batch of NFTs with [delayed reveal](https://portal.thirdweb.com/glossary/delayed-reveal);
|
||||
* allowing the owner to set placeholder metadata and reveal the metadata of the NFTs at a later time.
|
||||
*
|
||||
* Available to use on contracts that implement the
|
||||
* [ERC721Revealable](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721Revealable)
|
||||
* or [ERC1155Revealable](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155Revealable)
|
||||
* interfaces.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* ```tsx
|
||||
* import {
|
||||
* useDelayedRevealLazyMint,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: delayedRevealLazyMint,
|
||||
* mutateAsync: mintNft,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useDelayedRevealLazyMint(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to lazy mint NFT", error);
|
||||
* }
|
||||
* const nftData = {
|
||||
* placeholder: {
|
||||
* name: "My NFT",
|
||||
* description: "This is my NFT",
|
||||
* image: "ipfs://example.com/my-nft.png", // Accepts any URL or File type
|
||||
* },
|
||||
* metadatas: [
|
||||
* {
|
||||
* name: "My NFT",
|
||||
* description: "This is my NFT",
|
||||
* image: "ipfs://example.com/my-nft.png", // Accepts any URL or File type
|
||||
* },
|
||||
* ],
|
||||
* password: "{{password}}", // Password to be used for encryption
|
||||
* };
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => delayedRevealLazyMint({ metadatas: [{ name: "My NFT!"}] })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() => mintNft(nftData)}
|
||||
* >
|
||||
* Delayed Reveal Lazy mint NFT!
|
||||
* </button>
|
||||
* Mint NFTs
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link DropContract}
|
||||
* @param contract - Instance of a {@link DropContract}
|
||||
* @param onProgress - an optional callback that will be called with the progress of the upload
|
||||
* @returns a mutation object that can be used to lazy mint a batch of NFTs
|
||||
* @returns Mutation object to lazy mint a batch of NFTs
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useDelayedRevealLazyMint(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object as argument with below properties:
|
||||
*
|
||||
* #### metadatas
|
||||
* An array of metadata objects, representing the metadata of the NFTs to be lazy-minted. Each metadata object must conform to the [standard metadata properties](https://docs.opensea.io/docs/metadata-standards).
|
||||
*
|
||||
* #### password
|
||||
* The password used to encrypt the metadatas.
|
||||
*
|
||||
* __The password CANNOT be recovered once it is set. If you lose the password, you will not be able to reveal the metadata.__
|
||||
*
|
||||
* @twfeature ERC721Revealable | ERC1155Revealable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usedelayedreveallazymint?utm_source=sdk | Documentation}
|
||||
* @delayedReveal
|
||||
*/
|
||||
export function useDelayedRevealLazyMint<TContract extends RevealableContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -434,37 +722,55 @@ export function useDelayedRevealLazyMint<TContract extends RevealableContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveal a batch of delayed reveal NFTs
|
||||
* Hook for revealing a batch of delayed reveal NFTs using [delayed reveal](https://portal.thirdweb.com/glossary/delayed-reveal).
|
||||
*
|
||||
* Available to use on contracts that implement the
|
||||
* [ERC721Revealable](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721Revealable)
|
||||
* or [ERC1155Revealable](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155Revealable)
|
||||
* interfaces.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useRevealLazyMint } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const { mutateAsync, isLoading, error } = useRevealLazyMint(contract);
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* ```tsx
|
||||
* import {
|
||||
* useContract,
|
||||
* useRevealLazyMint,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* // Contract must be an ERC-721 or ERC-1155 contract that implements the ERC721Revealable or ERC1155Revealable interface
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: revealLazyMint,
|
||||
* mutateAsync: revealLazyMint,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useRevealLazyMint(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to reveal batch", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => revealLazyMint({ batchId: "0", password: "my-password" })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* revealLazyMint({
|
||||
* batchId: "{{batch_id}}", // ID of the batch to reveal (use useBatchesToReveal to get the batch IDs)
|
||||
* password: "{{password}}", // Password to reveal the batch
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Reveal batch!
|
||||
* </button>
|
||||
* Reveal Lazy Mint
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link RevealableContract}
|
||||
* @returns a mutation object that can be used to reveal a batch of delayed reveal NFTs
|
||||
* @param contract - Instance of a `RevealableContract`
|
||||
* @twfeature ERC721Revealable | ERC1155Revealable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usereveallazymint?utm_source=sdk | Documentation}
|
||||
* @delayedReveal
|
||||
*/
|
||||
export function useRevealLazyMint<TContract extends RevealableContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -35,19 +35,61 @@ import invariant from "tiny-invariant";
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Get a single NFT
|
||||
* Hook for fetching information about an NFT from a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`ERC721`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* or [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* NFT metadata is automatically fetched from where the `tokenUri` is hosted (e.g. IPFS), and makes the `image`
|
||||
* property available as a URL through our IPFS gateway (if the image is hosted on IPFS).
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const tokenId = 0; // the tokenId to look up
|
||||
* const { data: nft, isLoading, error } = useNFT(contract, tokenId);
|
||||
*
|
||||
* Provide your NFT collection contract object and the token ID of the NFT you want to fetch as
|
||||
* arguments.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useContract, useNFT } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // The token ID of the NFT you want to fetch
|
||||
* const tokenId = 0;
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const { data: nft, isLoading, error } = useNFT(contract, tokenId);
|
||||
*
|
||||
* if (isLoading) return <div>Fetching NFT…</div>;
|
||||
* if (error) return <div>Error fetching NFT</div>;
|
||||
* if (!nft) return <div>NFT not found</div>;
|
||||
* return <div>NFT: {nft.metadata.name}</div>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @param tokenId - the tokenId to look up
|
||||
* @returns a response object that includes the metadata for the given tokenId
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
*
|
||||
* @param tokenId - The token ID of the NFT you want to fetch.
|
||||
* ```jsx
|
||||
* import { useContract, useNFT } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // The token ID of the NFT you want to fetch
|
||||
* const tokenId = 0;
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* data: nft,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useNFT(
|
||||
* contract,
|
||||
* tokenId,
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns Query result object that includes the metadata for the given tokenId in `data` property
|
||||
* @twfeature ERC721 | ERC1155
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usenft?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useNFT<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -78,18 +120,38 @@ export function useNFT<TContract extends NFTContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all NFTs
|
||||
* Hook to query all NFTs associated with a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`ERC721`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* or [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* NFT metadata is automatically fetched from where the `tokenUri` is hosted (e.g. IPFS), and makes the `image`
|
||||
* property available as a URL through our IPFS gateway (if the image is hosted on IPFS).
|
||||
*
|
||||
* By default, only returns the first `100` NFTs in the collection. You can use the `queryParams` argument to
|
||||
* filter the NFTs that are returned or to paginate through the collection.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: nfts, isLoading, error } = useNFTs(contract, { start: 0, count: 100 });
|
||||
*
|
||||
* ```jsx
|
||||
* import { useNFTs, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useNFTs(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @param queryParams - query params to pass to the query for pagination
|
||||
* @returns a response object that includes an array of NFTs
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
*
|
||||
* @param queryParams -
|
||||
* By default, the hook will return the first 100 NFTs associated with the contract.
|
||||
*
|
||||
* You can use the `queryParams` argument to paginate the NFTs that are returned.
|
||||
*
|
||||
* @returns Query result object that includes an array of `NFT` objects
|
||||
* @twfeature ERC721Supply | ERC721Enumerable | ERC1155Enumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usenfts?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useNFTs<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -120,18 +182,27 @@ export function useNFTs<TContract extends NFTContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total supply count
|
||||
* Hook to get the total count of **unique** NFTs minted on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`ERC721`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* or [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* When used for ERC1155 contracts, the total count is the number of unique token IDs minted, _not_ the total supply of all tokens in circulation.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const { data: count, isLoading, error } = useTotalCount(contract);
|
||||
* ```jsx
|
||||
* import { useTotalCount, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data: totalCount, isLoading, error } = useTotalCount(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @returns a response object that includes the total count of NFTs
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
* @returns A `BigNumber` that includes the total count of NFTs
|
||||
* @twfeature ERC721Supply | ERC1155Enumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetotalcount?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useTotalCount<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -167,19 +238,43 @@ export function useTotalCount<TContract extends NFTContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total minted supply count
|
||||
* Hook for fetching the total number of NFTs in circulation for a given smart contract.
|
||||
*
|
||||
* This takes into account the increase in supply due to minting and the decrease in supply due to burning.
|
||||
*
|
||||
* Available to use on contracts that implement either the [ERC721](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* or [ERC1155](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const { data: totalCirculatingSupply, isLoading, error } = useTotalCirculatingSupply(contract);
|
||||
*
|
||||
* ```jsx
|
||||
* import { useTotalCirculatingSupply, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useTotalCirculatingSupply(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @param tokenId - required for ERC1155, the tokenId to look up
|
||||
* @returns a response object that includes the total minted supply
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
*
|
||||
* @param tokenId - Required for ERC1155, the tokenId to look up. This will return the total quantity of the given token ID in circulation.
|
||||
* ```ts
|
||||
* import { useTotalCirculatingSupply, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useTotalCirculatingSupply(
|
||||
* contract,
|
||||
* "{{token_id}}",
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A `BigNumber` representing the total circulating supply.
|
||||
*
|
||||
* @twfeature ERC721Supply | ERC1155Enumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetotalcirculatingsupply?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useTotalCirculatingSupply(
|
||||
contract: RequiredParam<NFTContract>,
|
||||
@@ -220,19 +315,32 @@ export function useTotalCirculatingSupply(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all NFTs owned by a specific wallet
|
||||
* Hook for accessing a list of NFTs owned by a single wallet address.
|
||||
*
|
||||
* Available to use on smart contracts that implement either ERC721Enumerable, ERC1155Enumerable, or ERC721Supply extensions.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: ownedNFTs, isLoading, error } = useOwnedNFTs(contract, "{{wallet_address}}", { start: 0, count: 100 });
|
||||
*
|
||||
* ```jsx
|
||||
* import { useOwnedNFTs, useContract, useAddress } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const address = useAddress();
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useOwnedNFTs(contract, address);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @param ownerWalletAddress - the wallet address to get owned tokens for
|
||||
* @param queryParams - query params to pass to the query for pagination
|
||||
* @returns a response object that includes the list of owned tokens
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
* @param ownerWalletAddress -
|
||||
* The wallet address to get owned tokens for. Likely, you will want to view the connected wallet’s NFTs. use the `useAddress` hook to get this value.
|
||||
*
|
||||
* @param queryParams - Query params to pass to the query for pagination
|
||||
*
|
||||
* @returns Query result object that includes the list of owned `NFT` objects
|
||||
*
|
||||
* @twfeature ERC721Enumerable | ERC1155Enumerable | ERC721Supply
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useownednfts?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useOwnedNFTs<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -262,22 +370,30 @@ export function useOwnedNFTs<TContract extends NFTContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get NFT balance of a specific wallet
|
||||
* Hook to get the quantity a user owns of a specific [ERC1155](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) NFT.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: ownerBalance, isLoading, error } = useNFTBalance(contract, "{{wallet_address}}");
|
||||
* // for ERC1155 contracts, you can also pass a tokenId
|
||||
* const tokenId = 0;
|
||||
* const { data: ownerBalance, isLoading, error } = useNFTBalance(contract, "{{wallet_address}}", tokenId);
|
||||
* ```jsx
|
||||
* import { useNFTBalance, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { isLoading, data, error } = useNFTBalance(
|
||||
* contract,
|
||||
* "{{wallet_address}}",
|
||||
* "{{token_id}}",
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @param ownerWalletAddress - the wallet address to check the balance of
|
||||
* @param tokenId - required for ERC1155, the tokenId to look up
|
||||
* @returns a response object that includes the total balance of the owner
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
* @param ownerWalletAddress - The wallet address to check the balance of. Use the `useAddress` hook to get the current wallet address.
|
||||
* @param tokenId - Required for ERC1155, the tokenId to look up
|
||||
* @returns The hook's `data` property, once loaded, returns a `BigNumber` representing the quantity of the NFT owned by the wallet.
|
||||
* @twfeature ERC721 | ERC1155
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usenftbalance?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useNFTBalance(
|
||||
contract: RequiredParam<NFTContract>,
|
||||
@@ -327,10 +443,10 @@ export function useNFTBalance(
|
||||
* const { data: sharedMetadata, isLoading, error } = useSharedMetadata(contract);
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @returns a response object that includes the shared metadata of the contract
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
* @returns Query result object that includes the shared metadata of the contract
|
||||
* @twfeature ERC721SharedMetadata
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usesharedmetadata?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useSharedMetadata(
|
||||
contract: RequiredParam<NFTContract>,
|
||||
@@ -361,37 +477,93 @@ export function useSharedMetadata(
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Mint an NFT to a specific wallet
|
||||
* Hook for minting a new NFT on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`ERC721`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* or [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* By default, the process uploads and pins the NFT metadata to IPFS before minting.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: mintNft,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useMintNFT(contract);
|
||||
* import { useMintNFT, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to mint NFT", error);
|
||||
* }
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: mintNft, isLoading, error } = useMintNFT(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => mintNft({ name: "My awesome NFT!", to: "{{wallet_address}}" })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* mintNft({
|
||||
* metadata: {
|
||||
* name: "My NFT",
|
||||
* description: "This is my NFT",
|
||||
* image: "ipfs://example.com/my-nft.png", // Accepts any URL or File type
|
||||
* },
|
||||
* to: "{{wallet_address}}", // Use useAddress hook to get current wallet address
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Mint!
|
||||
* </button>
|
||||
* Mint NFT
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @returns a mutation object that can be used to mint a new NFT token to the connected wallet
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
* @returns Mutation object that to mint a new NFT token to the connected wallet
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useMintNFT(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object with the following properties:
|
||||
*
|
||||
* #### metadata
|
||||
* The metadata of the NFT to mint.
|
||||
*
|
||||
* By default, the `metadata` object is uploaded and pinned to IPFS before minting.
|
||||
*
|
||||
* You can override this behavior by providing a `string` to the metadata property. The string must be a URL that points to a valid JSON object containing [standard metadata properties](https://docs.opensea.io/docs/metadata-standards)
|
||||
*
|
||||
* ```jsx
|
||||
* import { useMintNFT, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // Your smart contract address
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: mintNft, isLoading, error } = useMintNFT(contract);
|
||||
*
|
||||
* return (
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* mintNft({
|
||||
* // Any valid IPFS or HTTP URL that points to a JSON object
|
||||
* metadata: "https://<url>/<to>/<your>/<metadata>.json",
|
||||
* to: "{{wallet_address}}",
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Mint NFT
|
||||
* </Web3Button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* #### to (required)
|
||||
* The wallet address to mint the NFT to.
|
||||
*
|
||||
* Likely, you will want to mint the NFT to the currently connected wallet address.
|
||||
* Use the `useAddress` hook to get this value.
|
||||
*
|
||||
* @twfeature ERC721Mintable | ERC1155Mintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usemintnft?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useMintNFT<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -433,37 +605,83 @@ export function useMintNFT<TContract extends NFTContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Increase the supply of an existing NFT
|
||||
* Hook for minting additional supply to an _existing_ ERC-1155 token.
|
||||
*
|
||||
* Available to use on contracts that implement the
|
||||
* [ERC1155Mintable](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155Mintable)
|
||||
* interface, such as the [Edition](https://thirdweb.com/thirdweb.eth/TokenERC1155) or [Edition Drop](https://thirdweb.com/thirdweb.eth/DropERC1155).
|
||||
*
|
||||
* The wallet address that initiates this transaction must have minting permissions on the contract.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import { useContract, useMintNFTSupply, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* const walletAddress = "{{wallet_address}}";
|
||||
* const tokenId = "{{token_id}}";
|
||||
* const additionalSupply = "{{additional_supply}}";
|
||||
*
|
||||
* function App() {
|
||||
* // Contract must be an ERC-1155 contract that implements the ERC1155Mintable interface
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: mintNftSupply,
|
||||
* mutateAsync: mintNftSupply,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useMintNFTSupply(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to mint additional supply", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => mintNftSupply({ tokenId: 0, additionalSupply: 100, to: "{{wallet_address}}"})}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* mintNftSupply({
|
||||
* additionalSupply: additionalSupply, // Quantity to mint
|
||||
* to: walletAddress, // Address to mint to
|
||||
* tokenId: tokenId, // Token ID to add supply to
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Mint Additional Supply!
|
||||
* </button>
|
||||
* Mint NFT Supply
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link Erc1155}
|
||||
* @returns a mutation object that can be used to mint a more supply of a token id to the provided wallet
|
||||
* @param contract - Instance of a `Erc1155`
|
||||
*
|
||||
* @returns Mutation object to mint a more supply of a token id to the provided wallet
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useMintNFTSupply(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an object with the following properties:
|
||||
*
|
||||
* #### additionalSupply
|
||||
* The quantity of additional supply to mint.
|
||||
*
|
||||
* For example, if you have 10 quantity so far, and you want to mint 5 more, set `additionalSupply` to `5`.
|
||||
*
|
||||
* Can be a `string` or `number`.
|
||||
*
|
||||
*
|
||||
* #### to
|
||||
* The wallet address to mint the new supply to.
|
||||
*
|
||||
* To use the connected wallet address, use the `useAddress` hook.
|
||||
*
|
||||
*
|
||||
* #### tokenId
|
||||
* The token ID of the NFT to mint additional supply to.
|
||||
*
|
||||
* Can be a `string` or `number`.
|
||||
*
|
||||
* @twfeature ERC1155Mintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usemintnftsupply?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useMintNFTSupply(contract: Erc1155) {
|
||||
const activeChainId = useSDKChainId();
|
||||
@@ -496,40 +714,79 @@ export function useMintNFTSupply(contract: Erc1155) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer an NFT
|
||||
* Hook for transferring ERC721 or ERC1155 NFTs to another wallet address.
|
||||
*
|
||||
* Available to use on contracts that implement either the
|
||||
* [ERC721](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* and [ERC1155](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155)
|
||||
* interfaces, such as the [Edition](https://thirdweb.com/thirdweb.eth/TokenERC1155)
|
||||
* or [NFT Collection](https://thirdweb.com/thirdweb.eth/TokenERC721).
|
||||
*
|
||||
* The wallet address that initiates this transaction must have transfer permissions on the contract (i.e. the tokens are not soulbound).
|
||||
* It also must have the required amount of token(s) available to transfer.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import { useContract, useTransferNFT, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // Your NFT collection contract address
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* const walletAddress = "{{wallet_address}}";
|
||||
* const tokenId = "{{token_id}}";
|
||||
*
|
||||
* function App() {
|
||||
* // Contract must be an ERC-721 or ERC-1155 contract
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: transferNFT,
|
||||
* mutateAsync: transferNFT,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useTransferNFT(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to transfer NFT", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => transferNFT({
|
||||
* to: "{{wallet_address}}",
|
||||
* tokenId: 2
|
||||
* })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* transferNFT({
|
||||
* to: walletAddress, // Address to transfer the token to
|
||||
* tokenId: tokenId, // Token ID to transfer
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Transfer
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @returns a mutation object that can be used to transfer NFTs
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
*
|
||||
* @returns Mutation object to transfer NFTs
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useTransferNFT(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object with the following properties:
|
||||
*
|
||||
* #### to
|
||||
* The wallet address to transfer the token(s) to.
|
||||
*
|
||||
* To use the connected wallet address, use the `useAddress` hook.
|
||||
*
|
||||
*
|
||||
* #### tokenId
|
||||
* The token ID of the NFT to transfer.
|
||||
*
|
||||
* Can be a `string` or `number`.
|
||||
*
|
||||
* #### amount (ERC1155 only)
|
||||
* If you are using an ERC1155 contract, specify the amount of tokens to transfer.
|
||||
*
|
||||
* @twfeature ERC721 | ERC1155
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetransfernft?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useTransferNFT<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -577,43 +834,60 @@ export function useTransferNFT<TContract extends NFTContract>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Airdrop NFTs to a list of wallets
|
||||
* Hook for airdropping [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) NFT tokens to multiple wallet addresses at once.
|
||||
*
|
||||
* Available to use on smart contracts that implement the `ERC1155` standard.
|
||||
*
|
||||
* Performs a batch transfer from the connected wallet to the specified addresses.
|
||||
* This means you need to have the total number of tokens you wish to airdrop available in the wallet that performs this transaction.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: airdropNFT,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useAirdropNFT(contract);
|
||||
* import { useAirdropNFT, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to transfer batch NFTs", error);
|
||||
* }
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: airdropNft, isLoading, error } = useAirdropNFT(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => airdropNFT({
|
||||
* tokenId: 2,
|
||||
* addresses: [
|
||||
* { address: "{{wallet_address}}", quantity: 2 },
|
||||
* { address: "{{wallet_address}}", quantity: 4 } }
|
||||
* ]
|
||||
* )}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* airdropNft({
|
||||
* addresses: [
|
||||
* {
|
||||
* address: "0x123",
|
||||
* quantity: 1,
|
||||
* },
|
||||
* ],
|
||||
* tokenId: tokenId,
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Airdrop NFT
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link Erc1155}
|
||||
* @returns a mutation object that can be used to transfer batch NFTs
|
||||
* @param contract - Instance of a `Erc1155`
|
||||
* @returns Mutation object that to transfer batch NFTs
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useAirdropNFT(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object with the following properties:
|
||||
*
|
||||
* #### tokenId
|
||||
* The token ID of the NFT to airdrop.
|
||||
*
|
||||
* #### addresses
|
||||
* An array of objects containing an `address` and `quantity` of NFTs to airdrop to each address.
|
||||
*
|
||||
* @twfeature ERC1155
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useairdropnft?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useAirdropNFT(contract: Erc1155) {
|
||||
const activeChainId = useSDKChainId();
|
||||
@@ -639,37 +913,61 @@ export function useAirdropNFT(contract: Erc1155) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Burn an NFT
|
||||
* Hook for burning a NFT on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`ERC721`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721)
|
||||
* or [`ERC1155`](https://portal.thirdweb.com/contracts/build/extensions/erc-1155/ERC1155) standard.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: burnNFT,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useBurnNFT(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to burn NFT", error);
|
||||
* }
|
||||
* ```jsx
|
||||
* import { useBurnNFT, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* // The tokenId of the NFT you want to burn
|
||||
* const tokenIdToBurn = "{{tokenId}}}}";
|
||||
* const amount = 1;
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: burnNft, isLoading, error } = useBurnNFT(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => burnNFT({ tokenId: 0, amount: 1 })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* burnNft({
|
||||
* tokenId: tokenIdToBurn,
|
||||
* amount: amount,
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Burn!
|
||||
* </button>
|
||||
* Burn NFT
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link NFTContract}
|
||||
* @returns a mutation object that can be used to burn an NFT token from the connected wallet
|
||||
* @param contract - Instance of a `NFTContract`
|
||||
* @returns Mutation object that to burn an NFT token from the connected wallet
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useBurnNFT(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object with the following properties:
|
||||
*
|
||||
* #### tokenId
|
||||
* The token ID of the NFT you want to burn.
|
||||
*
|
||||
* #### amount (optional)
|
||||
* When using ERC1155 NFTs, you can specify the quantity you want to burn.
|
||||
*
|
||||
* Defaults value is `1`
|
||||
*
|
||||
* @twfeature ERC721Burnable | ERC1155Burnable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useburnnft?utm_source=sdk | Documentation}
|
||||
* @nft
|
||||
*/
|
||||
export function useBurnNFT<TContract extends NFTContract>(
|
||||
contract: RequiredParam<TContract>,
|
||||
|
||||
@@ -26,7 +26,7 @@ import invariant from "tiny-invariant";
|
||||
export type ContractWithRoles = Exclude<ValidContractInstance, Vote>;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @permissionControl
|
||||
*/
|
||||
export type RolesForContract<TContract extends ContractWithRoles> =
|
||||
TContract extends SmartContract
|
||||
@@ -46,17 +46,54 @@ type GetAllReturnType<TContract extends ContractWithRoles> = Promise<
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Get all members of all roles
|
||||
* Hook for getting all wallet addresses that have a role in a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions).
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* const { data: roles, isLoading, error } = useAllRoleMembers(contract);
|
||||
* import { useAllRoleMembers, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useAllRoleMembers(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property, once loaded, is an object, where the keys are the role names and the values are arrays of wallet addresses that have that role.
|
||||
*
|
||||
* For example, if the contract has two roles, `admin` and `transfer`, and the `admin` role has two members, the `data` property will look like this:
|
||||
*
|
||||
* ```ts
|
||||
* {
|
||||
* admin: ["0x1234", "0x5678"],
|
||||
* transfer: [],
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* #### Type
|
||||
*
|
||||
* ```ts
|
||||
* Record<
|
||||
* | "admin"
|
||||
* | "transfer"
|
||||
* | "minter"
|
||||
* | "pauser"
|
||||
* | "lister"
|
||||
* | "asset"
|
||||
* | "unwrap"
|
||||
* | "factory"
|
||||
* | (string & {}),
|
||||
* string[]
|
||||
* > | undefined;
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a list of addresses for all supported roles on the contract.
|
||||
* @twfeature PermissionsEnumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useallrolemembers?utm_source=sdk | Documentation}
|
||||
* @permissionControl
|
||||
*/
|
||||
export function useAllRoleMembers<TContract extends ContractWithRoles>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -77,18 +114,43 @@ export function useAllRoleMembers<TContract extends ContractWithRoles>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all members of a specific role
|
||||
* Hook for getting all wallet addresses that have a specific role in a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const { data: members, isLoading, error } = useRoleMembers(SmartContract, "admin");
|
||||
* import { useContract, useRoleMembers } from "@thirdweb-dev/react";
|
||||
*
|
||||
* // Your smart contract address (must implement permission controls)
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
*
|
||||
* const roleName = "admin";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { data, isLoading, error } = useRoleMembers(contract, roleName);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @param role - the role to get the members of, see {@link Role}
|
||||
* @returns a list of addresses that are members of the role
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @param role -
|
||||
* The name of the role to get the members of
|
||||
*
|
||||
* Can be any custom role, or a built-in role, such as:
|
||||
* - `"admin"`
|
||||
* - `"transfer"`
|
||||
* - `"minter"`
|
||||
* - `"pauser"`
|
||||
* - `"lister"`
|
||||
* - `"asset"`
|
||||
* - `"unwrap"`
|
||||
* - `"factory"`
|
||||
*
|
||||
* @returns The hook's `data` property, once loaded, is an array of wallet addresses that have the specified role
|
||||
*
|
||||
* @twfeature Permissions
|
||||
* @see {@link https://portal.thirdweb.com/react/react.userolemembers?utm_source=sdk | Documentation}
|
||||
* @permissionControl
|
||||
*/
|
||||
export function useRoleMembers<TContract extends ContractWithRoles>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -109,19 +171,47 @@ export function useRoleMembers<TContract extends ContractWithRoles>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an address is a member of a specific role
|
||||
* Hook to check if an address is a member of a role on a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface
|
||||
*
|
||||
* Provide the following arguments to the hook:
|
||||
*
|
||||
* 1. `contract` - The contract instance to check the role on.
|
||||
* 2. `roleName` - The name of the role to check.
|
||||
* 3. `address` - The wallet address to see if it is a member of the role.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* const { data: isMember, isLoading, error } = useIsAddressRole(contract, "admin", "{{wallet_address}}");
|
||||
* import { useIsAddressRole, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const isMember = useIsAddressRole(contract, roleName, walletAddress);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @param role - the role to check the member against, see {@link Role}
|
||||
* @param walletAddress - the address to check
|
||||
* @returns true if the address is a member of the role, or false if not
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @param role - The name of the role to check. Can be any custom role, or a built-in role, such as:
|
||||
* - `"admin"`
|
||||
* - `"transfer"`
|
||||
* - `"minter"`
|
||||
* - `"pauser"`
|
||||
* - `"lister"`
|
||||
* - `"asset"`
|
||||
* - `"unwrap"`
|
||||
* - `"factory"`
|
||||
*
|
||||
* @param walletAddress -
|
||||
* The wallet address to check if it is a member of the role.
|
||||
* Use the `useAddress` hook to get the current wallet address.
|
||||
*
|
||||
* @returns `true` if the address is a member of the role, or `false` if not
|
||||
*
|
||||
* @twfeature PermissionsEnumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useisaddressrole?utm_source=sdk | Documentation}
|
||||
* @permissionControl
|
||||
*/
|
||||
export function useIsAddressRole<TContract extends ContractWithRoles>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -181,9 +271,10 @@ export function useIsAddressRole<TContract extends ContractWithRoles>(
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to overwrite all roles on the contract
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
* @returns A mutation object to overwrite all roles on the contract
|
||||
* @twfeature Permissions
|
||||
* @permissionControl
|
||||
*/
|
||||
export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -212,37 +303,75 @@ export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Grant a role to a specific address
|
||||
* Hook for granting a role on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: grantRole,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useGrantRole(contract);
|
||||
* import { useGrantRole, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to grant role", error);
|
||||
* }
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* const roleToGrant = "{{role}}";
|
||||
* const walletAddressToGrant = "{{wallet_address}}";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: grantRole, isLoading, error } = useGrantRole(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => grantRole({ role: "admin", address: {{wallet_address}} })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* grantRole({
|
||||
* role: roleToGrant, // name of your role.
|
||||
* address: walletAddressToGrant, // address to grant the role to.
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Grant Role
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to grant a member of a role on the contract
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns A mutation object to grant a member of a role on the contract
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useGrantRole(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function accepts an object with the following properties:
|
||||
*
|
||||
* #### role
|
||||
* The name of the role to grant the address.
|
||||
*
|
||||
* Accepts any `string` value to include custom-defined roles.
|
||||
*
|
||||
* Also accepts the default roles available on the [prebuilt contracts](https://portal.thirdweb.com/pre-built-contracts):
|
||||
*
|
||||
* ```ts
|
||||
* string |
|
||||
* "admin" |
|
||||
* "minter" |
|
||||
* "transfer" |
|
||||
* "lister" |
|
||||
* "asset" |
|
||||
* "unwrap" |
|
||||
* "pauser" |
|
||||
* "factory";
|
||||
* ```
|
||||
*
|
||||
* #### address
|
||||
* The address to grant the role to.
|
||||
*
|
||||
* To use the address of the connected wallet, use the `useAddress` hook.
|
||||
*
|
||||
* @twfeature Permissions | PermissionsEnumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usegrantrole?utm_source=sdk | Documentation}
|
||||
* @permissionControl
|
||||
*/
|
||||
export function useGrantRole<TContract extends ContractWithRoles>(
|
||||
contract: RequiredParam<TContract>,
|
||||
@@ -272,37 +401,65 @@ export function useGrantRole<TContract extends ContractWithRoles>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a role from a specific address
|
||||
* Hook for revoking a wallet address from a role on a smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement [`Permissions`](https://portal.thirdweb.com/contracts/build/extensions/general/Permissions) interface
|
||||
*
|
||||
* The wallet address that initiates this transaction must have the relevant permissions on the contract to remove the role from the wallet address (typically `"admin"` level required).
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: revokeRole,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useRevokeRole(contract);
|
||||
* import { useContract, useRevokeRole, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to revoke role", error);
|
||||
* }
|
||||
* // Your smart contract address (must implement permission controls)
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* const walletAddress = "{{wallet_address}}";
|
||||
*
|
||||
* function App() {
|
||||
* // Contract must be a contract that implements the Permission Controls interface
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: revokeRole, isLoading, error } = useRevokeRole(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => revokeRole({ role: "admin", address: {{wallet_address}} })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* revokeRole({
|
||||
* role: "admin",
|
||||
* address: walletAddress,
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Revoke Role
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link SmartContract}
|
||||
* @returns a mutation object that can be used to revoke a role from a member on the contract
|
||||
* @param contract - Instance of a `SmartContract`
|
||||
*
|
||||
* @returns A mutation object to revoke a role from a member on the contract
|
||||
* #### role (required)
|
||||
*
|
||||
* The role to revoke from the wallet address.
|
||||
*
|
||||
* Can be any custom role, or a built-in role, such as:
|
||||
* - `"admin"`
|
||||
* - `"transfer"`
|
||||
* - `"minter"`
|
||||
* - `"pauser"`
|
||||
* - `"lister"`
|
||||
* - `"asset"`
|
||||
* - `"unwrap"`
|
||||
* - `"factory"`
|
||||
*
|
||||
* #### address
|
||||
*
|
||||
* The wallet address to revoke the role from.
|
||||
*
|
||||
* To use the connected wallet address, use the `useAddress` hook.
|
||||
*
|
||||
* @twfeature Permissions | PermissionsEnumerable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.userevokerole?utm_source=sdk | Documentation}
|
||||
* @permissionControl
|
||||
*/
|
||||
export function useRevokeRole<TContract extends ContractWithRoles>(
|
||||
contract: RequiredParam<TContract>,
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
requiredParamInvariant,
|
||||
RequiredParam,
|
||||
} from "../../../core/query-utils/required-param";
|
||||
import { useSDKChainId } from "../useSDK";
|
||||
import { useSDK, useSDKChainId } from "../useSDK";
|
||||
import {
|
||||
ClaimTokenParams,
|
||||
getErc20,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "../../types";
|
||||
import {
|
||||
cacheKeys,
|
||||
invalidateBalances,
|
||||
invalidateContractAndBalances,
|
||||
} from "../../utils/cache-keys";
|
||||
import { useQueryWithNetwork } from "../query-utils/useQueryWithNetwork";
|
||||
@@ -20,8 +21,9 @@ import {
|
||||
useMutation,
|
||||
UseMutationResult,
|
||||
useQueryClient,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
import type { providers } from "ethers";
|
||||
import type { BigNumber, providers } from "ethers";
|
||||
import invariant from "tiny-invariant";
|
||||
|
||||
/** **********************/
|
||||
@@ -29,19 +31,38 @@ import invariant from "tiny-invariant";
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Get the total supply for this token
|
||||
* Hook for fetching the total supply of an ERC20 token.
|
||||
*
|
||||
* This takes into account the increase and decrease in supply when tokens are minted and burned.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: totalSupply, isLoading, error } = useTokenSupply(contract);
|
||||
* ```jsx
|
||||
* import { useTokenSupply } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { data, isLoading, error } = useTokenSupply(contractAddress);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a response object that includes the total minted supply
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns Hook's `data` object includes the total supply of the token in the `value` property as a `BigNumber` object.
|
||||
*
|
||||
* @twfeature ERC20
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetokensupply?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useTokenSupply(contract: RequiredParam<TokenContract>) {
|
||||
export function useTokenSupply(
|
||||
contract: RequiredParam<TokenContract>,
|
||||
): UseQueryResult<
|
||||
{
|
||||
symbol: string;
|
||||
value: BigNumber;
|
||||
name: string;
|
||||
decimals: number;
|
||||
displayValue: string;
|
||||
},
|
||||
unknown
|
||||
> {
|
||||
const contractAddress = contract?.getAddress();
|
||||
return useQueryWithNetwork(
|
||||
cacheKeys.contract.token.totalSupply(contractAddress),
|
||||
@@ -60,22 +81,42 @@ export function useTokenSupply(contract: RequiredParam<TokenContract>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token balance for a specific wallet
|
||||
* Hook for fetching the balance a wallet has for a specific ERC20 token.
|
||||
*
|
||||
* __This hook is for _custom_ ERC20 tokens. For native tokens such as Ether, use `useBalance` or `useBalanceForAddress`__
|
||||
*
|
||||
* Available to use on contracts that implement the ERC20 interface.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: balance, isLoading, error } = useTokenBalance(contract, "{{wallet_address}}");
|
||||
* ```jsx
|
||||
* import { useTokenBalance, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress, "token");
|
||||
* const { data, isLoading, error } = useTokenBalance(contract, walletAddress);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a response object that includes the balance of the address
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns Hook's `data` object includes the token balance for given wallet address
|
||||
*
|
||||
* @twfeature ERC20
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetokenbalance?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useTokenBalance(
|
||||
contract: RequiredParam<TokenContract>,
|
||||
walletAddress: RequiredParam<WalletAddress>,
|
||||
) {
|
||||
): UseQueryResult<
|
||||
{
|
||||
symbol: string;
|
||||
value: BigNumber;
|
||||
name: string;
|
||||
decimals: number;
|
||||
displayValue: string;
|
||||
},
|
||||
unknown
|
||||
> {
|
||||
const contractAddress = contract?.getAddress();
|
||||
const erc20 = getErc20(contract);
|
||||
return useQueryWithNetwork(
|
||||
@@ -96,17 +137,29 @@ export function useTokenBalance(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token decimals
|
||||
* Hook for fetching the [decimals](https://docs.openzeppelin.com/contracts/3.x/erc20#a-note-on-decimals)
|
||||
* of an [ERC20](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20) token.
|
||||
*
|
||||
* Tokens usually opt for a value of `18`, imitating the relationship between Ether and Wei.
|
||||
* Therefore, `18` is the default value returned by this function, unless your ERC20 contract explicitly overrides it.
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { data: decimals, isLoading, error } = useTokenDecimals(contract);
|
||||
*
|
||||
* ```jsx
|
||||
* import { useTokenDecimals, useContract } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress, "token");
|
||||
* const { data, isLoading, error } = useTokenDecimals(contract);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a response object that includes the decimals of the ERC20 token
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns The hook's `data` property, once loaded, contains the `number` that represents the number of decimals of the ERC20 token.
|
||||
*
|
||||
* @twfeature ERC20
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetokendecimals?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useTokenDecimals(contract: RequiredParam<TokenContract>) {
|
||||
const contractAddress = contract?.getAddress();
|
||||
@@ -132,37 +185,64 @@ export function useTokenDecimals(contract: RequiredParam<TokenContract>) {
|
||||
/** **********************/
|
||||
|
||||
/**
|
||||
* Mint tokens
|
||||
* Hook for minting new tokens in an ERC20 smart contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [ERC20Mintable](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20BatchMintable)
|
||||
* interface, such as the [Token](https://thirdweb.com/thirdweb.eth/TokenERC20) contract.
|
||||
*
|
||||
* The wallet address that initiates this transaction must have minting permissions on the contract.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: mintTokens,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useMintToken(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to mint tokens", error);
|
||||
* }
|
||||
* ```jsx
|
||||
* import { useContract, useMintToken, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* const walletAddress = "{{wallet_address}}";
|
||||
* const tokenAmount = "{{token_amount}}";
|
||||
*
|
||||
* function App() {
|
||||
* // Contract must be an ERC-20 contract that implements the ERC20Mintable interface
|
||||
* const { contract } = useContract(contractAddress, "token");
|
||||
* const { mutateAsync: mintToken, isLoading, error } = useMintToken(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => mintTokens({ to: "{{wallet_address}}", amount: 1000 })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* mintToken({
|
||||
* amount: tokenAmount, // Quantity to mint
|
||||
* to: walletAddress, // Address to mint to
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Mint!
|
||||
* </button>
|
||||
* Mint Token
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a mutation object that can be used to mint new tokens to the connected wallet
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns A mutation object to mint new tokens to the connected wallet
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useMintToken(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object as an argument with the following properties:
|
||||
*
|
||||
* #### amount
|
||||
* The quantity of tokens to mint. Can be a `string` or `number`.
|
||||
*
|
||||
* #### to
|
||||
* The wallet address to mint the new tokens to.
|
||||
*
|
||||
* To use the connected wallet address, use the `useAddress` hook.
|
||||
*
|
||||
* @twfeature ERC20Mintable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useminttoken?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useMintToken(
|
||||
contract: RequiredParam<TokenContract>,
|
||||
@@ -204,37 +284,64 @@ export function useMintToken(
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim tokens to a specific wallet
|
||||
* Hook for claiming a ERC20 tokens from a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement both the [ERC20](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20) interface
|
||||
* and the [`claim`](https://portal.thirdweb.com/contracts/build/extensions/erc-721/ERC721Claimable) function,
|
||||
* such as the [Token Drop](https://thirdweb.com/thirdweb.eth/DropERC20).
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: claimTokens,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useClaimToken(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to claim tokens", error);
|
||||
* }
|
||||
* ```jsx
|
||||
* import { useClaimToken, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: claimToken, isLoading, error } = useClaimToken(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => claimTokens({ to: "{{wallet_address}}", amount: 100 })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* claimToken({
|
||||
* to: "{{wallet_address}}", // Use useAddress hook to get current wallet address
|
||||
* amount: 100, // Amount of token to claim
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Claim Tokens!
|
||||
* </button>
|
||||
* Claim Token
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a mutation object that can be used to tokens to the wallet specified in the params
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns A mutation object to tokens to the wallet specified in the params
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useClaimToken(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object as an argument with the following properties:
|
||||
*
|
||||
* #### to (required)
|
||||
* Likely, you will want to claim the token to the currently connected wallet address.
|
||||
*
|
||||
* You can use the `useAddress` hook to get this value.
|
||||
*
|
||||
* #### amount (required)
|
||||
* The amount of tokens to be claimed.
|
||||
*
|
||||
* #### checkERC20Allowance (optional)
|
||||
* Boolean value to check whether the current wallet has enough allowance to pay for claiming the tokens before
|
||||
* attempting to claim the tokens.
|
||||
*
|
||||
* Defaults to `true`.
|
||||
*
|
||||
* @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useclaimtoken?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useClaimToken(contract: RequiredParam<TokenContract>) {
|
||||
const activeChainId = useSDKChainId();
|
||||
@@ -265,37 +372,65 @@ export function useClaimToken(contract: RequiredParam<TokenContract>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer tokens to a specific wallet
|
||||
* Hook for transferring tokens on an ERC20 contract.
|
||||
*
|
||||
* Available to use on contracts that implement the [ERC20](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20)
|
||||
* interface, such as the [Token](https://thirdweb.com/thirdweb.eth/TokenERC20) contract.
|
||||
*
|
||||
* The wallet address that initiates this transaction must have a balance of tokens
|
||||
* greater than or equal to the amount being transferred.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* import { useContract, useTransferToken, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const contractAddress = "{{contract_address}}";
|
||||
* const toAddress = "{{to_address}}";
|
||||
* const amount = "{{amount}}";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const {
|
||||
* mutate: transferTokens,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useTransferToken(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to transfer tokens", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => transferTokens({ to: "{{wallet_address}}", amount: 1000 })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* transferTokens({
|
||||
* to: toAddress, // Address to transfer to
|
||||
* amount: amount, // Amount to transfer
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Transfer
|
||||
* </button>
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a mutation object that can be used to transfer tokens
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns A mutation object to transfer tokens
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useTransferToken(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object as an argument with the following properties:
|
||||
*
|
||||
* #### to
|
||||
* The wallet address to transfer tokens to.
|
||||
*
|
||||
* #### amount
|
||||
* The quantity of tokens to transfer. Can be a `string` or `number`.
|
||||
*
|
||||
* @twfeature ERC20
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetransfertoken?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useTransferToken(contract: RequiredParam<TokenContract>) {
|
||||
const activeChainId = useSDKChainId();
|
||||
@@ -324,37 +459,130 @@ export function useTransferToken(contract: RequiredParam<TokenContract>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Airdrop tokens to a list of wallets
|
||||
* A hook to transfer native token (of the active chain) to another wallet
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: transferBatchTokens,
|
||||
* mutate: transferNativeToken,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useTransferToken(contract);
|
||||
* } = useTransferNativeToken();
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to transfer batch tokens", error);
|
||||
* console.error("failed to transfer tokens", error);
|
||||
* }
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => transferBatchTokens([{ to: "{{wallet_address}}", amount: 1000 }, { to: "{{wallet_address}}", amount: 2000 }])}
|
||||
* onClick={() => transferNativeToken({ to: "{{wallet_address}}", amount: "0.1" })}
|
||||
* >
|
||||
* Airdrop
|
||||
* Transfer
|
||||
* </button>
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a mutation object that can be used to transfer batch tokens
|
||||
* @returns A Mutation object to transfer native tokens
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useTransferNativeToken();
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object containing `to` and `amount` properties.
|
||||
*
|
||||
* - `to` - The wallet address to transfer tokens to. Must be a `string`.
|
||||
* - `amount` - The amount of tokens to transfer. Must be a `number`.
|
||||
*
|
||||
* @token
|
||||
*/
|
||||
export function useTransferNativeToken() {
|
||||
const sdk = useSDK();
|
||||
const activeChainId = useSDKChainId();
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation(
|
||||
(data: TokenParams) => {
|
||||
const { to, amount } = data;
|
||||
invariant(sdk, "SDK is not initialized");
|
||||
return sdk.wallet.transfer(to, amount);
|
||||
},
|
||||
{
|
||||
onSettled: () => invalidateBalances(queryClient, activeChainId),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for transferring ERC20 tokens to multiple recipients in a single transaction (i.e. airdrop).
|
||||
*
|
||||
* Available to use on contracts that implement the [ERC20](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20) interface.
|
||||
*
|
||||
* The wallet that initiates this transaction must have sufficient balance to cover the total amount of tokens being transferred
|
||||
* and must have transfer permissions on the contract, i.e. tokens are not soulbound.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* Provide your token contract instance from the `useContract` hook to the hook.
|
||||
*
|
||||
* Then, provide an array of objects with the `to` and `amount` properties to the function.
|
||||
*
|
||||
* ```jsx
|
||||
* import {
|
||||
* useTransferBatchToken,
|
||||
* useContract,
|
||||
* Web3Button,
|
||||
* } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress, "token");
|
||||
* const {
|
||||
* mutateAsync: transferBatchToken,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useTransferBatchToken(contract);
|
||||
*
|
||||
* return (
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* transferBatchToken([
|
||||
* {
|
||||
* to: "{{wallet_address}}", // Transfer 10 tokens to a wallet
|
||||
* amount: 10,
|
||||
* },
|
||||
* {
|
||||
* to: "{{wallet_address}}", // Transfer 20 tokens to another wallet
|
||||
* amount: 20,
|
||||
* },
|
||||
* ])
|
||||
* }
|
||||
* >
|
||||
* Transfer Batch Tokens
|
||||
* </Web3Button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns A Mutation object to transfer batch tokens
|
||||
*
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useTransferBatchToken(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
*
|
||||
* The mutation function takes an array of objects containing `to` and `amount` properties.
|
||||
*
|
||||
* - `to` - The wallet address to transfer tokens to. Must be a `string`.
|
||||
* - `amount` - The amount of tokens to transfer. Must be a `number`.
|
||||
*
|
||||
* @twfeature ERC20
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usetransferbatchtoken?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useTransferBatchToken(contract: RequiredParam<TokenContract>) {
|
||||
const activeChainId = useSDKChainId();
|
||||
@@ -390,37 +618,52 @@ export function useTransferBatchToken(contract: RequiredParam<TokenContract>) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Burn tokens
|
||||
* Hook for burning ERC20 tokens on a smart contract.
|
||||
*
|
||||
* Available to use on smart contracts that implement the [ERC20](https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20) standard.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
* const Component = () => {
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* const {
|
||||
* mutate: burnTokens,
|
||||
* isLoading,
|
||||
* error,
|
||||
* } = useBurnToken(contract);
|
||||
*
|
||||
* if (error) {
|
||||
* console.error("failed to burn tokens", error);
|
||||
* }
|
||||
* ```jsx
|
||||
* import { useBurnToken, useContract, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { contract } = useContract(contractAddress);
|
||||
* const { mutateAsync: burnToken, isLoading, error } = useBurnToken(contract);
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* disabled={isLoading}
|
||||
* onClick={() => burnTokens({ amount: 1000 })}
|
||||
* <Web3Button
|
||||
* contractAddress={contractAddress}
|
||||
* action={() =>
|
||||
* burnToken({
|
||||
* amount: "10", // Amount of tokens to burn
|
||||
* })
|
||||
* }
|
||||
* >
|
||||
* Burn!
|
||||
* </button>
|
||||
* Burn Token
|
||||
* </Web3Button>
|
||||
* );
|
||||
* };
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param contract - an instance of a {@link TokenContract}
|
||||
* @returns a mutation object that can be used to burn tokens from the connected wallet
|
||||
* @param contract - Instance of a `TokenContract`
|
||||
*
|
||||
* @returns
|
||||
* A mutation object to burn tokens from the connected wallet
|
||||
* ```ts
|
||||
* const { mutateAsync, isLoading, error } = useBurnToken(contract);
|
||||
* ```
|
||||
*
|
||||
* ### options
|
||||
* The mutation function takes an object as an argument with the following properties:
|
||||
*
|
||||
* #### amount (required)
|
||||
* The amount of tokens to burn.
|
||||
*
|
||||
* The wallet initiating this transaction must have at least this amount of tokens.
|
||||
*
|
||||
* @twfeature ERC20Burnable
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useburntoken?utm_source=sdk | Documentation}
|
||||
* @token
|
||||
*/
|
||||
export function useBurnToken(contract: RequiredParam<TokenContract>) {
|
||||
const activeChainId = useSDKChainId();
|
||||
|
||||
@@ -3,6 +3,10 @@ import { useWallet } from "../../../core/hooks/wallet-hooks";
|
||||
import { useThirdwebAuthContext } from "../../contexts/thirdweb-auth";
|
||||
import { useMemo } from "react";
|
||||
|
||||
/**
|
||||
* Hook to get `ThirdwebAuth` instance
|
||||
* @auth
|
||||
*/
|
||||
export function useAuth() {
|
||||
const wallet = useWallet();
|
||||
const authConfig = useThirdwebAuthContext();
|
||||
|
||||
@@ -7,13 +7,57 @@ import invariant from "tiny-invariant";
|
||||
import { AUTH_TOKEN_STORAGE_KEY } from "../../../core/constants/auth";
|
||||
|
||||
/**
|
||||
* Hook to securely login to a backend with the connected wallet. The backend
|
||||
* authentication URL must be configured on the ThirdwebProvider.
|
||||
* Hook to prompt the user to sign in with their wallet using [auth](https://portal.thirdweb.com/wallets/auth)
|
||||
*
|
||||
* @returns - A function to invoke to login with the connected wallet, and an isLoading state.
|
||||
* Requires the `authConfig` prop to be configured on the `ThirdwebProvider`
|
||||
*
|
||||
* @see {@link https://portal.thirdweb.com/react/react.uselogin?utm_source=sdk | Documentation}
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useLogin } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { isLoading, login } = useLogin();
|
||||
*
|
||||
* return (
|
||||
* <button onClick={() => login()}>
|
||||
* {isLoading ? "Loading..." : "Sign in with Ethereum"}
|
||||
* </button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function to invoke to login with the connected wallet, and an `isLoading` state that indicates if the login request is in progress
|
||||
*
|
||||
* ### login
|
||||
*
|
||||
* The `login` function accepts an optional `LoginOptions` object as an argument.
|
||||
*
|
||||
* This configuration follows the [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) Sign in with Ethereum standard.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useLogin, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { login, isLoading } = useLogin();
|
||||
*
|
||||
* const loginOptions = {
|
||||
* domain: "https://your-domain.com", // Your dapp domain
|
||||
* statement: "My statement", // Text that the user will sign
|
||||
* uri: "https://your-domain.com/login", // RFC 3986 URI referring to the resource that is the subject of the signing
|
||||
* version: "1.0", // The current version of the message, which MUST be 1 for this specification.
|
||||
* chainId: "mainnet", // Chain ID to which the session is bound
|
||||
* nonce: "my-nonce", // randomized token typically used to prevent replay attacks
|
||||
* expirationTime: new Date(2021, 1, 1), // When this message expires
|
||||
* invalidBefore: new Date(2020, 12, 1), // When this message becomes valid
|
||||
* resources: ["balance", "history", "info"], // A list of information or references to information the user wishes to have resolved
|
||||
* };
|
||||
*
|
||||
* return <Web3Button action={() => login(loginOptions)}>Login</Web3Button>;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @auth
|
||||
*/
|
||||
export function useLogin() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -5,13 +5,26 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import invariant from "tiny-invariant";
|
||||
|
||||
/**
|
||||
* Hook to logout the connected wallet from the backend.
|
||||
* The backend logout URL must be configured on the ThirdwebProvider.
|
||||
* Hook for signing out of a wallet after a user has logged in using `useLogin`
|
||||
*
|
||||
* @returns - A function to invoke to logout.
|
||||
* @example
|
||||
* ```jsx
|
||||
* import { useLogout } from "@thirdweb-dev/react";
|
||||
*
|
||||
* @see {@link https://portal.thirdweb.com/react/react.uselogout?utm_source=sdk | Documentation}
|
||||
* function App() {
|
||||
* const { logout, isLoading } = useLogout();
|
||||
*
|
||||
* return (
|
||||
* <button onClick={() => logout()}>
|
||||
* {isLoading ? "Logging out..." : "Logout"}
|
||||
* </button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns object containing a `logout` function and an `isLoading` state that indicates if the logout request is in progress
|
||||
*
|
||||
* @auth
|
||||
*/
|
||||
export function useLogout() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -6,10 +6,18 @@ import invariant from "tiny-invariant";
|
||||
/**
|
||||
* Hook to switch the account of the active wallet
|
||||
*
|
||||
* @returns - A function to invoke to switch account.
|
||||
* @example
|
||||
* ```ts
|
||||
* const { switchAccount, isLoading } = useSwitchAccount();
|
||||
*
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useswitchaccount?utm_source=sdk | Documentation}
|
||||
* const handleSwitchAccount = async (address: string) => {
|
||||
* await switchAccount(address);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A function to invoke to switch account and a boolean to indicate if it is in progress
|
||||
*
|
||||
* @auth
|
||||
*/
|
||||
export function useSwitchAccount() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -5,6 +5,9 @@ import type { Json, User } from "@thirdweb-dev/auth";
|
||||
import invariant from "tiny-invariant";
|
||||
import { AUTH_TOKEN_STORAGE_KEY } from "../../../core/constants/auth";
|
||||
|
||||
/**
|
||||
* @auth
|
||||
*/
|
||||
export interface UserWithData<
|
||||
TData extends Json = Json,
|
||||
TContext extends Json = Json,
|
||||
@@ -13,11 +16,19 @@ export interface UserWithData<
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get the currently logged in user.
|
||||
* Hook for retrieving information about the currently signed-in user using [auth](https://portal.thirdweb.com/wallets/auth).
|
||||
*
|
||||
* @returns - The currently logged in user or null if not logged in, as well as a loading state.
|
||||
* Useful to get the user's address and session data, or `undefined` if no user is signed in.
|
||||
*
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useuser?utm_source=sdk | Documentation}
|
||||
* ```jsx
|
||||
* import { useUser } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { user, isLoggedIn, isLoading } = useUser();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @auth
|
||||
*
|
||||
*/
|
||||
export function useUser<
|
||||
|
||||
@@ -3,8 +3,9 @@ import { showDeprecationWarning } from "../../utils/deprecation-warning";
|
||||
import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
*
|
||||
* Hook for getting an instance of an `Edition` contract. This contract is used to interface with ERC1155 compliant NFTs.
|
||||
* @param contractAddress - the address of the Edition contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Edition contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +32,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const edition = useEdition("0x1234...");
|
||||
* + const edition = useContract("0x1234...", "edition").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useEdition(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of an `EditionDrop` contract. This contract is used to interface with ERC1155 compliant NFTs that can be lazily minted.
|
||||
* @param contractAddress - the address of the Edition Drop contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Edition Drop contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -30,6 +30,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const editionDrop = useEditionDrop("0x1234...");
|
||||
* + const editionDrop = useContract("0x1234...", "edition-drop").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useEditionDrop(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of a `Marketplace` contract. This contract is used to support marketplace for purchase and sale of on-chain assets.
|
||||
* @param contractAddress - the address of the Marketplace contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Marketplace contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const marketplace = useMarketplace("0x1234...");
|
||||
* + const marketplace = useContract("0x1234...", "marketplace").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useMarketplace(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of an `Multiwrap` contract. This contract is an ERC721 in which you can wrap ERC721, ERC1155 and ERC20 tokens.
|
||||
* @param contractAddress - the address of the Multiwrap contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Multiwrap contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -30,6 +30,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const multiwrap = useMultiwrap("0x1234...");
|
||||
* + const multiwrap = useContract("0x1234...", "multiwrap").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useMultiwrap(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of an `NFTCollection` contract. This contract is meant to interface with ERC721 compliant NFTs.
|
||||
* @param contractAddress - the address of the NFT Collection contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the NFT Collection contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const nftCollection = useNFTCollection("0x1234...");
|
||||
* + const nftCollection = useContract("0x1234...", "nft-collection").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useNFTCollection(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of an `NFTDrop` contract. This contract is meant to interface with ERC721 compliant NFTs that can be lazily minted.
|
||||
* @param contractAddress - the address of the NFT Drop contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the NFT Drop contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -30,6 +30,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const nftDrop = useNFTDrop("0x1234...");
|
||||
* + const nftDrop = useContract("0x1234...", "nft-drop").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useNFTDrop(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of a `Pack` contract. This contract supports the creation of on-chain luck-based lootboxes.
|
||||
* @param contractAddress - the address of the Pack contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Pack contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,8 @@ import { useContract } from "../async/contracts";
|
||||
* - const pack = usePack("0x1234...");
|
||||
* + const pack = useContract("0x1234...", "pack").contract;
|
||||
* ```
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function usePack(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of an `SignatureDrop` contract. This contract is meant to interface with ERC721 compliant NFTs that can be lazily minted.
|
||||
* @param contractAddress - the address of the NFT Drop contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the NFT Drop contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -30,6 +30,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const signatureDrop = useSignatureDrop("0x1234...");
|
||||
* + const signatureDrop = useContract("0x1234...", "signature-drop").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useSignatureDrop(contractAddress?: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of a `Split` contract. This contract supports fund distribution to multiple parties.
|
||||
* @param contractAddress - the address of the Split contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Split contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,7 @@ import { useContract } from "../async/contracts";
|
||||
* - const split = useSplit("0x1234...");
|
||||
* + const split = useContract("0x1234...", "split").contract;
|
||||
* ```
|
||||
* @internal
|
||||
*/
|
||||
export function useSplit(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of a `Token` contract. This contract supports ERC20 compliant tokens.
|
||||
* @param contractAddress - the address of the Token contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Token contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,8 @@ import { useContract } from "../async/contracts";
|
||||
* - const token = useToken("0x1234...");
|
||||
* + const token = useContract("0x1234...", "token").contract;
|
||||
* ```
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useToken(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of a `Token Drop` contract.
|
||||
* @param contractAddress - the address of the Token Drop contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Token Drop contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,9 @@ import { useContract } from "../async/contracts";
|
||||
* - const token = useTokenDrop("0x1234...");
|
||||
* + const token = useContract("0x1234...", "token-drop").contract;
|
||||
* ```
|
||||
*
|
||||
* @token
|
||||
* @internal
|
||||
*/
|
||||
export function useTokenDrop(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useContract } from "../async/contracts";
|
||||
|
||||
/**
|
||||
* Hook for getting an instance of an `Vote` contract. This contract enables fully featured voting-based decentralized governance systems.
|
||||
* @param contractAddress - the address of the Vote contract, found in your thirdweb dashboard
|
||||
* @param contractAddress - The address of the Vote contract, found in your thirdweb dashboard
|
||||
*
|
||||
* @example
|
||||
* ```javascript
|
||||
@@ -31,6 +31,8 @@ import { useContract } from "../async/contracts";
|
||||
* - const vote = useVote("0x1234...");
|
||||
* + const vote = useContract("0x1234...", "vote").contract;
|
||||
* ```
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function useVote(contractAddress: RequiredParam<string>) {
|
||||
showDeprecationWarning(
|
||||
|
||||
@@ -1,9 +1,48 @@
|
||||
import { useSDK } from "../useSDK";
|
||||
|
||||
/**
|
||||
* Get the configured `ThirdwebStorage` instance
|
||||
* @returns The `storageInterface` configured on the `ThirdwebProvider`
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usestorage?utm_source=sdk | Documentation}
|
||||
* Get the instance of the `ThirdwebStorage` class being used by the `ThirdwebProvider`
|
||||
*
|
||||
* Allows you to use the TypeScript SDK functionality of [Storage](https://portal.thirdweb.com/infrastructure/storage/overview) in your React app.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useStorage } from "@thirdweb-dev/react";
|
||||
*
|
||||
* export default function Component() {
|
||||
* const storage = useStorage();
|
||||
*
|
||||
* // Now you can use the functionality of the ThirdwebStorage class:
|
||||
* storage?.download(); // Download a file from IPFS
|
||||
* storage?.upload(); // Upload a file to IPFS
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* ### API Key
|
||||
*
|
||||
* You will require an API key to use thirdweb’s storage services with the SDK. If you haven’t created a key yet you can do so for free from the [**thirdweb dashboard**](https://thirdweb.com/create-api-key).
|
||||
*
|
||||
* You can then obtain a `clientId` from the API key which you will need to pass to the `ThirdwebProvider` component:
|
||||
*
|
||||
*
|
||||
* ```jsx
|
||||
* import { ThirdwebProvider } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const App = () => {
|
||||
* return (
|
||||
* <ThirdwebProvider clientId="YOUR_CLIENT_ID">
|
||||
* <YourApp />
|
||||
* </ThirdwebProvider>
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* Storage can also be configured using the `storageInterface` prop on `ThirdwebProvider`
|
||||
*
|
||||
* @storage
|
||||
*/
|
||||
export function useStorage() {
|
||||
const sdk = useSDK();
|
||||
|
||||
@@ -9,11 +9,7 @@ interface StorageUploadOptions<T extends UploadOptions> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook used to upload any files or JSON data to decentralized storage systems like IPFS,
|
||||
* using the `storageInterface` configured on the `ThirdwebProvider`
|
||||
*
|
||||
* @param options - Configure the options for your upload
|
||||
* @returns Function used to upload files or JSON to decentralized storage systems
|
||||
* Hook for uploading files to IPFS and retrieving the IPFS URI.
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
@@ -35,7 +31,90 @@ interface StorageUploadOptions<T extends UploadOptions> {
|
||||
* )
|
||||
* }
|
||||
* ```
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usestorageupload?utm_source=sdk | Documentation}
|
||||
*
|
||||
* @remarks
|
||||
* ### API key
|
||||
*
|
||||
* You will require an API key to use thirdweb’s storage services with the SDK. If you haven’t created a key yet you can do so for free from the [**thirdweb dashboard**](https://thirdweb.com/create-api-key).
|
||||
*
|
||||
* You can then obtain a `clientId` from the API key which you will need to pass to the [`ThirdwebProvider`](/react/react.thirdwebprovider) component:
|
||||
*
|
||||
* ```jsx
|
||||
* import { ThirdwebProvider } from "@thirdweb/react";
|
||||
*
|
||||
* const App = () => {
|
||||
* return (
|
||||
* <ThirdwebProvider clientId="YOUR_CLIENT_ID">
|
||||
* <YourApp />
|
||||
* </ThirdwebProvider>
|
||||
* );
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* @param options - Configure the options for your upload
|
||||
* ### rewriteFileNames (optional)
|
||||
*
|
||||
* If specified, will rewrite file names to numbers for use on-chain.
|
||||
*
|
||||
* Useful to use with NFT contracts that map token IDs to files.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useStorageUpload } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { mutateAsync: upload } = useStorageUpload({
|
||||
* rewriteFileNames: {
|
||||
* fileStartNumber: 1,
|
||||
* },
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### uploadWithGatewayUrl (optional)
|
||||
*
|
||||
* If specified, any URLs with schemes will be replaced with resolved URLs before upload.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useStorageUpload } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { mutateAsync: upload } = useStorageUpload({
|
||||
* uploadWithGatewayUrl: true,
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### onProgress (optional)
|
||||
*
|
||||
* Callback that gets triggered when file upload progresses.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useStorageUpload } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { mutateAsync: upload } = useStorageUpload({
|
||||
* onProgress: (progress) => {
|
||||
* console.log(progress);
|
||||
* },
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### uploadWithoutDirectory (optional)
|
||||
*
|
||||
* If specified, will upload a single file without wrapping it in a directory.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useStorageUpload } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { mutateAsync: upload } = useStorageUpload({
|
||||
* uploadWithoutDirectory: true,
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @storage
|
||||
*/
|
||||
export function useStorageUpload<
|
||||
T extends UploadOptions = IpfsUploadBatchOptions,
|
||||
|
||||
@@ -2,31 +2,25 @@ import { useSDKChainId } from "./useSDK";
|
||||
import { useChainId } from "./wallet";
|
||||
|
||||
/**
|
||||
* Hook for checking whether the connected wallet is on the correct network specified by the `network` passed to the `<ThirdwebProvider />`.
|
||||
*
|
||||
* ```javascript
|
||||
* import { useNetworkMismatch } from "@thirdweb-dev/react"
|
||||
* ```
|
||||
*
|
||||
* @returns `true` if the chainId of the connected wallet is different from the chainId of the network passed into `<ThirdwebProvider />`
|
||||
*
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usenetworkmismatch?utm_source=sdk | Documentation}
|
||||
* Hook for checking whether the connected wallet is currently on the correct chain,
|
||||
* i.e. the chain specified in the `activeChain` on the `ThirdwebProvider`.
|
||||
*
|
||||
* @example
|
||||
* You can check if a users wallet is connected to the correct chain ID as follows:
|
||||
* ```javascript
|
||||
* import { useNetworkMismatch } from "@thirdweb-dev/react"
|
||||
*
|
||||
* ```jsx
|
||||
* import { useNetworkMismatch } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const App = () => {
|
||||
* const isMismatched = useNetworkMismatch()
|
||||
*
|
||||
* return <div>{isMismatched}</div>
|
||||
* }
|
||||
* const isMismatched = useNetworkMismatch();
|
||||
* };
|
||||
* ```
|
||||
*
|
||||
* From here, you can prompt users to switch their network using the `useNetwork` hook.
|
||||
* Using this value, you can prompt users to switch their network using the `useSwitchChain` hook.
|
||||
*
|
||||
* @public
|
||||
* @returns
|
||||
* Returns `true` if the `chainId` of the connected wallet is different from the `chainId` of the `activeChain` on the `ThirdwebProvider` component
|
||||
*
|
||||
* @networkConnection
|
||||
*/
|
||||
export function useNetworkMismatch() {
|
||||
const walletChainId = useChainId();
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useWallet } from "../../core/hooks/wallet-hooks";
|
||||
|
||||
/**
|
||||
* Hook for getting the address of the personal wallet connected to the current wallet connection.
|
||||
*
|
||||
* This is only relevant if the current connected wallet uses a personal wallet - For Example - Smart Wallet and Safe.
|
||||
* @walletConnection
|
||||
*/
|
||||
export const usePersonalWalletAddress = () => {
|
||||
const [personalWalletAddress, setPersonalWalletAddress] = useState<
|
||||
string | undefined
|
||||
|
||||
@@ -16,13 +16,29 @@ export function useSDKContext(): TWSDKContext {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to get the instance of the `ThirdwebSDK` class being used by the `ThirdwebProvider` component.
|
||||
*
|
||||
* This gives access to all of the functionality of the TypeScript SDK in your React app.
|
||||
*
|
||||
* - If there is a connected wallet, the SDK is instantiated from the connected wallet’s signer. Meaning all transactions are initiated from the connected wallet.
|
||||
* - If there is no connected wallet, the SDK is in read-only mode on the activeChain.
|
||||
*
|
||||
* @returns {@link ThirdwebSDK}
|
||||
* Access the instance of the thirdweb SDK created by the ThirdwebProvider
|
||||
* to call methods using the connected wallet on the desiredChainId.
|
||||
* @example
|
||||
* ```javascript
|
||||
* const sdk = useSDK();
|
||||
* ```tsx
|
||||
* import { useSDK } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const sdk = useSDK();
|
||||
*
|
||||
* // Now you use all of the TypeScript SDK functionality
|
||||
* // For example, deploy a new contract from the connected wallet.
|
||||
* async function deployContract() {
|
||||
* sdk?.deployer.deployNFTDrop({
|
||||
* name: "My NFT Drop",
|
||||
* primary_sale_recipient: "{{wallet_address}}",
|
||||
* });
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function useSDK(): ThirdwebSDK | undefined {
|
||||
|
||||
@@ -4,8 +4,23 @@ import type { Signer } from "ethers";
|
||||
import invariant from "tiny-invariant";
|
||||
|
||||
/**
|
||||
* Hook for getting the [ethers signer](https://docs.ethers.org/v5/api/signer/) of the connected wallet.
|
||||
*
|
||||
* @internal
|
||||
* @example
|
||||
*
|
||||
* ```jsx
|
||||
* import { useSigner, Web3Button } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const signer = useSigner();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns
|
||||
*
|
||||
* `Signer` if wallet is connected, otherwise `undefined`.
|
||||
*
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useSigner(): Signer | undefined {
|
||||
const context = useContext(ThirdwebConnectedWalletContext);
|
||||
|
||||
@@ -2,6 +2,12 @@ import { useContext } from "react";
|
||||
import invariant from "tiny-invariant";
|
||||
import { ThirdwebConfigContext } from "../contexts/thirdweb-config";
|
||||
|
||||
/**
|
||||
* Hook to get the `supportedChains` which returns the array passed to the `supportedChains` prop of the `ThirdwebProvider` or the default supported chains if not specified.
|
||||
*
|
||||
* If `activeChain` is set in the `ThirdwebProvider` then it is also added to the `supportedChains` array
|
||||
*
|
||||
*/
|
||||
export function useSupportedChains() {
|
||||
const context = useContext(ThirdwebConfigContext);
|
||||
invariant(
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useWalletContext } from "../../core/providers/thirdweb-wallet-provider";
|
||||
|
||||
/**
|
||||
* @deprecated use `useWallet` instead
|
||||
* @internal
|
||||
*/
|
||||
export function useSupportedWallet(id: string) {
|
||||
const context = useWalletContext();
|
||||
const wallet = context?.wallets.find((_wallet) => _wallet.id === id);
|
||||
|
||||
@@ -24,7 +24,18 @@ export type UseWatchTransactionsParams = Partial<
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @returns an array of {@link Transaction} objects
|
||||
* @param watchTransactionParams - Options for watching transactions
|
||||
*
|
||||
* #### address
|
||||
* The address to watch transactions for
|
||||
*
|
||||
* #### network
|
||||
* The network to watch transactions on
|
||||
*
|
||||
* #### sdkOptions
|
||||
* Options to pass to the thirdweb SDK
|
||||
*
|
||||
* @returns An array of `Transaction` objects
|
||||
*/
|
||||
export function useWatchTransactions(
|
||||
watchTransactionParams: UseWatchTransactionsParams,
|
||||
|
||||
@@ -6,19 +6,56 @@ import {
|
||||
import { ContractAddress } from "../types";
|
||||
import { cacheKeys } from "../utils/cache-keys";
|
||||
import { useSupportedChains } from "./useSupportedChains";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { UseQueryResult, useQuery } from "@tanstack/react-query";
|
||||
import { Chain, defaultChains } from "@thirdweb-dev/chains";
|
||||
import { useContext, useMemo } from "react";
|
||||
import { useSDK } from "./useSDK";
|
||||
import { useWalletContext } from "../../core/providers/thirdweb-wallet-provider";
|
||||
import { BigNumber } from "ethers";
|
||||
|
||||
/**
|
||||
* A hook to get the native or (optional) ERC20 token balance of the connected wallet.
|
||||
* Hook for getting a wallet's current balance of native or (optional) ERC20 token balance
|
||||
*
|
||||
* @param tokenAddress - the address of the token contract, if empty will use the chain's native token
|
||||
* @returns the balance of the connected wallet (native or ERC20)
|
||||
* @example
|
||||
*
|
||||
* ### get the balance of the native token
|
||||
*
|
||||
* ```jsx
|
||||
* import { useBalance } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { data, isLoading } = useBalance();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### get the balance of any other token
|
||||
*
|
||||
* ```jsx
|
||||
* import { useBalance } from "@thirdweb-dev/react";
|
||||
*
|
||||
* function App() {
|
||||
* const { data, isLoading } = useBalance(tokenAddress);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param tokenAddress - The address of the token contract, if not provided, it defaults to the native token
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property contains the token's balance in the `value` property as a `BigNumber` object.
|
||||
*
|
||||
* @token
|
||||
*/
|
||||
export function useBalance(tokenAddress?: ContractAddress) {
|
||||
export function useBalance(tokenAddress?: ContractAddress): UseQueryResult<
|
||||
| {
|
||||
symbol: string;
|
||||
value: BigNumber;
|
||||
name: string;
|
||||
decimals: number;
|
||||
displayValue: string;
|
||||
}
|
||||
| undefined,
|
||||
unknown
|
||||
> {
|
||||
const walletAddress = useAddress();
|
||||
|
||||
const { wallet, address, chainId } = useThirdwebConnectedWalletContext();
|
||||
@@ -42,12 +79,32 @@ export function useBalance(tokenAddress?: ContractAddress) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the native token balance of a wallet address on the `activeChain` network set in the `ThirdwebProvider`
|
||||
* This hook is similar to the `useBalance` hook, but it for fetching the native token balance of any given wallet address.
|
||||
*
|
||||
* @param walletAddress - the address of the wallet that you want to get the native balance
|
||||
* @returns the balance of the given wallet address
|
||||
* This hook only fetches the native token balance of the given wallet address. If you want to get the ERC20 balance from a given wallet, use `useTokenBalance`
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const { data, isLoading } = useBalanceForAddress(walletAddress)
|
||||
* ```
|
||||
*
|
||||
* @param walletAddress - The address of the wallet that you want to get the native balance
|
||||
*
|
||||
* @returns
|
||||
* The hook's `data` property contains the native token's balance in the `value` property as a `BigNumber` object.
|
||||
*
|
||||
* @token
|
||||
*/
|
||||
export function useBalanceForAddress(walletAddress: string) {
|
||||
export function useBalanceForAddress(walletAddress: string): UseQueryResult<
|
||||
{
|
||||
symbol: string;
|
||||
value: BigNumber;
|
||||
name: string;
|
||||
decimals: number;
|
||||
displayValue: string;
|
||||
},
|
||||
unknown
|
||||
> {
|
||||
invariant(walletAddress, "wallet address is not provided");
|
||||
const { activeChain } = useWalletContext();
|
||||
const chainId = activeChain.chainId;
|
||||
@@ -75,31 +132,22 @@ export function useConnectedWallet() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for accessing the address of the connected wallet
|
||||
*
|
||||
* ```javascript
|
||||
* import { useAddress } from "@thirdweb-dev/react"
|
||||
* ```
|
||||
* Get the address of the connected wallet.
|
||||
*
|
||||
* Returns `undefined` if no wallet is connected.
|
||||
*
|
||||
* @example
|
||||
* To get the address of the connected wallet, you can use the hook as follows:
|
||||
*
|
||||
* ```javascript
|
||||
* ```tsx
|
||||
* import { useAddress } from "@thirdweb-dev/react"
|
||||
*
|
||||
* const App = () => {
|
||||
* function Example() {
|
||||
* const address = useAddress()
|
||||
*
|
||||
* return <div>{address}</div>
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* The `address` variable will hold the address of the connected wallet if a user has connected using one of the supported wallet connection hooks.
|
||||
*
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useaddress?utm_source=sdk | Documentation}
|
||||
*
|
||||
* @public
|
||||
* @walletConnection
|
||||
*/
|
||||
export function useAddress(): string | undefined {
|
||||
const context = useContext(ThirdwebConnectedWalletContext);
|
||||
@@ -118,7 +166,6 @@ export function useAddress(): string | undefined {
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* You can get the chain ID of the connected wallet by using the hook as follows:
|
||||
* ```javascript
|
||||
* import { useChainId } from "@thirdweb-dev/react"
|
||||
*
|
||||
@@ -128,8 +175,13 @@ export function useAddress(): string | undefined {
|
||||
* return <div>{chainId}</div>
|
||||
* }
|
||||
* ```
|
||||
* @see {@link https://portal.thirdweb.com/react/react.usechainid?utm_source=sdk | Documentation}
|
||||
* @public
|
||||
*
|
||||
* @returns
|
||||
* A `number` representing the current chain id, or `undefined` if the user is not connected to a wallet.
|
||||
*
|
||||
* For Example, if the user is connected to the Ethereum Mainnet, the return value will be `1`.
|
||||
*
|
||||
* @networkConnection
|
||||
*/
|
||||
export function useChainId(): number | undefined {
|
||||
const context = useContext(ThirdwebConnectedWalletContext);
|
||||
@@ -141,25 +193,44 @@ export function useChainId(): number | undefined {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for accessing the active Chain the current wallet is connected to
|
||||
* Hook for getting the `Chain` object of the network that the user is connected - but only if
|
||||
* it's a supported network (added in the `ThirdwebProvider`'s `supportedChains` or one of default chains
|
||||
*
|
||||
* ```javascript
|
||||
* import { useChain } from "@thirdweb-dev/react-core"
|
||||
* Returns `undefined` if the network is not supported or the user is not connected to a wallet. You can use the `useConnectionStatus` hook to check if the user is connected to a wallet or not to differentiate between the two cases.
|
||||
*
|
||||
* If you only want to get the chain id of the network the user is connected to regardless of whether it's supported or not, use `useChainId` instead.
|
||||
*
|
||||
* ```jsx
|
||||
* import { useChain } from "@thirdweb-dev/react";
|
||||
*
|
||||
* const chain = useChain();
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* You can get the chain of the connected wallet by using the hook as follows:
|
||||
* ```javascript
|
||||
* import { useChain } from "@thirdweb-dev/react-core"
|
||||
*
|
||||
* const App = () => {
|
||||
* const chain = useChain()
|
||||
* ```jsx
|
||||
* import { useChain, useConnectionStatus } from "@thirdweb-dev/react";
|
||||
*
|
||||
* return <div>{chain.chainId}</div>
|
||||
* function App() {
|
||||
* const chain = useChain();
|
||||
* const status = useConnectionStatus();
|
||||
*
|
||||
* if (status === "unknown") return <div> Loading... </div>;
|
||||
* if (status === "disconnected") return <div> disconnected </div>;
|
||||
* if (status === "connecting") return <div> connecting... </div>;
|
||||
*
|
||||
* if (chain) {
|
||||
* return <p> Connected to {chain.name} </p>;
|
||||
* }
|
||||
*
|
||||
* return <p> Connected to an unsupported network </p>;
|
||||
* }
|
||||
* ```
|
||||
* @see {@link https://portal.thirdweb.com/react/react.useActiveChain?utm_source=sdk | Documentation}
|
||||
* @public
|
||||
*
|
||||
* @returns
|
||||
* An object of type `Chain` from [`@thirdweb-dev/chains`](https://www.npmjs.com/package/\@thirdweb-dev/chains) package containing various information about the network, or `undefined` if the network is not supported or user is not connected to a wallet.
|
||||
*
|
||||
* @networkConnection
|
||||
*/
|
||||
export function useChain(): Chain | undefined {
|
||||
const chainId = useChainId();
|
||||
@@ -180,6 +251,7 @@ export function useChain(): Chain | undefined {
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @deprecated
|
||||
*
|
||||
* This hook is renamed to `useChain`
|
||||
|
||||
@@ -9,6 +9,7 @@ export { __DEV__ } from "../core/constants/runtime";
|
||||
|
||||
// wallet hooks
|
||||
export {
|
||||
type WalletIdToWalletTypeMap,
|
||||
useWallet,
|
||||
useConnect,
|
||||
useConnectionStatus,
|
||||
@@ -24,6 +25,7 @@ export { useNetwork } from "../core/hooks/useNetwork";
|
||||
export { useWalletContext } from "../core/providers/thirdweb-wallet-provider";
|
||||
export { usePersonalWalletAddress } from "./hooks/usePersonalWalletAddress";
|
||||
export { useWalletConnectHandler } from "../core/providers/thirdweb-wallet-provider";
|
||||
export type { ConnectionStatus } from "../core/providers/thirdweb-wallet-provider";
|
||||
|
||||
// connected wallet hooks
|
||||
export {
|
||||
@@ -43,9 +45,7 @@ export type {
|
||||
WalletConfig,
|
||||
ConnectUIProps,
|
||||
SelectUIProps,
|
||||
WalletClass,
|
||||
WalletInstance,
|
||||
ExtraCoreWalletOptions,
|
||||
WalletOptions,
|
||||
} from "../core/types/wallet";
|
||||
|
||||
@@ -195,6 +195,7 @@ export {
|
||||
useTransferToken,
|
||||
useTransferBatchToken,
|
||||
useBurnToken,
|
||||
useTransferNativeToken,
|
||||
} from "./hooks/async/token";
|
||||
|
||||
// account factory
|
||||
|
||||
@@ -178,6 +178,98 @@ const WrappedThirdwebSDKProvider = <TChains extends Chain[]>({
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param props -
|
||||
* The props for the ThirdwebSDKProvider component
|
||||
*
|
||||
* ### clientId (optional)
|
||||
* The clientId prop is required to use the thirdweb infrastructure services with the SDK.
|
||||
*
|
||||
* ### activeChain (optional)
|
||||
* The activeChain prop determines which chain you want your app to be operating on.
|
||||
*
|
||||
* There are 1000+ chains available in the `@thirdweb-dev/chains` package. Import the chain you want and pass it to the `activeChain` prop.
|
||||
*
|
||||
* You can override the imported object or pass a custom chain object with required properties.
|
||||
*
|
||||
* You can get a client ID by creating an API key on [thirdweb dashboard](https://thirdweb.com/dashboard/settings/api-keys)
|
||||
*
|
||||
* ### supportedChains (optional)
|
||||
* An array of chains supported by your app.
|
||||
* There are 1000+ chains available in the `@thirdweb-dev/chains` package. You can import the chain you want and pass it to the `supportedChains` prop in an array.
|
||||
*
|
||||
* If not provided, it will default to the default supported chains supported by the thirdweb SDK.
|
||||
*
|
||||
* ```tsx
|
||||
* import { Ethereum, Polygon } from "@thirdweb-dev/chains";
|
||||
*
|
||||
* function Example() {
|
||||
* return (
|
||||
* <ThirdwebSDKProvider supportedChains={[ Ethereum, Polygon ]} activeChain={Ethereum}>
|
||||
* <App />
|
||||
* </ThirdwebSDKProvider>
|
||||
* )
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### signer (optional)
|
||||
* A signer is an abstraction of an Ethereum Account, which can be used to sign messages and initiate transactions.
|
||||
*
|
||||
* Since the ThirdwebSDKProvider is used when you want to provide your own wallet connection logic, you will need to provide a signer prop to inform the SDK of the wallet you want to use to sign transactions.
|
||||
*
|
||||
* Libraries such as ethers.js, web3.js, wagmi, etc. all provide ways to get a signer.
|
||||
*
|
||||
* To use this signer with the SDK, pass it to the `signer` prop. If the signer is connected, the SDK will use this wallet to sign transactions for all write operations on the blockchain.
|
||||
*
|
||||
* ### sdkOptions (optional)
|
||||
* The thirdweb SDK Options to pass to the thirdweb SDK which includes Gas settings, gasless transactions, RPC configuration, and more.
|
||||
*
|
||||
* This Overrides any of the default values for the SDK. If not provided, it uses sensible defaults.
|
||||
*
|
||||
* ### storageInterface (optional)
|
||||
* Override the default [Storage](https://portal.thirdweb.com/infrastructure/storage/overview) interface used by the SDK.
|
||||
*
|
||||
* It allows you to create an instance of `ThirdwebStorage` with your own customized config, and pass it to the SDK.
|
||||
*
|
||||
* *This requires the `@thirdweb-dev/storage` package to be installed.*
|
||||
*
|
||||
* ```tsx
|
||||
* import { ThirdwebSDKProvider } from "@thirdweb-dev/react";
|
||||
* import {
|
||||
* ThirdwebStorage,
|
||||
* StorageDownloader,
|
||||
* IpfsUploader,
|
||||
* } from "@thirdweb-dev/storage";
|
||||
*
|
||||
* // Configure a custom ThirdwebStorage instance
|
||||
* const gatewayUrls = {
|
||||
* "ipfs://": [
|
||||
* "https://gateway.ipfscdn.io/ipfs/",
|
||||
* "https://cloudflare-ipfs.com/ipfs/",
|
||||
* "https://ipfs.io/ipfs/",
|
||||
* ],
|
||||
* };
|
||||
* const downloader = new StorageDownloader();
|
||||
* const uploader = new IpfsUploader();
|
||||
* const storage = new ThirdwebStorage({ uploader, downloader, gatewayUrls });
|
||||
*
|
||||
* // Provide the custom storage instance to the SDK
|
||||
* function MyApp() {
|
||||
* return (
|
||||
* <ThirdwebSDKProvider
|
||||
* storageInterface={storage}
|
||||
* >
|
||||
* <YourApp />
|
||||
* </ThirdwebSDKProvider>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* ### authConfig (optional)
|
||||
* The configuration object for setting up [Auth](https://portal.thirdweb.com/wallets/auth); allowing users to sign in with their wallet.
|
||||
*
|
||||
* ### secretKey (optional)
|
||||
* secretKey for thirdweb services. This is only required if server side rendering is being used.
|
||||
*
|
||||
* @public
|
||||
*/
|
||||
export const ThirdwebSDKProvider = <TChains extends Chain[]>(
|
||||
|
||||
@@ -47,7 +47,7 @@ export interface ThirdwebSDKProviderProps<TChains extends Chain[]>
|
||||
sdkOptions?: Omit<SDKOptions, "chains">;
|
||||
|
||||
/**
|
||||
* Override the default [Storage](https://portal.thirdweb.com/storage) interface used by the SDK.
|
||||
* Override the default [Storage](https://portal.thirdweb.com/infrastructure/storage/overview) interface used by the SDK.
|
||||
*
|
||||
* It allows you to create an instance of `ThirdwebStorage` with your own customized config, and pass it to the SDK.
|
||||
*
|
||||
@@ -89,7 +89,7 @@ export interface ThirdwebSDKProviderProps<TChains extends Chain[]>
|
||||
storageInterface?: IThirdwebStorage;
|
||||
|
||||
/**
|
||||
* The configuration object for setting up [Auth](https://portal.thirdweb.com/auth); allowing users to sign in with their wallet.
|
||||
* The configuration object for setting up [Auth](https://portal.thirdweb.com/wallets/auth); allowing users to sign in with their wallet.
|
||||
*/
|
||||
authConfig?: ThirdwebAuthConfig;
|
||||
|
||||
|
||||
@@ -38,6 +38,9 @@ type AddEthereumChainParameter = {
|
||||
iconUrls?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export type Chain = {
|
||||
id: number;
|
||||
name: AddEthereumChainParameter["chainName"];
|
||||
@@ -52,6 +55,7 @@ export type Chain = {
|
||||
|
||||
/**
|
||||
* A wallet address.
|
||||
* @walletConnection
|
||||
*/
|
||||
export type WalletAddress = AddressOrEns;
|
||||
|
||||
@@ -62,7 +66,7 @@ export type ContractAddress = AddressOrEns;
|
||||
|
||||
/**
|
||||
* The parameters to pass to the mint and transfer functions.
|
||||
*
|
||||
* @token
|
||||
*/
|
||||
export type TokenParams = {
|
||||
to: WalletAddress;
|
||||
@@ -71,7 +75,7 @@ export type TokenParams = {
|
||||
|
||||
/**
|
||||
* The parameters to pass to the burn function.
|
||||
*
|
||||
* @token
|
||||
*/
|
||||
export type TokenBurnParams = {
|
||||
amount: Amount;
|
||||
@@ -81,10 +85,7 @@ export type TokenBurnParams = {
|
||||
|
||||
/**
|
||||
* The possible NFT contract types.
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* ```
|
||||
* @nft
|
||||
*/
|
||||
export type NFTContract =
|
||||
| NFTCollection
|
||||
@@ -95,20 +96,19 @@ export type NFTContract =
|
||||
|
||||
/**
|
||||
* The possible Token contract types.
|
||||
* @example
|
||||
* ```javascript
|
||||
* const { contract } = useContract("{{contract_address}}");
|
||||
* ```
|
||||
* @token
|
||||
*/
|
||||
export type TokenContract = TokenDrop | Token | SmartContract | null;
|
||||
|
||||
/**
|
||||
* Possible NFT contract types.
|
||||
* @internal
|
||||
*/
|
||||
export type Erc721OrErc1155 = Erc721 | Erc1155;
|
||||
|
||||
/**
|
||||
* The params to pass to `useTransferNFT`.
|
||||
* @nft
|
||||
*/
|
||||
export type TransferNFTParams = {
|
||||
to: WalletAddress;
|
||||
@@ -118,6 +118,7 @@ export type TransferNFTParams = {
|
||||
|
||||
/**
|
||||
* The params to pass to `useTransferBatchNFT`.
|
||||
* @nft
|
||||
*/
|
||||
export type AirdropNFTParams = {
|
||||
tokenId: BigNumberish;
|
||||
@@ -126,6 +127,7 @@ export type AirdropNFTParams = {
|
||||
|
||||
/**
|
||||
* The params to pass to `useMintNFTSupply`.
|
||||
* @nft
|
||||
*/
|
||||
export type MintNFTSupplyParams = {
|
||||
tokenId: BigNumberish;
|
||||
@@ -134,8 +136,8 @@ export type MintNFTSupplyParams = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The params for the {@link useMintNFT} hook mutation.
|
||||
*
|
||||
* The params for the `useMintNFT` hook mutation.
|
||||
* @nft
|
||||
*/
|
||||
export type MintNFTParams = {
|
||||
metadata: NFTMetadataOrUri;
|
||||
@@ -144,8 +146,8 @@ export type MintNFTParams = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The return type of the {@link useMintNFT} hook.
|
||||
*
|
||||
* The return type of the `useMintNFT` hook.
|
||||
* @nft
|
||||
*/
|
||||
export type MintNFTReturnType<TContract> = TContract extends Erc721
|
||||
? Awaited<ReturnType<Erc721["mintTo"]>>
|
||||
@@ -154,8 +156,9 @@ export type MintNFTReturnType<TContract> = TContract extends Erc721
|
||||
: never;
|
||||
|
||||
/**
|
||||
* The params for the {@link useBurnNFT} hook mutation.
|
||||
* The params for the `useBurnNFT` hook mutation.
|
||||
*
|
||||
* @nft
|
||||
*/
|
||||
export type BurnNFTParams = { tokenId: BigNumberish; amount?: Amount };
|
||||
|
||||
@@ -163,6 +166,7 @@ export type BurnNFTParams = { tokenId: BigNumberish; amount?: Amount };
|
||||
|
||||
/**
|
||||
* The possible DROP contract types.
|
||||
* @nftDrop
|
||||
*/
|
||||
export type DropContract =
|
||||
| NFTDrop
|
||||
@@ -174,22 +178,36 @@ export type DropContract =
|
||||
|
||||
/**
|
||||
* The possible revealable contract types.
|
||||
* @delayedReveal
|
||||
*/
|
||||
export type RevealableContract = NFTDrop | SignatureDrop | SmartContract | null;
|
||||
|
||||
/**
|
||||
* The params for the {@link useDelayedRevealLazyMint} hook mutation.
|
||||
*
|
||||
* @delayedReveal
|
||||
*/
|
||||
export type DelayedRevealLazyMintInput = {
|
||||
/**
|
||||
* The placeholder object represents the metadata the NFTs will have until the owner reveals the metadata.
|
||||
*/
|
||||
placeholder: NFTMetadataInput;
|
||||
/**
|
||||
* An array of metadata objects, representing the metadata of the NFTs to be lazy-minted.
|
||||
*
|
||||
* Each metadata object must conform to the [standard metadata properties](https://docs.opensea.io/docs/metadata-standards).
|
||||
*/
|
||||
metadatas: NFTMetadataInput[];
|
||||
/**
|
||||
* The password used to encrypt the metadatas.
|
||||
*
|
||||
* __The password CANNOT be recovered once it is set. If you lose the password, you will not be able to reveal the metadata.__
|
||||
*/
|
||||
password: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The params for the {@link useRevealLazyMint} hook mutation.
|
||||
*
|
||||
* @delayedReveal
|
||||
*/
|
||||
export type RevealLazyMintInput = {
|
||||
batchId: BigNumberish;
|
||||
@@ -197,8 +215,8 @@ export type RevealLazyMintInput = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The params for the {@link useClaimNFT} hook mutation.
|
||||
*
|
||||
* The params for the `useClaimNFT` hook mutation.
|
||||
* @nftDrop
|
||||
*/
|
||||
export type ClaimNFTParams = {
|
||||
to?: WalletAddress;
|
||||
@@ -211,8 +229,8 @@ export type ClaimNFTParams = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The return type of the {@link useClaimNFT} hook.
|
||||
*
|
||||
* The return type of the `useClaimNFT` hook.
|
||||
* @nftDrop
|
||||
*/
|
||||
export type ClaimNFTReturnType =
|
||||
| Awaited<ReturnType<Erc721["claimTo"]>>
|
||||
@@ -220,41 +238,101 @@ export type ClaimNFTReturnType =
|
||||
|
||||
// MARKETPLACE //
|
||||
|
||||
/**
|
||||
* @marketplace
|
||||
*/
|
||||
export type MakeBidParams = { listingId: BigNumberish; bid: Price };
|
||||
|
||||
/**
|
||||
* @marketplace
|
||||
*/
|
||||
export type MakeOfferParams = {
|
||||
listingId: BigNumberish;
|
||||
pricePerToken: Price;
|
||||
quantity?: Amount;
|
||||
};
|
||||
|
||||
/**
|
||||
* @marketplace
|
||||
*/
|
||||
export type AcceptDirectOffer = {
|
||||
/**
|
||||
* The `listingId` of the listing you wish to accept. Each listing has a unique `listingId` on the `Marketplace` contract.
|
||||
*/
|
||||
listingId: BigNumberish;
|
||||
/**
|
||||
* The wallet address of the user who made the offer you wish to accept.
|
||||
*
|
||||
* The `useContractEvents` hook can be used to read all `"NewOffer"` events on your `Marketplace` contract.
|
||||
*/
|
||||
addressOfOfferor: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* @marketplace
|
||||
*/
|
||||
export type ExecuteAuctionSale = {
|
||||
listingId: BigNumberish;
|
||||
};
|
||||
|
||||
/**
|
||||
* @marketplace
|
||||
*/
|
||||
export type BuyNowParams<TListingType = ListingType> =
|
||||
TListingType extends ListingType.Direct
|
||||
? {
|
||||
/**
|
||||
* The ID of the listing you want to buy.
|
||||
*/
|
||||
id: BigNumberish;
|
||||
/**
|
||||
* The type of listing. Either ListingType.Direct (0) or ListingType.Auction (1).
|
||||
*/
|
||||
type: ListingType.Direct;
|
||||
/**
|
||||
* The amount of tokens you want to buy from the listing.
|
||||
*
|
||||
* Applicable for ERC1155 listings only, should always be `1` for ERC721 listings.
|
||||
*/
|
||||
buyAmount: BigNumberish;
|
||||
/**
|
||||
* Optionally, specify a different wallet address to buy the listing for.
|
||||
*/
|
||||
buyForWallet?: WalletAddress;
|
||||
}
|
||||
: {
|
||||
/**
|
||||
* The ID of the listing you want to buy.
|
||||
*/
|
||||
id: BigNumberish;
|
||||
/**
|
||||
* The type of listing. Either ListingType.Direct (0) or ListingType.Auction (1).
|
||||
*/
|
||||
type: ListingType.Auction;
|
||||
};
|
||||
|
||||
export type BuyFromListingParams = {
|
||||
/**
|
||||
* The ID of the direct listing you want to buy.
|
||||
*/
|
||||
listingId: string;
|
||||
/**
|
||||
* The amount of tokens you want to buy from the listing.
|
||||
*
|
||||
* Applicable for ERC1155 listings only, should always be `1` for ERC721 listings.
|
||||
*/
|
||||
quantity: Amount;
|
||||
/**
|
||||
* Specify a different wallet address to buy the listing for.
|
||||
*/
|
||||
buyer: WalletAddress;
|
||||
};
|
||||
|
||||
// TOKEN DROP //
|
||||
|
||||
/**
|
||||
* @token
|
||||
*/
|
||||
export type ClaimTokenParams = {
|
||||
to: WalletAddress;
|
||||
amount: Amount;
|
||||
|
||||
@@ -23,6 +23,7 @@ export function shortenString(str: string, extraShort: boolean = true) {
|
||||
* ```ts
|
||||
* const address = shortenIfAddress("0x1234567890123456789012345678901234567890", true); // result will be "0x1234...890"
|
||||
* ```
|
||||
*
|
||||
*/
|
||||
export function shortenAddress(
|
||||
address?: string,
|
||||
|
||||
@@ -58,12 +58,22 @@ export function invalidateContractAndBalances(
|
||||
),
|
||||
),
|
||||
),
|
||||
queryClient.invalidateQueries(
|
||||
enforceCachePrefix(createCacheKeyWithNetwork(["balance"], chainId)),
|
||||
),
|
||||
invalidateBalances(queryClient, chainId),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export function invalidateBalances(
|
||||
queryClient: QueryClient,
|
||||
chainId: RequiredParam<SUPPORTED_CHAIN_ID>,
|
||||
) {
|
||||
return queryClient.invalidateQueries(
|
||||
enforceCachePrefix(createCacheKeyWithNetwork(["balance"], chainId)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@internal
|
||||
*/
|
||||
|
||||
@@ -5,9 +5,109 @@
|
||||
{
|
||||
"tagName": "@twfeature",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@marketplace",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@contract",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@claimConditions",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@nftDrop",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@platformFees",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@nft",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@metadata",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@permissionControl",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@networkConnection",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@delayedReveal",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@token",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@walletConnection",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@smartWallet",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@auth",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@storage",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@connectWallet",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@theme",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@locale",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@appURI",
|
||||
"syntaxKind": "block"
|
||||
},
|
||||
{
|
||||
"tagName": "@wallet",
|
||||
"syntaxKind": "block"
|
||||
}
|
||||
],
|
||||
"supportForTags": {
|
||||
"@twfeature": true
|
||||
"@twfeature": true,
|
||||
"@marketplace": true,
|
||||
"@contract": true,
|
||||
"@claimConditions": true,
|
||||
"@nftDrop": true,
|
||||
"@platformFees": true,
|
||||
"@nft": true,
|
||||
"@metadata": true,
|
||||
"@permissionControl": true,
|
||||
"@networkConnection": true,
|
||||
"@delayedReveal": true,
|
||||
"@token": true,
|
||||
"@walletConnection": true,
|
||||
"@smartWallet": true,
|
||||
"@auth": true,
|
||||
"@storage": true,
|
||||
"@connectWallet": true,
|
||||
"@theme": true,
|
||||
"@locale": true,
|
||||
"@appURI": true,
|
||||
"@wallet": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# @thirdweb-dev/react-native-compat
|
||||
|
||||
## 0.5.5
|
||||
|
||||
## 0.5.4
|
||||
|
||||
## 0.5.3
|
||||
|
||||
## 0.5.2
|
||||
|
||||
## 0.5.1
|
||||
|
||||
## 0.5.0
|
||||
|
||||
## 0.4.14
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/react-native-compat",
|
||||
"description": "Shims for Thirdweb in React Native Projects",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.5",
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native-compat",
|
||||
"license": "Apache-2.0",
|
||||
|
||||
@@ -1,5 +1,84 @@
|
||||
# @thirdweb-dev/react-native
|
||||
|
||||
## 0.5.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2119](https://github.com/thirdweb-dev/js/pull/2119) [`cf606665`](https://github.com/thirdweb-dev/js/commit/cf606665fcfdad7b08259350d39b60313278a8dc) Thanks [@MananTank](https://github.com/MananTank)! - Update Links to Docs website
|
||||
|
||||
- [#2092](https://github.com/thirdweb-dev/js/pull/2092) [`4c3c840d`](https://github.com/thirdweb-dev/js/commit/4c3c840d8815915840d0819932aa0a858c5d3184) Thanks [@iketw](https://github.com/iketw)! - Export WalletConnect modal component
|
||||
|
||||
- Updated dependencies [[`cf606665`](https://github.com/thirdweb-dev/js/commit/cf606665fcfdad7b08259350d39b60313278a8dc)]:
|
||||
- @thirdweb-dev/react-core@4.2.2
|
||||
- @thirdweb-dev/wallets@2.3.4
|
||||
- @thirdweb-dev/sdk@4.0.25
|
||||
|
||||
## 0.5.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies []:
|
||||
- @thirdweb-dev/react-core@4.2.1
|
||||
|
||||
## 0.5.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2101](https://github.com/thirdweb-dev/js/pull/2101) [`7fdb1715`](https://github.com/thirdweb-dev/js/commit/7fdb1715e4263e9b9c90370a1e70c7fa1fa0e95e) Thanks [@iketw](https://github.com/iketw)! - Export types for better reference docs
|
||||
|
||||
- [#2108](https://github.com/thirdweb-dev/js/pull/2108) [`b90fa2cc`](https://github.com/thirdweb-dev/js/commit/b90fa2cc298bf1a6deb0f4c0f927ab77f2716448) Thanks [@iketw](https://github.com/iketw)! - Adds `hideSendButton` and `hideReceiveButton` to the ConnectWallet component.
|
||||
|
||||
Both props default to `false`.
|
||||
|
||||
```js
|
||||
<ConnectWallet hideReceiveButton={true} hideSendButton={true} />
|
||||
```
|
||||
|
||||
- Updated dependencies [[`b808e942`](https://github.com/thirdweb-dev/js/commit/b808e942fdaa81b5de61dcb3f2083081cb99ea11), [`e46dd025`](https://github.com/thirdweb-dev/js/commit/e46dd0254f157c3c4d50fe3e4f44e2e24eaf34a8)]:
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
|
||||
## 0.5.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2084](https://github.com/thirdweb-dev/js/pull/2084) [`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c) Thanks [@MananTank](https://github.com/MananTank)! - JSDoc comments Improvements
|
||||
|
||||
- [#2087](https://github.com/thirdweb-dev/js/pull/2087) [`b7d4dee4`](https://github.com/thirdweb-dev/js/commit/b7d4dee4460185f7706c3f97b67b385bb279b6e2) Thanks [@iketw](https://github.com/iketw)! - Support expo versions =>47 < 50
|
||||
|
||||
- [#2099](https://github.com/thirdweb-dev/js/pull/2099) [`94a8f796`](https://github.com/thirdweb-dev/js/commit/94a8f7960a71f24f1eb5c7cebfb548578642e281) Thanks [@iketw](https://github.com/iketw)! - Updates CoinbaseWallet SDK to fix scheme redirection bug
|
||||
|
||||
- Updated dependencies [[`c410a1c1`](https://github.com/thirdweb-dev/js/commit/c410a1c18a704d118555215db9ba7d92c3b24d8c), [`fed1313a`](https://github.com/thirdweb-dev/js/commit/fed1313a199011a9b52d7c5e11ad6e72fc969002), [`f369bffe`](https://github.com/thirdweb-dev/js/commit/f369bffe5a30e2e8a9df2ac62f24f93f96324186), [`81c46e22`](https://github.com/thirdweb-dev/js/commit/81c46e22984cdb5b33b2e6eb99a0ebf0e4fbdb33), [`23db97cc`](https://github.com/thirdweb-dev/js/commit/23db97cca51211df82d430fbfff4bbfbd7d4dc38)]:
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
|
||||
## 0.5.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#2074](https://github.com/thirdweb-dev/js/pull/2074) [`07fbb799`](https://github.com/thirdweb-dev/js/commit/07fbb799be87c1c5229ae3183fa8bc67ae15c756) Thanks [@iketw](https://github.com/iketw)! - Adds the ability to login with any arbitrary login payload
|
||||
|
||||
```typescript
|
||||
await embeddedWallet.authenticate({
|
||||
strategy: "auth_endpoint",
|
||||
payload: "SOME_STRING",
|
||||
encryptionKey: "",
|
||||
});
|
||||
```
|
||||
|
||||
- [#2082](https://github.com/thirdweb-dev/js/pull/2082) [`699f31c2`](https://github.com/thirdweb-dev/js/commit/699f31c20a76cd284dbed1629c4a19d93aca7b7f) Thanks [@iketw](https://github.com/iketw)! - Better comments
|
||||
|
||||
- [#2086](https://github.com/thirdweb-dev/js/pull/2086) [`328ef5dc`](https://github.com/thirdweb-dev/js/commit/328ef5dc9c628a89a022a559852dfa2a788f70cb) Thanks [@iketw](https://github.com/iketw)! - Hide WC modal back button when only WC is defined as a supportedWallet
|
||||
|
||||
- Updated dependencies [[`c701c388`](https://github.com/thirdweb-dev/js/commit/c701c388c65a1e531b88991d8fd67d25f153992e), [`699f31c2`](https://github.com/thirdweb-dev/js/commit/699f31c20a76cd284dbed1629c4a19d93aca7b7f)]:
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
- @thirdweb-dev/[email protected]
|
||||
|
||||
## 0.5.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@thirdweb-dev/react-native",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.5",
|
||||
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native",
|
||||
"author": "thirdweb eng <[email protected]>",
|
||||
"license": "Apache-2.0",
|
||||
@@ -27,7 +27,7 @@
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-lambda": "3.350.0",
|
||||
"@aws-sdk/credential-providers": "3.350.0",
|
||||
"@coinbase/wallet-mobile-sdk": "1.0.7",
|
||||
"@coinbase/wallet-mobile-sdk": "1.0.10",
|
||||
"@magic-sdk/provider": "17.2.0",
|
||||
"@magic-sdk/react-native-bare": "^18.5.0",
|
||||
"@paperxyz/embedded-wallet-service-sdk": "^1.2.4",
|
||||
@@ -72,7 +72,6 @@
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"eslint-plugin-tsdoc": "^0.2.16",
|
||||
"ethers": "^5.7.2",
|
||||
"expo": "^47.0.14",
|
||||
"jest": "^29.6.2",
|
||||
"prettier": "^3.0.0",
|
||||
"react": "^18.2.0",
|
||||
@@ -99,7 +98,7 @@
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ethers": ">=5.5.1 <6",
|
||||
"expo": "^47.0.0",
|
||||
"expo": ">=47 <50",
|
||||
"react": ">=18.0.0",
|
||||
"react-native": ">=0.70.0"
|
||||
},
|
||||
|
||||
@@ -118,7 +118,7 @@ export class ThirdwebStorage<T extends UploadOptions = IpfsUploadBatchOptions>
|
||||
*
|
||||
* @param data - Arbitrary file or JSON data to upload
|
||||
* @param options - Options to pass through to the storage uploader class
|
||||
* @returns - The URI of the uploaded data
|
||||
* @returns The URI of the uploaded data
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
@@ -150,7 +150,7 @@ export class ThirdwebStorage<T extends UploadOptions = IpfsUploadBatchOptions>
|
||||
*
|
||||
* @param data - Array of arbitrary file or JSON data to upload
|
||||
* @param options - Options to pass through to the storage uploader class
|
||||
* @returns - The URIs of the uploaded data
|
||||
* @returns The URIs of the uploaded data
|
||||
*
|
||||
* @example
|
||||
* ```jsx
|
||||
|
||||
@@ -24,15 +24,29 @@ import { SupportedTokens, defaultTokens } from "./SendFunds/defaultTokens";
|
||||
|
||||
export type ConnectWalletProps = {
|
||||
/**
|
||||
* render a custom button to display the connected wallet details instead of the default button
|
||||
* Renders a custom button to display the connected wallet details instead of the default button
|
||||
*/
|
||||
detailsButton?: ConnectWalletDetailsProps["detailsButton"];
|
||||
|
||||
/**
|
||||
* render custom rows in the Connect Wallet Details modal
|
||||
* Renders custom rows in the Connect Wallet Details modal
|
||||
*/
|
||||
extraRows?: ConnectWalletDetailsProps["extraRows"];
|
||||
|
||||
/**
|
||||
* Option to hide the Send button in the wallet details modal.
|
||||
*
|
||||
* The default is `false`
|
||||
*/
|
||||
hideSendButton?: boolean;
|
||||
|
||||
/**
|
||||
* Option to hide the Receive button in the wallet details modal.
|
||||
*
|
||||
* The default is `false`
|
||||
*/
|
||||
hideReceiveButton?: boolean;
|
||||
|
||||
/**
|
||||
* Hide option to request testnet funds for testnets in dropdown
|
||||
*
|
||||
@@ -42,7 +56,7 @@ export type ConnectWalletProps = {
|
||||
|
||||
/**
|
||||
* Whether to show "Switch Network" button if the wallet is connected,
|
||||
* but it is not connected to the `activeChain` provided in `ThirdwebProvider`
|
||||
* but it is not connected to the `activeChain` provided in [`ThirdwebProvider`](https://portal.thirdweb.com/react-native/v0/ThirdwebProvider)
|
||||
*
|
||||
* Please, note that if you support multiple networks in your app this prop should
|
||||
* be set to `false` to allow users to switch between networks.
|
||||
@@ -84,6 +98,8 @@ export const ConnectWallet = ({
|
||||
buttonTitle,
|
||||
modalTitle,
|
||||
modalTitleIconUrl,
|
||||
hideReceiveButton,
|
||||
hideSendButton,
|
||||
extraRows,
|
||||
hideTestnetFaucet,
|
||||
displayBalanceToken,
|
||||
@@ -169,6 +185,8 @@ export const ConnectWallet = ({
|
||||
detailsButton={detailsButton}
|
||||
extraRows={extraRows}
|
||||
hideTestnetFaucet={hideTestnetFaucet}
|
||||
hideReceiveButton={hideReceiveButton}
|
||||
hideSendButton={hideSendButton}
|
||||
supportedTokens={supportedTokensMemo}
|
||||
displayBalanceToken={displayBalanceToken}
|
||||
hideSwitchToPersonalWallet={hideSwitchToPersonalWallet}
|
||||
|
||||
+27
-9
@@ -45,6 +45,8 @@ export const ConnectWalletDetailsModal = ({
|
||||
supportedTokens,
|
||||
displayBalanceToken,
|
||||
hideSwitchToPersonalWallet,
|
||||
hideReceiveButton,
|
||||
hideSendButton,
|
||||
}: {
|
||||
isVisible: boolean;
|
||||
onClosePress: () => void;
|
||||
@@ -54,6 +56,8 @@ export const ConnectWalletDetailsModal = ({
|
||||
supportedTokens: SupportedTokens;
|
||||
displayBalanceToken?: Record<number, string>;
|
||||
hideSwitchToPersonalWallet?: boolean;
|
||||
hideReceiveButton?: boolean;
|
||||
hideSendButton?: boolean;
|
||||
}) => {
|
||||
const l = useLocale();
|
||||
const [isExportModalVisible, setIsExportModalVisible] = useState(false);
|
||||
@@ -143,7 +147,7 @@ export const ConnectWalletDetailsModal = ({
|
||||
if (activeWallet?.walletId === walletIds.localWallet) {
|
||||
return (
|
||||
<>
|
||||
<View style={styles.currentNetwork}>
|
||||
<View style={styles.additionalActions}>
|
||||
<Text variant="bodySmallSecondary">
|
||||
{l.connect_wallet_details.additional_actions}
|
||||
</Text>
|
||||
@@ -267,14 +271,19 @@ export const ConnectWalletDetailsModal = ({
|
||||
</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
<Box
|
||||
flexDirection="row"
|
||||
justifyContent="space-evenly"
|
||||
marginVertical="md"
|
||||
>
|
||||
<SendButton supportedTokens={supportedTokens} />
|
||||
<ReceiveButton />
|
||||
</Box>
|
||||
{hideReceiveButton && hideSendButton ? null : (
|
||||
<Box
|
||||
flexDirection="row"
|
||||
justifyContent="space-evenly"
|
||||
gap="xs"
|
||||
marginTop="md"
|
||||
>
|
||||
{hideSendButton ? null : (
|
||||
<SendButton supportedTokens={supportedTokens} />
|
||||
)}
|
||||
{hideReceiveButton ? null : <ReceiveButton />}
|
||||
</Box>
|
||||
)}
|
||||
<View style={styles.currentNetwork}>
|
||||
<Text variant="bodySmallSecondary">
|
||||
{l.connect_wallet_details.current_network}
|
||||
@@ -353,6 +362,15 @@ const styles = StyleSheet.create({
|
||||
minWidth: 200,
|
||||
},
|
||||
currentNetwork: {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignContent: "flex-start",
|
||||
alignItems: "flex-start",
|
||||
justifyContent: "flex-start",
|
||||
marginBottom: 8,
|
||||
marginTop: 28,
|
||||
},
|
||||
additionalActions: {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignContent: "flex-start",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user