Compare commits

..
Author SHA1 Message Date
github-actions[bot]andgithub-actions[bot] c5959fbd52 Version Packages (#689)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-03-07 22:37:23 -08:00
Adam Majmudar 68d52f99b3 [SDK] Poll if transaction isn't found yet (#688) 2023-03-08 06:17:23 +00:00
9efeba38f0 [Auth] Include credentials on initial login request, [react] web3button type (#684)
Co-authored-by: Manan Tank <[email protected]>
Co-authored-by: Jonas Daniels <[email protected]>
2023-03-08 06:10:39 +00:00
github-actions[bot]andgithub-actions[bot] 50346bd9d0 Version Packages (#622)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-03-07 18:03:15 -08:00
Jonas Daniels f9cf2bc6ba [chains] - fix windows build? (#686) 2023-03-07 20:11:52 +00:00
Jonas Daniels 4355518afe [chains] - update chains (#685) 2023-03-07 18:57:43 +00:00
Jonas Daniels 99521129ed quicker timeouts (#682) 2023-03-06 17:49:44 -08:00
nkrishangandJonas Daniels c9067681c2 Add CLI command to deploy dynamic smart contracts (#678)
Co-authored-by: Jonas Daniels <[email protected]>
2023-03-07 00:22:30 +00:00
Jonas DanielsandJoaquim Verges 2335f000c9 [SDK] - NFT supply is now string instead of number (#679)
Co-authored-by: Joaquim Verges <[email protected]>
2023-03-05 04:46:00 +00:00
Adam Majmudar a7e908b5fe [SDK] Add transaction pattern to registry (#676) 2023-03-03 22:18:35 +00:00
Adam Majmudar 2a8cc289ac [SDK] Add transaction builder to publisher and registry (#675) 2023-03-03 21:44:45 +00:00
Adam Majmudar d8dec9fc19 [SDK] Fix configuring SDK with custom chains (#674) 2023-03-03 08:23:55 +00:00
Adam Majmudar 0c88304464 [SDK] Don't use functions in sdk.getContract (#673) 2023-03-03 07:25:22 +00:00
Jonas Daniels 2676fc01f4 fix react core (#672) 2023-03-03 07:14:50 +00:00
Furqan Rydhan 61ef69649f app URI fixes (#671) 2023-03-03 07:07:32 +00:00
Furqan Rydhan 460576fea9 Merge branch 'main' of github.com:thirdweb-dev/js 2023-03-03 06:47:37 +00:00
Furqan Rydhan 87a8ebdb7a fix things 2023-03-03 06:47:01 +00:00
Furqan Rydhan e23ee0526e fix type for prebuilt contracts and app uri 2023-03-03 06:13:09 +00:00
be04ff2775 CLI improvements (#666)
Co-authored-by: Adam Majmudar <[email protected]>
Co-authored-by: adam-maj <[email protected]>
Co-authored-by: Jonas Daniels <[email protected]>
2023-03-03 06:11:48 +00:00
3740a0bf5d app uri (#662)
Co-authored-by: Nacho Iacovino <[email protected]>
Co-authored-by: Nacho Iacovino <[email protected]>
2023-03-03 05:40:00 +00:00
Jonas Daniels 6ae39277a1 [react-core] fix signer more (#670) 2023-03-03 05:39:18 +00:00
Jonas Daniels 8f46a2eef5 update signer correctly (#668) 2023-03-02 20:04:56 +00:00
Furqan Rydhan 8ac9b03f4a fix code tab for contract metadata 2023-03-02 06:24:17 +00:00
sidandJonas Daniels 6ef52dc916 Fix spelling (#665)
Co-authored-by: Jonas Daniels <[email protected]>
2023-03-02 03:04:05 +00:00
Adam Majmudar b6b0855b81 [SDK] Allow setting extra overrides (#667) 2023-03-02 02:20:45 +00:00
Jonas Daniels ac01516ce6 fix it 2023-03-01 17:36:09 -08:00
Jonas Daniels 1aef3bd270 changesets action 2023-03-01 17:29:45 -08:00
Jonas Daniels e9b5031565 more things 2023-03-01 17:23:40 -08:00
Adam Majmudar e081075b2c [SDK] Expose get and set functions on transaction and tx.sign() (#663) 2023-03-02 00:28:40 +00:00
Jonas Daniels 3212867de2 just always do it 2023-03-01 16:18:02 -08:00
Jonas Daniels 91e7178295 hasChangesets true value not string 2023-03-01 16:08:28 -08:00
Jonas Daniels 3985560942 changeset and workflow changes (#664) 2023-03-01 23:32:43 +00:00
Manan TankandJonas Daniels 87a101ad56 Fix Wrong Currency symbol in non-default chains (#660)
Co-authored-by: Jonas Daniels <[email protected]>
2023-03-01 21:37:51 +00:00
nkrishang 842ed519a3 CLI command to create extensions for dynamic contracts (#641) 2023-03-01 19:04:30 +00:00
Adam Majmudar 2f4cd92848 [SDK] Add prepare method to all contracts (#661) 2023-03-01 18:49:55 +00:00
iketw 303bf63c1a [ReactCoreSDK] pass default key to the sdkprovider (#658) 2023-03-01 17:44:56 +00:00
Adam Majmudar 8845bf960e [SDK] await getGasOverrides (#659) 2023-03-01 08:12:48 +00:00
Jake Loo b80024c6cc ERC20Permit detect (#655) 2023-03-01 03:39:12 +00:00
Jonas Daniels 696c384a34 Jd/fix build app uri (#654) 2023-03-01 01:53:26 +00:00
Jonas Daniels bd6be0bae7 [SDK] - add extensions getter (#653) 2023-03-01 01:09:57 +00:00
Nacho Iacovino 8d5b418e78 [React] Fix appURI hook invariant (#650) 2023-03-01 00:51:59 +00:00
Adam Majmudar 1bdb44d36b [React] Fix onError in Web3Button to work with errors on promise (#651) 2023-03-01 00:51:35 +00:00
Nacho Iacovino b83ea5251b [SDK] Detect appURI (#631) 2023-03-01 00:50:03 +00:00
Adam Majmudar 537785fed0 [SDK] Add getContract and getContractFromAbi functions (#628) 2023-03-01 00:40:13 +00:00
Adam Majmudar fb346ffd45 [Storage] Send progress event if files have already been uploaded (#648) 2023-02-28 23:54:29 +00:00
Adam Majmudar 63f552d736 Allow passing gatewayUrls as array and directly (#644) 2023-02-28 23:27:14 +00:00
Adam Majmudar cc7ce8b1e8 Allow CID prediction for file type on client (#646) 2023-02-28 23:19:30 +00:00
Jonas Daniels 85250cf711 [multi] - various fixes (#643) 2023-02-28 22:50:22 +00:00
Adam Majmudar 29c1cf7eff Make checking for CID non-blocking on error (#645) 2023-02-28 22:16:58 +00:00
Adam Majmudar 0666f37c13 [SDK] Cleanup signer and provider logic & add exhaustive test cases (#623) 2023-02-28 09:14:14 +00:00
Adam Majmudar 8a8a37f6d3 [Storage] Pre-compute IPFS hashes before uploading (#637) 2023-02-28 08:08:15 +00:00
Furqan Rydhan dc08aa731f contract metadata compatibility (#642) 2023-02-28 03:59:31 +00:00
Adam Majmudar 541dfeeaba Fix top-level transaction functions (#640) 2023-02-28 02:27:13 +00:00
Adam MajmudarandJonas Daniels 1e1a39123b [SDK] Add new transaction pattern (#566)
Co-authored-by: Jonas Daniels <[email protected]>
2023-02-27 23:22:21 +00:00
Jonas Daniels 5c7ae694c4 add test for chains (#639) 2023-02-27 22:30:36 +00:00
Jonas Daniels e33bd2a856 add getChainByChainId function (#638) 2023-02-27 19:18:04 +00:00
Nacho Iacovino b1ee7491c8 [React] Export appURI hooks (#636) 2023-02-27 01:01:05 +00:00
Jonas Daniels 7832041c0f add chains (#635) 2023-02-27 00:47:10 +00:00
Joaquim Verges 88c78f3b32 [SDK] export marketplace and appUri classes (#634) 2023-02-26 23:16:43 +00:00
Nacho Iacovino 78536ba65f [Multi] More docs small changes (#633) 2023-02-26 07:26:22 +00:00
Nacho Iacovino b0e8406d1e [Multi] Document marketplace v3 with examples (#632) 2023-02-26 04:00:43 +00:00
Nacho Iacovino 9c5dbf1fe6 [Multi] AppURI now works with ContractMetadata feature (#630) 2023-02-25 23:13:09 +00:00
Nacho Iacovino ba90c675db [Multi] More docs updates (#629) 2023-02-25 22:51:46 +00:00
Joaquim Verges fd9ba94db2 Fix feature snippets SDK script (#627) 2023-02-25 17:10:32 +00:00
Nacho Iacovino 91f5a2fd5c Fix documentation for react docs (#626) 2023-02-25 16:30:23 +00:00
Joaquim Verges e50911bc06 [Wallet] Email wallet improvements (#612) 2023-02-25 04:02:59 +00:00
Nacho Iacovino 23cd88ec3a [React] Add AppURI get/set hooks (#625) 2023-02-25 01:52:20 +00:00
Joaquim Verges 1adaf41e41 [SDK] Extension code comments (#624) 2023-02-25 01:16:02 +00:00
Yash 478780f634 [SDK] Feature for extension router (#621) 2023-02-24 03:59:16 +00:00
255 changed files with 8784 additions and 4708 deletions
+1 -1
View File
@@ -16,6 +16,6 @@
}, },
"snapshot": { "snapshot": {
"useCalculatedVersion": true, "useCalculatedVersion": true,
"prereleaseTemplate": "{tag}-{commit}" "prereleaseTemplate": "{tag}-{datetime}-{commit}"
} }
} }
+1 -1
View File
@@ -23,7 +23,7 @@ We use [Turborepo](https://turborepo.org/docs/getting-started) to manage the mon
You can see a quick outline of each of the projects within this repo below, each living within the [/packages](/packages) directory: You can see a quick outline of each of the projects within this repo below, each living within the [/packages](/packages) directory:
| Package | Description | Latest Version | | Package | Description | Latest Version |
| ------------------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |--------------------------------|----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [/sdk](./packages/sdk) | Best in class web3 SDK for Browser, Node and Mobile apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/sdk"><img src="https://img.shields.io/npm/v/@thirdweb-dev/sdk?color=red&label=npm&logo=npm" alt="npm version"/></a> | | [/sdk](./packages/sdk) | Best in class web3 SDK for Browser, Node and Mobile apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/sdk"><img src="https://img.shields.io/npm/v/@thirdweb-dev/sdk?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/react](./packages/react) | Ultimate collection of React hooks for your web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react?color=red&label=npm&logo=npm" alt="npm version"/></a> | | [/react](./packages/react) | Ultimate collection of React hooks for your web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?color=red&label=npm&logo=npm" alt="npm version"/></a> | | [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?color=red&label=npm&logo=npm" alt="npm version"/></a> |
+4
View File
@@ -20,6 +20,7 @@ env:
jobs: jobs:
build: build:
timeout-minutes: 15
name: Build name: Build
runs-on: ubuntu-latest-16 runs-on: ubuntu-latest-16
@@ -46,6 +47,7 @@ jobs:
key: ${{ github.sha }}-${{ github.run_number }} key: ${{ github.sha }}-${{ github.run_number }}
lint: lint:
timeout-minutes: 15
name: Lint Packages name: Lint Packages
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: build needs: build
@@ -66,6 +68,7 @@ jobs:
- run: yarn lint - run: yarn lint
test: test:
timeout-minutes: 15
name: Unit Tests name: Unit Tests
runs-on: ubuntu-latest-16 runs-on: ubuntu-latest-16
needs: build needs: build
@@ -91,6 +94,7 @@ jobs:
files: ./packages/sdk/coverage/evm/lcov.info,./packages/sdk/coverage/solana/lcov.info, files: ./packages/sdk/coverage/evm/lcov.info,./packages/sdk/coverage/solana/lcov.info,
e2e: e2e:
timeout-minutes: 15
name: E2E Tests name: E2E Tests
runs-on: ubuntu-latest-16 runs-on: ubuntu-latest-16
needs: build needs: build
+2
View File
@@ -76,8 +76,10 @@ jobs:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Deploy pre-release - name: Deploy pre-release
id: changesets
run: | run: |
yarn changeset version --snapshot dev yarn changeset version --snapshot dev
node ./scripts/pre-release.mjs
yarn changeset publish --tag dev --no-git-tag yarn changeset publish --tag dev --no-git-tag
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-1
View File
@@ -10,7 +10,6 @@ dist-ssr
.cache .cache
server/dist server/dist
public/dist public/dist
.turbo
./packages/contracts-js/abis ./packages/contracts-js/abis
.idea/ .idea/
.yalc/ .yalc/
+2 -2
View File
@@ -5,7 +5,7 @@
<br /> <br />
</p> </p>
<h1 align="center"><a href='http://thirdweb.com/'>thirdweb</a> JavaScript/TypeScript monorepo</h1> <h1 align="center"><a href='https://thirdweb.com/'>thirdweb</a> JavaScript/TypeScript monorepo</h1>
<p align="center"> <p align="center">
<a href="https://github.com/thirdweb-dev/js/actions/workflows/build-test-lint.yml"> <a href="https://github.com/thirdweb-dev/js/actions/workflows/build-test-lint.yml">
@@ -21,7 +21,7 @@
## Packages ## Packages
| Package | Description | Latest Version | | Package | Description | Latest Version |
| ------------------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |--------------------------------|----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [/sdk](./packages/sdk) | Best in class web3 SDK for Browser, Node and Mobile apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/sdk"><img src="https://img.shields.io/npm/v/@thirdweb-dev/sdk?color=red&label=npm&logo=npm" alt="npm version"/></a> | | [/sdk](./packages/sdk) | Best in class web3 SDK for Browser, Node and Mobile apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/sdk"><img src="https://img.shields.io/npm/v/@thirdweb-dev/sdk?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/react](./packages/react) | Ultimate collection of React hooks for your web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react?color=red&label=npm&logo=npm" alt="npm version"/></a> | | [/react](./packages/react) | Ultimate collection of React hooks for your web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?color=red&label=npm&logo=npm" alt="npm version"/></a> | | [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?color=red&label=npm&logo=npm" alt="npm version"/></a> |
+2 -2
View File
@@ -41,10 +41,10 @@
"mocha": "^10.2.0", "mocha": "^10.2.0",
"postinstall-postinstall": "^2.1.0", "postinstall-postinstall": "^2.1.0",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"turbo": "^1.8.2", "turbo": "^1.8.3",
"yalc": "^1.0.0-pre.53" "yalc": "^1.0.0-pre.53"
}, },
"manypkg": { "manypkg": {
"defaultBranch": "main" "defaultBranch": "main"
} }
} }
+6
View File
@@ -1,5 +1,11 @@
# @thirdweb-dev/auth # @thirdweb-dev/auth
## 3.0.7
### Patch Changes
- [#665](https://github.com/thirdweb-dev/js/pull/665) [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75) Thanks [@shift4id](https://github.com/shift4id)! - Fix spelling throughout all packages
## 3.0.6 ## 3.0.6
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/auth", "name": "@thirdweb-dev/auth",
"version": "3.0.6", "version": "3.0.7",
"main": "dist/thirdweb-dev-auth.cjs.js", "main": "dist/thirdweb-dev-auth.cjs.js",
"module": "dist/thirdweb-dev-auth.esm.js", "module": "dist/thirdweb-dev-auth.esm.js",
"exports": { "exports": {
+5 -39
View File
@@ -468,6 +468,7 @@ const polygonMumbai: Chain = {
/** /**
* @public * @public
* @deprecated - use the chainId number directly instead
*/ */
export enum ChainId { export enum ChainId {
Mainnet = 1, Mainnet = 1,
@@ -488,6 +489,7 @@ export enum ChainId {
/** /**
* @public * @public
* @deprecated - thirdweb now supports all evm chains, for a list of chain install the @thirdweb-dev/chains package
*/ */
export type SUPPORTED_CHAIN_ID = export type SUPPORTED_CHAIN_ID =
| ChainId.Mainnet | ChainId.Mainnet
@@ -507,6 +509,7 @@ export type SUPPORTED_CHAIN_ID =
/** /**
* @public * @public
* @deprecated - thirdweb now supports all evm chains, for a list of chain install the @thirdweb-dev/chains package
*/ */
export const SUPPORTED_CHAIN_IDS: SUPPORTED_CHAIN_ID[] = [ export const SUPPORTED_CHAIN_IDS: SUPPORTED_CHAIN_ID[] = [
ChainId.Mainnet, ChainId.Mainnet,
@@ -534,45 +537,8 @@ export const NATIVE_TOKEN_ADDRESS =
export const DEFAULT_API_KEY = export const DEFAULT_API_KEY =
"c6634ad2d97b74baf15ff556016830c251050e6c36b9da508ce3ec80095d3dc1"; "c6634ad2d97b74baf15ff556016830c251050e6c36b9da508ce3ec80095d3dc1";
function getRpcNameFromChainId(chainId: SUPPORTED_CHAIN_ID): string { export function getRpcUrl(chainId: number) {
switch (chainId) { return `https://${chainId}.rpc.thirdweb.com/${DEFAULT_API_KEY}`;
case ChainId.Mainnet:
return "mainnet";
case ChainId.Goerli:
return "goerli";
case ChainId.Polygon:
return "polygon";
case ChainId.Mumbai:
return "mumbai";
case ChainId.Avalanche:
return "avalanche";
case ChainId.AvalancheFujiTestnet:
return "avalanche-fuji";
case ChainId.Fantom:
return "fantom";
case ChainId.FantomTestnet:
return "fantom-testnet";
case ChainId.Arbitrum:
return "arbitrum";
case ChainId.ArbitrumGoerli:
return "arbitrum-goerli";
case ChainId.Optimism:
return "optimism";
case ChainId.OptimismGoerli:
return "optimism-goerli";
case ChainId.BinanceSmartChainMainnet:
return "bsc";
case ChainId.BinanceSmartChainTestnet:
return "bsc-testnet";
default:
throw new Error("Unsupported chain id");
}
}
export function getRpcUrl(chainId: SUPPORTED_CHAIN_ID) {
return `https://${getRpcNameFromChainId(
chainId,
)}.rpc.thirdweb.com/${DEFAULT_API_KEY}`;
} }
function enhanceChain<TChain extends Chain>(chain: TChain) { function enhanceChain<TChain extends Chain>(chain: TChain) {
+1 -1
View File
@@ -31,5 +31,5 @@ export default async function handler(
}), }),
); );
return res.status(200).json({ message: "Succesfully logged out" }); return res.status(200).json({ message: "Successfully logged out" });
} }
+1 -1
View File
@@ -31,5 +31,5 @@ export default async function handler(
}), }),
); );
return res.status(200).json({ message: "Succesfully logged out" }); return res.status(200).json({ message: "Successfully logged out" });
} }
+12
View File
@@ -1,5 +1,17 @@
# @thirdweb-dev/chains # @thirdweb-dev/chains
## 0.1.6
### Patch Changes
- [#635](https://github.com/thirdweb-dev/js/pull/635) [`7832041c`](https://github.com/thirdweb-dev/js/commit/7832041c0fb25852489c73453c2b26e844d94582) Thanks [@jnsdls](https://github.com/jnsdls)! - Add additional chains
- [#643](https://github.com/thirdweb-dev/js/pull/643) [`85250cf7`](https://github.com/thirdweb-dev/js/commit/85250cf71190092b61023d56d1e786d395a008a6) Thanks [@jnsdls](https://github.com/jnsdls)! - expose `getChainBySlug` and `ChainSlug` and `ChainId` type
- [#638](https://github.com/thirdweb-dev/js/pull/638) [`e33bd2a8`](https://github.com/thirdweb-dev/js/commit/e33bd2a856bbc2e2f6b0c90b46be5166281875ae) Thanks [@jnsdls](https://github.com/jnsdls)! - Add `getChainByChainId()` to retrieve chain by chainId
- [#685](https://github.com/thirdweb-dev/js/pull/685) [`4355518a`](https://github.com/thirdweb-dev/js/commit/4355518afea68cd8026d3ab8a0144c15d66b9e24) Thanks [@jnsdls](https://github.com/jnsdls)! - update chains
## 0.1.5 ## 0.1.5
### Patch Changes ### Patch Changes
+41
View File
@@ -0,0 +1,41 @@
export default {
"name": "Siberium Network",
"chain": "SBR",
"rpc": [
"https://siberium-network.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.main.siberium.net",
"https://rpc.main.siberium.net.ru"
],
"faucets": [],
"nativeCurrency": {
"name": "Siberium",
"symbol": "SBR",
"decimals": 18
},
"infoURL": "https://siberium.net",
"shortName": "sbr",
"chainId": 111111,
"networkId": 111111,
"icon": {
"url": "ipfs://QmVDeoGo2TZPDWiaNDdPCnH2tz2BCQ7viw8ugdDWnU5LFq",
"width": 1920,
"height": 1920,
"format": "svg"
},
"explorers": [
{
"name": "Siberium Mainnet Explorer - blockscout - 1",
"url": "https://explorer.main.siberium.net",
"icon": "siberium",
"standard": "EIP3091"
},
{
"name": "Siberium Mainnet Explorer - blockscout - 2",
"url": "https://explorer.main.siberium.net.ru",
"icon": "siberium",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "siberium-network"
} as const;
+30
View File
@@ -0,0 +1,30 @@
export default {
"name": "HashBit Mainnet",
"chain": "HBIT",
"rpc": [
"https://hashbit.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://mainnet-rpc.hashbit.org",
"https://rpc.hashbit.org"
],
"faucets": [
"https://free-online-app.com/faucet-for-eth-evm-chains/"
],
"nativeCurrency": {
"name": "HashBit Native Token",
"symbol": "HBIT",
"decimals": 18
},
"infoURL": "https://hashbit.org",
"shortName": "hbit",
"chainId": 11119,
"networkId": 11119,
"explorers": [
{
"name": "hashbitscan",
"url": "https://explorer.hashbit.org",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "hashbit"
} as const;
+1
View File
@@ -5,6 +5,7 @@ export default {
"rpc": [ "rpc": [
"https://sepolia.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://sepolia.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.sepolia.org", "https://rpc.sepolia.org",
"https://rpc2.sepolia.org",
"https://rpc-sepolia.rockx.com" "https://rpc-sepolia.rockx.com"
], ],
"faucets": [ "faucets": [
+1 -1
View File
@@ -9,7 +9,7 @@ export default {
}, },
"rpc": [ "rpc": [
"https://dogcoin.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://dogcoin.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://mainnet-rpc.dogcoin.network" "https://mainnet-rpc.dogcoin.me"
], ],
"faucets": [ "faucets": [
"https://faucet.dogcoin.network" "https://faucet.dogcoin.network"
+6
View File
@@ -15,6 +15,12 @@ export default {
"shortName": "fuse", "shortName": "fuse",
"chainId": 122, "chainId": 122,
"networkId": 122, "networkId": 122,
"icon": {
"url": "ipfs://QmQg8aqyeaMfHvjzFDtZkb8dUNRYhFezPp8UYVc1HnLpRW/green.png",
"format": "png",
"width": 512,
"height": 512
},
"testnet": false, "testnet": false,
"slug": "fuse" "slug": "fuse"
} as const; } as const;
+6
View File
@@ -18,5 +18,11 @@ export default {
"chainId": 123, "chainId": 123,
"networkId": 123, "networkId": 123,
"testnet": true, "testnet": true,
"icon": {
"url": "ipfs://QmQg8aqyeaMfHvjzFDtZkb8dUNRYhFezPp8UYVc1HnLpRW/green.png",
"format": "png",
"width": 512,
"height": 512
},
"slug": "fuse-sparknet" "slug": "fuse-sparknet"
} as const; } as const;
+33
View File
@@ -0,0 +1,33 @@
export default {
"name": "Fibonacci Mainnet",
"chain": "FIBO",
"icon": {
"url": "ipfs://bafkreidiedaz3jugxmh2ylzlc4nympbd5iwab33adhwkcnblyop6vvj25y",
"width": 1494,
"height": 1494,
"format": "png"
},
"rpc": [
"https://fibonacci.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://node1.fibo-api.asia"
],
"faucets": [],
"nativeCurrency": {
"name": "FIBONACCI UTILITY TOKEN",
"symbol": "FIBO",
"decimals": 18
},
"infoURL": "https://fibochain.org",
"shortName": "fibo",
"chainId": 12306,
"networkId": 1230,
"explorers": [
{
"name": "fiboscan",
"url": "https://scan.fibochain.org",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "fibonacci"
} as const;
+45
View File
@@ -0,0 +1,45 @@
export default {
"name": "Horizen Yuma Testnet",
"shortName": "Yuma",
"chain": "Yuma",
"icon": {
"url": "ipfs://QmSFMBk3rMyu45Sy9KQHjgArFj4HdywANNYrSosLMUdcti",
"width": 1213,
"height": 1213,
"format": "png"
},
"rpc": [
"https://horizen-yuma-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://yuma-testnet.horizenlabs.io/ethv1"
],
"features": [
{
"name": "EIP155"
},
{
"name": "EIP1559"
}
],
"faucets": [
"https://yuma-testnet-faucet.horizen.io"
],
"nativeCurrency": {
"name": "Testnet Zen",
"symbol": "tZEN",
"decimals": 18
},
"infoURL": "https://horizen.io/",
"chainId": 1662,
"networkId": 1662,
"slip44": 121,
"explorers": [
{
"name": "Yuma Testnet Block Explorer",
"url": "https://yuma-explorer.horizen.io",
"icon": "eon",
"standard": "EIP3091"
}
],
"testnet": true,
"slug": "horizen-yuma-testnet"
} as const;
+31
View File
@@ -0,0 +1,31 @@
export default {
"name": "Eleanor",
"title": "Metatime Testnet Eleanor",
"chain": "MTC",
"rpc": [
"https://eleanor.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.metatime.com/eleanor",
"wss://ws.metatime.com/eleanor"
],
"faucets": [
"https://faucet.metatime.com/eleanor"
],
"nativeCurrency": {
"name": "Eleanor Metacoin",
"symbol": "MTC",
"decimals": 18
},
"infoURL": "https://eleanor.metatime.com",
"shortName": "mtc",
"chainId": 1967,
"networkId": 1967,
"explorers": [
{
"name": "metaexplorer-eleanor",
"url": "https://explorer.metatime.com/eleanor",
"standard": "EIP3091"
}
],
"testnet": true,
"slug": "eleanor"
} as const;
+2 -1
View File
@@ -3,7 +3,8 @@ export default {
"chain": "edeXa TestNetwork", "chain": "edeXa TestNetwork",
"rpc": [ "rpc": [
"https://edexa-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://edexa-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://testnet.edexa.com/rpc" "https://testnet.edexa.com/rpc",
"https://io-dataseed1.testnet.edexa.io-market.com/rpc"
], ],
"faucets": [ "faucets": [
"https://faucet.edexa.com/" "https://faucet.edexa.com/"
+19
View File
@@ -0,0 +1,19 @@
export default {
"name": "Arevia",
"chain": "Arevia",
"rpc": [],
"faucets": [],
"nativeCurrency": {
"name": "Arev",
"symbol": "ARÉV",
"decimals": 18
},
"infoURL": "",
"shortName": "arevia",
"chainId": 2309,
"networkId": 2309,
"explorers": [],
"status": "incubating",
"testnet": false,
"slug": "arevia"
} as const;
+15
View File
@@ -29,6 +29,21 @@ export default {
"url": "https://filfox.info/en", "url": "https://filfox.info/en",
"standard": "none" "standard": "none"
}, },
{
"name": "Beryx",
"url": "https://beryx.zondax.ch",
"standard": "none"
},
{
"name": "Glif Explorer",
"url": "https://explorer.glif.io",
"standard": "EIP3091"
},
{
"name": "Filmine",
"url": "https://explorer.filmine.io",
"standard": "none"
},
{ {
"name": "Filscan", "name": "Filscan",
"url": "https://filscan.io", "url": "https://filscan.io",
+1
View File
@@ -10,6 +10,7 @@ export default {
"rpc": [ "rpc": [
"https://filecoin-hyperspace-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://filecoin-hyperspace-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://api.hyperspace.node.glif.io/rpc/v1", "https://api.hyperspace.node.glif.io/rpc/v1",
"https://rpc.ankr.com/filecoin_testnet",
"https://filecoin-hyperspace.chainstacklabs.com/rpc/v1" "https://filecoin-hyperspace.chainstacklabs.com/rpc/v1"
], ],
"faucets": [ "faucets": [
+35
View File
@@ -0,0 +1,35 @@
export default {
"name": "Tipboxcoin Mainnet",
"chain": "TPBX",
"icon": {
"url": "ipfs://QmbiaHnR3fVVofZ7Xq2GYZxwHkLEy3Fh5qDtqnqXD6ACAh",
"width": 192,
"height": 192,
"format": "png"
},
"rpc": [
"https://tipboxcoin.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://mainnet-rpc.tipboxcoin.net"
],
"faucets": [
"https://faucet.tipboxcoin.net"
],
"nativeCurrency": {
"name": "Tipboxcoin",
"symbol": "TPBX",
"decimals": 18
},
"infoURL": "https://tipboxcoin.net",
"shortName": "TPBXm",
"chainId": 404040,
"networkId": 404040,
"explorers": [
{
"name": "Tipboxcoin",
"url": "https://tipboxcoin.net",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "tipboxcoin"
} as const;
+33
View File
@@ -0,0 +1,33 @@
export default {
"name": "Nahmii 3 Mainnet",
"chain": "Nahmii",
"rpc": [],
"status": "incubating",
"faucets": [],
"nativeCurrency": {
"name": "Ether",
"symbol": "ETH",
"decimals": 18
},
"infoURL": "https://nahmii.io",
"shortName": "Nahmii3Mainnet",
"chainId": 4061,
"networkId": 4061,
"icon": {
"url": "ipfs://QmZhKXgoGpzvthr2eh8ZNgT75YvMtEBegdELAaMPPzf5QT",
"width": 384,
"height": 384,
"format": "png"
},
"parent": {
"type": "L2",
"chain": "eip155-1",
"bridges": [
{
"url": "https://bridge.nahmii.io"
}
]
},
"testnet": false,
"slug": "nahmii-3"
} as const;
+43
View File
@@ -0,0 +1,43 @@
export default {
"name": "Nahmii 3 Testnet",
"chain": "Nahmii",
"rpc": [
"https://nahmii-3-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://ngeth.testnet.n3.nahmii.io"
],
"faucets": [],
"nativeCurrency": {
"name": "Goerli Ether",
"symbol": "ETH",
"decimals": 18
},
"infoURL": "https://nahmii.io",
"shortName": "Nahmii3Testnet",
"chainId": 4062,
"networkId": 4062,
"icon": {
"url": "ipfs://QmZhKXgoGpzvthr2eh8ZNgT75YvMtEBegdELAaMPPzf5QT",
"width": 384,
"height": 384,
"format": "png"
},
"explorers": [
{
"name": "Nahmii 3 Testnet Explorer",
"url": "https://explorer.testnet.n3.nahmii.io",
"icon": "nahmii",
"standard": "EIP3091"
}
],
"parent": {
"type": "L2",
"chain": "eip155-3",
"bridges": [
{
"url": "https://bridge.testnet.n3.nahmii.io"
}
]
},
"testnet": true,
"slug": "nahmii-3-testnet"
} as const;
+35
View File
@@ -0,0 +1,35 @@
export default {
"name": "Tipboxcoin Testnet",
"chain": "TPBX",
"icon": {
"url": "ipfs://QmbiaHnR3fVVofZ7Xq2GYZxwHkLEy3Fh5qDtqnqXD6ACAh",
"width": 192,
"height": 192,
"format": "png"
},
"rpc": [
"https://tipboxcoin-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://testnet-rpc.tipboxcoin.net"
],
"faucets": [
"https://faucet.tipboxcoin.net"
],
"nativeCurrency": {
"name": "Tipboxcoin",
"symbol": "TPBX",
"decimals": 18
},
"infoURL": "https://tipboxcoin.net",
"shortName": "TPBXt",
"chainId": 4141,
"networkId": 4141,
"explorers": [
{
"name": "Tipboxcoin",
"url": "https://testnet.tipboxcoin.net",
"standard": "EIP3091"
}
],
"testnet": true,
"slug": "tipboxcoin-testnet"
} as const;
+30
View File
@@ -0,0 +1,30 @@
export default {
"name": "BeanEco SmartChain",
"title": "BESC Mainnet",
"chain": "BESC",
"rpc": [
"https://beaneco-smartchain.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://mainnet-rpc.bescscan.io"
],
"faucets": [
"faucet.bescscan.ion"
],
"nativeCurrency": {
"name": "BeanEco SmartChain",
"symbol": "BESC",
"decimals": 18
},
"infoURL": "besceco.finance",
"shortName": "BESC",
"chainId": 535037,
"networkId": 535037,
"explorers": [
{
"name": "bescscan",
"url": "https://Bescscan.io",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "beaneco-smartchain"
} as const;
+6
View File
@@ -18,6 +18,12 @@ export default {
"shortName": "bakerloo-0", "shortName": "bakerloo-0",
"chainId": 65010000, "chainId": 65010000,
"networkId": 65010000, "networkId": 65010000,
"icon": {
"url": "ipfs://Qme5nxFZZoNNpiT8u9WwcBot4HyLTg2jxMxRnsbc5voQwB",
"width": 1000,
"height": 1000,
"format": "png"
},
"explorers": [ "explorers": [
{ {
"name": "autonity-blockscout", "name": "autonity-blockscout",
+6
View File
@@ -18,6 +18,12 @@ export default {
"shortName": "piccadilly-0", "shortName": "piccadilly-0",
"chainId": 65100000, "chainId": 65100000,
"networkId": 65100000, "networkId": 65100000,
"icon": {
"url": "ipfs://Qme5nxFZZoNNpiT8u9WwcBot4HyLTg2jxMxRnsbc5voQwB",
"width": 1000,
"height": 1000,
"format": "png"
},
"explorers": [ "explorers": [
{ {
"name": "autonity-blockscout", "name": "autonity-blockscout",
-27
View File
@@ -1,27 +0,0 @@
export default {
"name": "SiriusNet",
"chain": "SIN",
"rpc": [
"https://siriusnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://u0tnafcv6j:o2T045sxuCNXL878RDQLp5__Zj-es2cvdjtgkl4etn0@u0v7kwtvtg-u0wj114sve-rpc.us0-aws.kaleido.io/"
],
"faucets": [],
"nativeCurrency": {
"name": "MCD",
"symbol": "MCD",
"decimals": 18
},
"infoURL": "https://macaucasinolisboa.xyz",
"shortName": "mcl",
"chainId": 67390,
"networkId": 67390,
"explorers": [
{
"name": "siriusnetscan",
"url": "https://siriusnet.tryethernal.com",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "siriusnet"
} as const;
+37
View File
@@ -0,0 +1,37 @@
export default {
"name": "KLYNTAR",
"chain": "KLY",
"rpc": [
"https://klyntar.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://evm.klyntar.org/kly_evm_rpc",
"https://evm.klyntarscan.org/kly_evm_rpc"
],
"faucets": [],
"nativeCurrency": {
"name": "KLYNTAR",
"symbol": "KLY",
"decimals": 18
},
"features": [
{
"name": "EIP155"
},
{
"name": "EIP1559"
}
],
"infoURL": "https://klyntar.org",
"shortName": "kly",
"chainId": 7331,
"networkId": 7331,
"icon": {
"url": "ipfs://QmaDr9R6dKnZLsogRxojjq4dwXuXcudR8UeTZ8Nq553K4u",
"width": 400,
"height": 400,
"format": "png"
},
"explorers": [],
"status": "incubating",
"testnet": false,
"slug": "klyntar"
} as const;
+14
View File
@@ -3,6 +3,9 @@ export default {
"chain": "KLAY", "chain": "KLAY",
"rpc": [ "rpc": [
"https://klaytn-cypress.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://klaytn-cypress.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://klaytn.blockpi.network/v1/rpc/public",
"https://klaytn-mainnet-rpc.allthatnode.com:8551",
"https://public-en-cypress.klaytn.net",
"https://public-node-api.klaytnapi.com/v1/cypress" "https://public-node-api.klaytnapi.com/v1/cypress"
], ],
"faucets": [], "faucets": [],
@@ -17,12 +20,23 @@ export default {
"networkId": 8217, "networkId": 8217,
"slip44": 8217, "slip44": 8217,
"explorers": [ "explorers": [
{
"name": "klaytnfinder",
"url": "https://www.klaytnfinder.io/",
"standard": "none"
},
{ {
"name": "Klaytnscope", "name": "Klaytnscope",
"url": "https://scope.klaytn.com", "url": "https://scope.klaytn.com",
"standard": "none" "standard": "none"
} }
], ],
"icon": {
"format": "png",
"url": "ipfs://bafkreigtgdivlmfvf7trqjqy4vkz2d26xk3iif6av265v4klu5qavsugm4",
"height": 1000,
"width": 1000
},
"testnet": false, "testnet": false,
"slug": "klaytn-cypress" "slug": "klaytn-cypress"
} as const; } as const;
+24
View File
@@ -0,0 +1,24 @@
export default {
"name": "Base",
"chain": "ETH",
"rpc": [],
"faucets": [],
"nativeCurrency": {
"name": "Ether",
"symbol": "ETH",
"decimals": 18
},
"infoURL": "https://base.org",
"shortName": "base",
"chainId": 8453,
"networkId": 8453,
"status": "incubating",
"icon": {
"url": "ipfs://QmW5Vn15HeRkScMfPcW12ZdZcC2yUASpu6eCsECRdEmjjj/base-512.png",
"height": 512,
"width": 512,
"format": "png"
},
"testnet": false,
"slug": "base"
} as const;
+1 -1
View File
@@ -9,7 +9,7 @@ export default {
}, },
"rpc": [ "rpc": [
"https://dogcoin-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://dogcoin-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://testnet-rpc.dogcoin.network" "https://testnet-rpc.dogcoin.me"
], ],
"faucets": [ "faucets": [
"https://faucet.dogcoin.network" "https://faucet.dogcoin.network"
+13
View File
@@ -0,0 +1,13 @@
// @ts-check
/** @typedef { import("../../src/types").Chain } Chain */
/** @type {Partial<Chain>} */
export default {
chainId: 122,
icon: {
url: "ipfs://QmQg8aqyeaMfHvjzFDtZkb8dUNRYhFezPp8UYVc1HnLpRW/green.png",
format: "png",
width: 512,
height: 512,
},
};
+14
View File
@@ -0,0 +1,14 @@
// @ts-check
/** @typedef { import("../../src/types").Chain } Chain */
/** @type {Partial<Chain>} */
export default {
chainId: 123,
testnet: true,
icon: {
url: "ipfs://QmQg8aqyeaMfHvjzFDtZkb8dUNRYhFezPp8UYVc1HnLpRW/green.png",
format: "png",
width: 512,
height: 512,
},
};
+25
View File
@@ -0,0 +1,25 @@
// @ts-check
/** @typedef { import("../../src/types").Chain } Chain */
/** @type {Partial<Chain>} */
export default {
chainId: 8217,
rpc: [
"https://public-en-cypress.klaytn.net",
"https://klaytn-mainnet-rpc.allthatnode.com:8551",
"https://klaytn.blockpi.network/v1/rpc/public",
],
explorers: [
{
name: "klaytnfinder",
url: "https://www.klaytnfinder.io/",
standard: "none",
},
],
icon: {
format: "png",
url: "ipfs://bafkreigtgdivlmfvf7trqjqy4vkz2d26xk3iif6av265v4klu5qavsugm4",
height: 1000,
width: 1000,
},
};
+4 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/chains", "name": "@thirdweb-dev/chains",
"version": "0.1.5", "version": "0.1.6",
"main": "dist/thirdweb-dev-chains.cjs.js", "main": "dist/thirdweb-dev-chains.cjs.js",
"module": "dist/thirdweb-dev-chains.esm.js", "module": "dist/thirdweb-dev-chains.esm.js",
"exports": { "exports": {
@@ -18,6 +18,7 @@
"author": "thirdweb eng <[email protected]>", "author": "thirdweb eng <[email protected]>",
"devDependencies": { "devDependencies": {
"axios": "^0.27.2", "axios": "^0.27.2",
"jest": "^29.4.3",
"plop": "^3.1.2", "plop": "^3.1.2",
"typescript": "^4.7.4" "typescript": "^4.7.4"
}, },
@@ -33,6 +34,7 @@
"push": "yalc push", "push": "yalc push",
"plop": "plop", "plop": "plop",
"add-chain": "plop add-chain", "add-chain": "plop add-chain",
"override-chain": "plop override-chain" "override-chain": "plop override-chain",
"test": "jest"
} }
} }
+25 -3
View File
@@ -30,7 +30,8 @@ let overrides = {};
const overridesDir = path.join(process.cwd(), "./data/overrides"); const overridesDir = path.join(process.cwd(), "./data/overrides");
const overridesFiles = fs.readdirSync(overridesDir); const overridesFiles = fs.readdirSync(overridesDir);
for (const file of overridesFiles) { for (const file of overridesFiles) {
const override = await import(path.join(overridesDir, file)); // file:// is required for windows builds
const override = await import(path.join("file://", overridesDir, file));
// get file name without extension // get file name without extension
const chainId = parseInt(file.split(".")[0]); const chainId = parseInt(file.split(".")[0]);
overrides[chainId] = override.default; overrides[chainId] = override.default;
@@ -49,7 +50,10 @@ chains = chains.filter((c) => c.chainId !== 1337);
const additionalChainsDir = path.join(process.cwd(), "./data/additional"); const additionalChainsDir = path.join(process.cwd(), "./data/additional");
const additionalChainsFiles = fs.readdirSync(additionalChainsDir); const additionalChainsFiles = fs.readdirSync(additionalChainsDir);
for (const file of additionalChainsFiles) { for (const file of additionalChainsFiles) {
const additionalChain = await import(path.join(additionalChainsDir, file)); // file:// is required for windows builds
const additionalChain = await import(
path.join("file://", additionalChainsDir, file)
);
chains.push(additionalChain.default); chains.push(additionalChain.default);
} }
@@ -206,5 +210,23 @@ export * from "./types";
export * from "./utils"; export * from "./utils";
export const defaultChains = [Ethereum, Goerli, Polygon, Mumbai, Arbitrum, ArbitrumGoerli, Optimism, OptimismGoerli, Binance, BinanceTestnet, Fantom, FantomTestnet, Avalanche, AvalancheFuji, Localhost]; export const defaultChains = [Ethereum, Goerli, Polygon, Mumbai, Arbitrum, ArbitrumGoerli, Optimism, OptimismGoerli, Binance, BinanceTestnet, Fantom, FantomTestnet, Avalanche, AvalancheFuji, Localhost];
export const allChains = [${exportNames.join(", ")}]; export const allChains = [${exportNames.join(", ")}];
`,
export function getChainByChainId(chainId: number): Chain {
const chain = allChains.find(chain => chain.chainId === chainId);
if (!chain) {
throw new Error(\`Chain with chainId "\${chainId}" not found\`);
}
return chain;
}
export function getChainBySlug(slug: string): Chain {
const chain = allChains.find(chain => chain.slug === slug);
if (!chain) {
throw new Error(\`Chain with slug "\${slug}" not found\`);
}
return chain;
}
export type ChainSlug = typeof allChains[number]["slug"];
export type ChainId = typeof allChains[number]["chainId"];`,
); );
File diff suppressed because one or more lines are too long
+17
View File
@@ -11,6 +11,14 @@ const defaultOptions = {
mode: "http", mode: "http",
} as const; } as const;
/**
* Construct the list of RPC URLs given a specific chain config. Format any RPC URLs
* with necessary API keys.
*
* @param chain - The chain config to assemble RPC URLs from
* @param options - Options to configure the RPC URLs
* @returns The list of RPC URLs for the chain
*/
export function getChainRPCs( export function getChainRPCs(
chain: Pick<Chain, "rpc" | "chainId">, chain: Pick<Chain, "rpc" | "chainId">,
options?: ChainRPCOptions, options?: ChainRPCOptions,
@@ -75,6 +83,15 @@ export function getChainRPCs(
return orderedRPCs; return orderedRPCs;
} }
/**
* Get the highest priority RPC URL for a specific chain
*
* @param chain - The chain config to get the RPC URL for
* @param options - Options to configure the RPC URL
* @returns The RPC URL for the chain
*
* @internal
*/
export function getChainRPC( export function getChainRPC(
chain: Pick<Chain, "rpc" | "chainId">, chain: Pick<Chain, "rpc" | "chainId">,
options?: ChainRPCOptions, options?: ChainRPCOptions,
@@ -0,0 +1,5 @@
import { getChainByChainId, Goerli } from "../src";
test("expect chainId 5 to be goerli", () => {
expect(getChainByChainId(5)).toBe(Goerli);
});
+29
View File
@@ -1,5 +1,34 @@
# thirdweb # thirdweb
## 0.10.1
### Patch Changes
- Updated dependencies [[`68d52f99`](https://github.com/thirdweb-dev/js/commit/68d52f99b36c6744e45872d0bdebafbbf7d09b59)]:
- @thirdweb-dev/sdk@3.10.1
## 0.10.0
### Minor Changes
- [#678](https://github.com/thirdweb-dev/js/pull/678) [`c9067681`](https://github.com/thirdweb-dev/js/commit/c9067681c21f7506d002182415d50918d31cba77) Thanks [@nkrishang](https://github.com/nkrishang)! - Add --dynamic option to deploy command
### Patch Changes
- [#665](https://github.com/thirdweb-dev/js/pull/665) [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75) Thanks [@shift4id](https://github.com/shift4id)! - Fix spelling throughout all packages
- [#662](https://github.com/thirdweb-dev/js/pull/662) [`3740a0bf`](https://github.com/thirdweb-dev/js/commit/3740a0bf5db1301dbd93a97ab4c9343429a4e12d) Thanks [@furqanrydhan](https://github.com/furqanrydhan)! - Change URL for thirdweb app deploy redirect
- [#664](https://github.com/thirdweb-dev/js/pull/664) [`39855609`](https://github.com/thirdweb-dev/js/commit/398556094245a4a6865ed1cb93a4ee3b1f37fb49) Thanks [@jnsdls](https://github.com/jnsdls)! - Add `@thirdweb-dev/storage` to dependencies explicitly
- [#641](https://github.com/thirdweb-dev/js/pull/641) [`842ed519`](https://github.com/thirdweb-dev/js/commit/842ed519a3fd68dc456fcb3f50d6927a9e39d681) Thanks [@nkrishang](https://github.com/nkrishang)! - Add CLI command to create dynamic contract extensions.
- [#666](https://github.com/thirdweb-dev/js/pull/666) [`be04ff27`](https://github.com/thirdweb-dev/js/commit/be04ff27759d8f63409fc46def83fe838eefb285) Thanks [@shift4id](https://github.com/shift4id)! - various cli fixes
- Updated dependencies [[`a7e908b5`](https://github.com/thirdweb-dev/js/commit/a7e908b5fe60803e64b418cf42e081ca75123a45), [`61ef6964`](https://github.com/thirdweb-dev/js/commit/61ef69649fb605f6079dd9bbef12b739b02dda30), [`2f4cd928`](https://github.com/thirdweb-dev/js/commit/2f4cd92848a6c8cec4e86654f376a6d15bdd2b52), [`8a8a37f6`](https://github.com/thirdweb-dev/js/commit/8a8a37f6d3468b2a9c9736834bc39a3eee4754f4), [`63f552d7`](https://github.com/thirdweb-dev/js/commit/63f552d736a549532eb4d6a05cfe66a771b190b9), [`fb346ffd`](https://github.com/thirdweb-dev/js/commit/fb346ffd45edf9f50cc8c68a0c318eee39a6d9c6), [`e081075b`](https://github.com/thirdweb-dev/js/commit/e081075b2cebc7edad855481366bd9864ddba102), [`d8dec9fc`](https://github.com/thirdweb-dev/js/commit/d8dec9fc19079c79729857c36e45102c90fb7e0a), [`478780f6`](https://github.com/thirdweb-dev/js/commit/478780f6349595c17a7b3cd7de7668973c201d65), [`b83ea525`](https://github.com/thirdweb-dev/js/commit/b83ea5251bcd07feaab02a7ad1be202ccc6147fd), [`541dfeea`](https://github.com/thirdweb-dev/js/commit/541dfeeabaa744880cf78b310a9d61db4dfb32b3), [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75), [`0c883044`](https://github.com/thirdweb-dev/js/commit/0c88304464ef4461a660a374198e893c578c8de0), [`0666f37c`](https://github.com/thirdweb-dev/js/commit/0666f37c13ed4b824e238325f9d13b9af785e0b0), [`85250cf7`](https://github.com/thirdweb-dev/js/commit/85250cf71190092b61023d56d1e786d395a008a6), [`b80024c6`](https://github.com/thirdweb-dev/js/commit/b80024c6cca17541c9b5ebb51c1476e9f210d3ab), [`8845bf96`](https://github.com/thirdweb-dev/js/commit/8845bf960e18c89d0e1f2fe1c370f4e2f4e855d0), [`2335f000`](https://github.com/thirdweb-dev/js/commit/2335f000c9023dd47b1a341a4dd40ed674e9bcdb), [`696c384a`](https://github.com/thirdweb-dev/js/commit/696c384a348890202e37cbd8488b1b1eceb4e8c2), [`3740a0bf`](https://github.com/thirdweb-dev/js/commit/3740a0bf5db1301dbd93a97ab4c9343429a4e12d), [`cc7ce8b1`](https://github.com/thirdweb-dev/js/commit/cc7ce8b1e8f73288b5c00a29e0000bea9867e8c1), [`91f5a2fd`](https://github.com/thirdweb-dev/js/commit/91f5a2fd5cb2f5aed6498defdb1feeabb283db6c), [`537785fe`](https://github.com/thirdweb-dev/js/commit/537785fed0021345b0d1cec37658e43c65931f9f), [`29c1cf7e`](https://github.com/thirdweb-dev/js/commit/29c1cf7eff60221d05e87060f3c96a83343218e6), [`b6b0855b`](https://github.com/thirdweb-dev/js/commit/b6b0855b81854ec3d5dd3c763a1ad2a235837cc9), [`2a8cc289`](https://github.com/thirdweb-dev/js/commit/2a8cc289ac42273800554a247cb9259a8f0329d7), [`1e1a3912`](https://github.com/thirdweb-dev/js/commit/1e1a39123bad2b96c332ebb58b25369b31dd9de7), [`dc08aa73`](https://github.com/thirdweb-dev/js/commit/dc08aa731f92ce3c2dd232378637a3075137367d), [`bd6be0ba`](https://github.com/thirdweb-dev/js/commit/bd6be0bae78511878c2344949bb212dab30ec30c)]:
- @thirdweb-dev/sdk@3.10.0
- @thirdweb-dev/storage@1.1.0
## 0.9.25 ## 0.9.25
### Patch Changes ### Patch Changes
+2 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "thirdweb", "name": "thirdweb",
"main": "dist/cli/index.js", "main": "dist/cli/index.js",
"version": "0.9.25", "version": "0.10.1",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
"author": "thirdweb eng <[email protected]>", "author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -30,6 +30,7 @@
}, },
"dependencies": { "dependencies": {
"@thirdweb-dev/sdk": "*", "@thirdweb-dev/sdk": "*",
"@thirdweb-dev/storage": "*",
"async-retry": "^1.3.3", "async-retry": "^1.3.3",
"commander": "^9.1.0", "commander": "^9.1.0",
"detect-package-manager": "^2.0.1", "detect-package-manager": "^2.0.1",
+15 -20
View File
@@ -54,10 +54,7 @@ const main = async () => {
if (lastCheckCache.isCached) { if (lastCheckCache.isCached) {
const lastVersionCheck = new Date(lastCheckCache.value); const lastVersionCheck = new Date(lastCheckCache.value);
// Don't check for updates if already checked within past 24 hours // Don't check for updates if already checked within past 24 hours
if ( if (Date.now() - lastVersionCheck.getTime() < 1000 * 60 * 60 * 24) {
new Date().getTime() - lastVersionCheck.getTime() <
1000 * 60 * 60 * 24
) {
shouldCheckVersion = false; shouldCheckVersion = false;
} }
} }
@@ -115,7 +112,7 @@ const main = async () => {
`Now using CLI version ${versionInfo.latest}. Continuing execution...`, `Now using CLI version ${versionInfo.latest}. Continuing execution...`,
); );
await new Promise((done, failed) => { await new Promise((resolve, reject) => {
const shell = spawn( const shell = spawn(
`npx --yes thirdweb@latest ${process.argv `npx --yes thirdweb@latest ${process.argv
.slice(2) .slice(2)
@@ -125,9 +122,9 @@ const main = async () => {
); );
shell.on("close", (code) => { shell.on("close", (code) => {
if (code === 0) { if (code === 0) {
done(""); resolve("");
} else { } else {
failed(); reject();
} }
}); });
}); });
@@ -160,14 +157,10 @@ const main = async () => {
process.exit(1); process.exit(1);
} }
await new Promise((done, failed) => { await new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => { exec(command, (err, stdout, stderr) => {
if (err) { if (err) {return reject(err);}
failed(err); resolve({ stdout, stderr });
return;
}
done({ stdout, stderr });
}); });
}); });
@@ -181,7 +174,7 @@ const main = async () => {
!installation.isGlobal || installation.packageManager === "npm" !installation.isGlobal || installation.packageManager === "npm"
? `npx thirdweb` ? `npx thirdweb`
: `thirdweb`; : `thirdweb`;
await new Promise((done, failed) => { await new Promise((resolve, reject) => {
const shell = spawn( const shell = spawn(
`${executionCommand} ${process.argv.slice(2).join(" ")}`, `${executionCommand} ${process.argv.slice(2).join(" ")}`,
[], [],
@@ -189,9 +182,9 @@ const main = async () => {
); );
shell.on("close", (code) => { shell.on("close", (code) => {
if (code === 0) { if (code === 0) {
done(""); resolve("");
} else { } else {
failed(); reject();
} }
}); });
}); });
@@ -214,6 +207,7 @@ const main = async () => {
.option("--js, --javascript", "Initialize as a JavaScript project.") .option("--js, --javascript", "Initialize as a JavaScript project.")
.option("--forge", "Initialize as a Forge project.") .option("--forge", "Initialize as a Forge project.")
.option("--hardhat", "Initialize as a Hardhat project.") .option("--hardhat", "Initialize as a Hardhat project.")
.option("--extension", "Create a smart contract extension.")
.option("--cra", "Initialize as a Create React App project.") .option("--cra", "Initialize as a Create React App project.")
.option("--next", "Initialize as a Next.js project.") .option("--next", "Initialize as a Next.js project.")
.option("--vite", "Initialize as a Vite project.") .option("--vite", "Initialize as a Vite project.")
@@ -282,10 +276,11 @@ const main = async () => {
) )
.option("--app", "Deploy a web app to decentralized storage") .option("--app", "Deploy a web app to decentralized storage")
.option("--contract", "Deploy a smart contract to blockchains") .option("--contract", "Deploy a smart contract to blockchains")
.option("--dynamic", "Deploy a dynamic smart contract made up of extensions to blockchains")
.action(async (options) => { .action(async (options) => {
const url = await deploy(options); const url = await deploy(options);
if (url) { if (url) {
open(url); await open(url);
} }
}); });
@@ -314,7 +309,7 @@ const main = async () => {
url.toString(), url.toString(),
)}`, )}`,
); );
open(url.toString()); await open(url.toString());
}); });
program program
@@ -341,7 +336,7 @@ const main = async () => {
url.toString(), url.toString(),
)}`, )}`,
); );
open(url.toString()); await open(url.toString());
}); });
program program
+1 -1
View File
@@ -21,7 +21,7 @@ export function findFiles(
} }
const stat = statSync(filename); const stat = statSync(filename);
// brownie has a "depdendencies" directory *inside* the build directory, if we detect that we should skip it // brownie has a "dependencies" directory *inside* the build directory, if we detect that we should skip it
if (stat.isDirectory() && basename(filename) === "dependencies") { if (stat.isDirectory() && basename(filename) === "dependencies") {
logger.debug('skipping "dependencies" directory'); logger.debug('skipping "dependencies" directory');
continue; continue;
+148 -14
View File
@@ -3,14 +3,19 @@ import build from "../core/builder/build";
import detect from "../core/detection/detect"; import detect from "../core/detection/detect";
import { execute } from "../core/helpers/exec"; import { execute } from "../core/helpers/exec";
import { error, info, logger, spinner } from "../core/helpers/logger"; import { error, info, logger, spinner } from "../core/helpers/logger";
import { createContractsPrompt } from "../core/helpers/selector"; import { createContractsPrompt, createRouterPrompt } from "../core/helpers/selector";
import { ContractPayload } from "../core/interfaces/ContractPayload"; import { ContractPayload } from "../core/interfaces/ContractPayload";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { detectFeatures } from "@thirdweb-dev/sdk";
import chalk from "chalk"; import chalk from "chalk";
import { readFileSync } from "fs"; import { readFileSync, writeFileSync } from "fs";
import { ethers } from "ethers";
import ora from "ora"; import ora from "ora";
import path from "path"; import path from "path";
import { Extension, ExtensionFunction, ExtensionMetadata, ExtensionDeployArgs } from "../core/interfaces/Extension";
import { EXTENSION_REGISTRY_ADDRESS, ROUTER_CONTRACTS, PreDeployedRouter, TWRouterParams, RouterParams } from "../constants/router-contracts";
export async function processProject( export async function processProject(
options: any, options: any,
command: "deploy" | "publish", command: "deploy" | "publish",
@@ -94,6 +99,37 @@ export async function processProject(
process.exit(1); process.exit(1);
} }
let selectedRouter: PreDeployedRouter = { name: "", metadataUri: "", bytecodeUri: ""};
if(options.dynamic) {
const choices = Object.keys(ROUTER_CONTRACTS).map((key) => { return { title: key, value: key } });
let routerType: string = "";
const res = await createRouterPrompt(
choices,
"Choose a router to deploy",
);
if (typeof res.routerType === "string") {
routerType = res.routerType.trim();
}
selectedRouter = ROUTER_CONTRACTS[routerType];
}
if(options.dynamic && !selectedRouter) {
error(
`No router selected. Please select a router contract to deploy.`,
);
process.exit(1);
}
if (options.dynamic && !selectedRouter.name) {
error(
`No router selected. Please select a router contract to deploy.`,
);
process.exit(1);
}
let selectedContracts: ContractPayload[] = []; let selectedContracts: ContractPayload[] = [];
if (compiledResult.contracts.length === 1) { if (compiledResult.contracts.length === 1) {
selectedContracts = [compiledResult.contracts[0]]; selectedContracts = [compiledResult.contracts[0]];
@@ -149,7 +185,7 @@ export async function processProject(
}); });
const prompt = createContractsPrompt( const prompt = createContractsPrompt(
choices, choices,
`Choose which contract(s) to ${command}`, options.dynamic ? "Choose which extensions to add to your contract" : `Choose which contract(s) to ${command}`,
); );
const selection: Record<string, ContractPayload> = await prompt.run(); const selection: Record<string, ContractPayload> = await prompt.run();
selectedContracts = Object.keys(selection).map((key) => selection[key]); selectedContracts = Object.keys(selection).map((key) => selection[key]);
@@ -168,12 +204,31 @@ export async function processProject(
process.exit(0); process.exit(0);
} }
const loader = spinner("Uploading contract data...");
const soliditySDKPackage = "@thirdweb-dev/contracts"; const soliditySDKPackage = "@thirdweb-dev/contracts";
let usesSoliditySDK = false; let usesSoliditySDK = false;
if(selectedRouter.name === "thirdweb-router") {
const deployArgs: TWRouterParams = {
extensionRegistry: EXTENSION_REGISTRY_ADDRESS,
extensionNames: selectedContracts.map((c) => c.name),
}
const outputDeployArgs = JSON.stringify(deployArgs, undefined, 2);
writeFileSync("./deployArgs.json", outputDeployArgs, "utf-8");
info("Deployment parameters written to deployArgs.json in your project directory");
} else {
const deployArgs: RouterParams = await formatToExtensions(selectedContracts);
const outputDeployArgs = JSON.stringify(deployArgs, undefined, 2);
writeFileSync("./deployArgs.json", outputDeployArgs, "utf-8");
info("Deployment parameters written to deployArgs.json in your project directory");
}
const loader = spinner("Uploading contract data...");
try { try {
// Upload contract sources.
for (let i = 0; i < selectedContracts.length; i++) { for (let i = 0; i < selectedContracts.length; i++) {
const contract = selectedContracts[i]; const contract = selectedContracts[i];
if (contract.sources) { if (contract.sources) {
@@ -201,6 +256,7 @@ export async function processProject(
const metadataURIs = await Promise.all( const metadataURIs = await Promise.all(
selectedContracts.map(async (c) => { selectedContracts.map(async (c) => {
logger.debug(`Uploading ${c.name}...`); logger.debug(`Uploading ${c.name}...`);
return await storage.upload(JSON.parse(JSON.stringify(c.metadata)), { return await storage.upload(JSON.parse(JSON.stringify(c.metadata)), {
uploadWithoutDirectory: true, uploadWithoutDirectory: true,
}); });
@@ -211,23 +267,47 @@ export async function processProject(
const bytecodes = selectedContracts.map((c) => c.bytecode); const bytecodes = selectedContracts.map((c) => c.bytecode);
const bytecodeURIs = await storage.uploadBatch(bytecodes); const bytecodeURIs = await storage.uploadBatch(bytecodes);
const combinedContents = selectedContracts.map((c, i) => { let combinedContents = [];
// attach analytics blob to metadata if(options.dynamic) {
const analytics = { const analytics = {
command, command,
contract_name: c.name, contract_name: selectedRouter.name,
cli_version: cliVersion, cli_version: cliVersion,
project_type: projectType, project_type: projectType,
from_ci: options.ci || false, from_ci: options.ci || false,
uses_contract_extensions: usesSoliditySDK, uses_contract_extensions: usesSoliditySDK,
}; };
return {
name: c.name, combinedContents.push({
metadataUri: metadataURIs[i], name: selectedRouter.name,
bytecodeUri: bytecodeURIs[i], metadataUri: selectedRouter.metadataUri,
bytecodeUri: selectedRouter.bytecodeUri,
analytics, analytics,
}; })
});
} else {
combinedContents = selectedContracts.map((c, i) => {
// attach analytics blob to metadata
const analytics = {
command,
contract_name: c.name,
cli_version: cliVersion,
project_type: projectType,
from_ci: options.ci || false,
uses_contract_extensions: usesSoliditySDK,
};
return {
name: c.name,
metadataUri: metadataURIs[i],
bytecodeUri: bytecodeURIs[i],
analytics,
};
});
}
let combinedURIs: string[] = []; let combinedURIs: string[] = [];
if (combinedContents.length === 1) { if (combinedContents.length === 1) {
// use upload single if only one contract to get a clean IPFS hash // use upload single if only one contract to get a clean IPFS hash
@@ -265,3 +345,57 @@ export function getUrl(hashes: string[], command: string) {
} }
return url; return url;
} }
async function formatToExtensions(contracts: ContractPayload[]): Promise<{extensions: Extension[], extensionDeployArgs: ExtensionDeployArgs[]}> {
const storage = new ThirdwebStorage();
const extensions: Extension[] = [];
const extensionDeployArgs: ExtensionDeployArgs[] = [];
for(const contract of contracts) {
// Prepare extension metadata.
let metadata: ExtensionMetadata = {
name: contract.name,
metadataURI: await getMetadataURIForExtension(contract, storage),
implementation: ethers.constants.AddressZero
}
// Get extension ABI.
const abi: Parameters<typeof detectFeatures>[0] = JSON.parse(
contract.metadata,
)["output"]["abi"];
// Format ABI as `ExtensionFunction[]`.
const extensionInterface = new ethers.utils.Interface(abi);
const functions: ExtensionFunction[] = [];
const fragments = extensionInterface.functions;
for (const fnSignature of Object.keys(fragments)) {
functions.push({
functionSelector: extensionInterface.getSighash(fragments[fnSignature]),
functionSignature: fnSignature
});
}
extensions.push({
metadata,
functions
});
extensionDeployArgs.push({
name: contract.name,
amount: 0,
salt: ethers.utils.keccak256(ethers.utils.toUtf8Bytes(contract.name)),
bytecode: contract.bytecode
})
}
return { extensions, extensionDeployArgs };
}
async function getMetadataURIForExtension(contract: ContractPayload, storage: ThirdwebStorage): Promise<string> {
return await storage.upload(JSON.parse(JSON.stringify(contract.metadata)), {
uploadWithoutDirectory: true,
});
}
@@ -0,0 +1,37 @@
import { Extension, ExtensionDeployArgs } from "../core/interfaces/Extension";
export interface PreDeployedRouter {
name: string;
metadataUri: string;
bytecodeUri: string;
}
export interface RouterParams {
extensions: Extension[];
extensionDeployArgs: ExtensionDeployArgs[];
}
export interface TWRouterParams {
extensionRegistry: string;
extensionNames: string[];
}
export const EXTENSION_REGISTRY_ADDRESS: string = "0x0000000000000000000000000000000000000000";
export const ROUTER_CONTRACTS: Record<string, PreDeployedRouter> = {
"upgradeable": {
name: "RouterUpgradeableFactory",
metadataUri: "ipfs://QmdqXhoJg9RfDDURHxtHKDprh3VvyWEwZWVtQvnvXMannF",
bytecodeUri: "ipfs://QmS63fhpjFFSzGXhM9deRSVaqWvEHEN9gcDkwNjiLr5oiV/1",
},
"non-upgradeable": {
name: "RouterImmutableFactory",
metadataUri: "ipfs://QmPMmcxK7RwQfcRwS8kmFU2hLWRLWpgcsESeXeFHM8W3Wp",
bytecodeUri: "ipfs://QmS63fhpjFFSzGXhM9deRSVaqWvEHEN9gcDkwNjiLr5oiV/0",
},
"thirdweb-router": {
name: "TWRouterFactory",
metadataUri: "ipfs://QmbrV9NUBZAXqoSHpdTzxsZjtubdqumgt6WTMLV8RW3tkV",
bytecodeUri: "ipfs://QmYjMfB1uhnnsdz6qmmc3bBAv8jmnniCkjXpDU6jGN8H5s/1",
}
}
+1 -2
View File
@@ -40,8 +40,7 @@ export class BrownieBuilder extends BaseBuilder {
const contractJsonFile = readFileSync(file, "utf-8"); const contractJsonFile = readFileSync(file, "utf-8");
const contractInfo = JSON.parse(contractJsonFile); const contractInfo = JSON.parse(contractJsonFile);
const abi = contractInfo.abi; const { abi, bytecode } = contractInfo;
const bytecode = contractInfo.bytecode;
for (const input of abi) { for (const input of abi) {
if (this.isThirdwebContract(input)) { if (this.isThirdwebContract(input)) {
+1 -1
View File
@@ -150,7 +150,7 @@ export class FoundryBuilder extends BaseBuilder {
) { ) {
// replace the abi with the actual abi // replace the abi with the actual abi
parsedMetadata.output.abi = abi; parsedMetadata.output.abi = abi;
// need to re-add libraries if not present since forge stripts it out // need to re-add libraries if not present since forge strips it out
if (!parsedMetadata.settings.libraries) { if (!parsedMetadata.settings.libraries) {
parsedMetadata.settings.libraries = {}; parsedMetadata.settings.libraries = {};
} }
+1 -2
View File
@@ -97,8 +97,7 @@ export class HardhatBuilder extends BaseBuilder {
const bytecode = info.evm.bytecode.object; const bytecode = info.evm.bytecode.object;
const deployedBytecode = info.evm.deployedBytecode.object; const deployedBytecode = info.evm.deployedBytecode.object;
const metadata = info.metadata; const { metadata, abi } = info;
const abi = info.abi;
const meta = JSON.parse(metadata); const meta = JSON.parse(metadata);
const sources = Object.keys(meta.sources) const sources = Object.keys(meta.sources)
+1 -1
View File
@@ -70,7 +70,7 @@ export class SolcBuilder extends BaseBuilder {
} }
// write them out to artifacts dir // write them out to artifacts dir
// TODO technically we *could* just return them straight here, we have them in memory anywa? // TODO technically we *could* just return them straight here, we have them in memory anyway?
Object.keys(output.contracts) Object.keys(output.contracts)
.filter((contractName) => contractName in sources) .filter((contractName) => contractName in sources)
.forEach((contractName) => { .forEach((contractName) => {
+6 -11
View File
@@ -36,14 +36,12 @@ export class TruffleBuilder extends BaseBuilder {
logger.debug("Processing:", file.replace(buildPath, "")); logger.debug("Processing:", file.replace(buildPath, ""));
const contractJsonFile = readFileSync(file, "utf-8"); const contractJsonFile = readFileSync(file, "utf-8");
const contractInfo = JSON.parse(contractJsonFile); const contractInfo = JSON.parse(contractJsonFile);
const contractName = contractInfo.contractName; const { contractName, metadata, bytecode, deployedBytecode } =
const metadata = contractInfo.metadata; contractInfo;
const bytecode = contractInfo.bytecode; const meta = JSON.parse(metadata);
const deployedBytecode = contractInfo.deployedBytecode; const abi = meta.output.abi;
const parsedMetadata = JSON.parse(metadata);
const abi = parsedMetadata.output.abi;
const target = parsedMetadata.settings.compilationTarget; const target = meta.settings.compilationTarget;
if ( if (
Object.keys(target).length === 0 || Object.keys(target).length === 0 ||
Object.keys(target)[0].includes("@") Object.keys(target)[0].includes("@")
@@ -53,7 +51,6 @@ export class TruffleBuilder extends BaseBuilder {
continue; continue;
} }
const meta = JSON.parse(metadata);
const sources = Object.keys(meta.sources) const sources = Object.keys(meta.sources)
.map((path) => { .map((path) => {
path = path.replace("project:/", ""); path = path.replace("project:/", "");
@@ -73,9 +70,7 @@ export class TruffleBuilder extends BaseBuilder {
}) })
.filter((path) => path !== undefined) as string[]; .filter((path) => path !== undefined) as string[];
const fileNames = Object.keys( const fileNames = Object.keys(meta?.settings?.compilationTarget || {});
parsedMetadata?.settings?.compilationTarget || {},
);
const fileName = fileNames.length > 0 ? fileNames[0] : ""; const fileName = fileNames.length > 0 ? fileNames[0] : "";
if (this.shouldProcessContract(abi, deployedBytecode, contractName)) { if (this.shouldProcessContract(abi, deployedBytecode, contractName)) {
+1 -1
View File
@@ -19,7 +19,7 @@ export default async function detect(
new HardhatDetector(), new HardhatDetector(),
new FoundryDetector(), new FoundryDetector(),
new TruffleDetector(), new TruffleDetector(),
// new BrownieDetector(), TODO brownie does not support outputing metadata yet // new BrownieDetector(), TODO brownie does not support outputting metadata yet
]; ];
const possibleProjectTypes = detectors const possibleProjectTypes = detectors
+3 -3
View File
@@ -5,14 +5,14 @@ export async function execute(
projectPath: string, projectPath: string,
options = { log: false, cwd: projectPath }, options = { log: false, cwd: projectPath },
): Promise<{ stdout: string; stderr: string }> { ): Promise<{ stdout: string; stderr: string }> {
return new Promise((done, failed) => { return new Promise((resolve, reject) => {
exec(command, { ...options }, (err, stdout, stderr) => { exec(command, { ...options }, (err, stdout, stderr) => {
if (err) { if (err) {
failed(err); reject(err);
return; return;
} }
done({ stdout, stderr }); resolve({ stdout, stderr });
}); });
}); });
} }
+13
View File
@@ -1,5 +1,6 @@
import { ContractPayload } from "../interfaces/ContractPayload"; import { ContractPayload } from "../interfaces/ContractPayload";
import chalk from "chalk"; import chalk from "chalk";
import prompts from "prompts";
const { MultiSelect } = require("enquirer"); const { MultiSelect } = require("enquirer");
@@ -34,3 +35,15 @@ export function createContractsPrompt(
}, },
}); });
} }
export async function createRouterPrompt(
choices: { title: string; value: string }[],
message: string,
) {
return await prompts({
type: "select",
name: "routerType",
message: message,
choices: choices,
});
}
@@ -0,0 +1,24 @@
import { BytesLike } from "ethers";
export interface ExtensionMetadata {
name: string;
metadataURI: string;
implementation: string;
}
export interface ExtensionFunction {
functionSelector: BytesLike;
functionSignature: string;
}
export interface Extension {
metadata: ExtensionMetadata;
functions: ExtensionFunction[];
}
export interface ExtensionDeployArgs {
name: string;
amount: number;
salt: string;
bytecode: string;
}
+28 -18
View File
@@ -19,6 +19,7 @@ let framework: string = "";
let language: string = ""; let language: string = "";
let baseContract: string = ""; let baseContract: string = "";
let chain: string = ""; let chain: string = "";
let createExtension: boolean = false;
/* let createType: string = "app"; */ /* let createType: string = "app"; */
export async function twCreate( export async function twCreate(
@@ -38,13 +39,14 @@ export async function twCreate(
projectType = "app"; projectType = "app";
} else if (pType === "contract" || options.contract) { } else if (pType === "contract" || options.contract) {
projectType = "contract"; projectType = "contract";
} else if (pType === "extension" || options.extension) {
projectType = "extension";
} }
if (projectType === "app") { if (projectType === "app") {
if (options.typescript) { if (options.typescript) {
language = "typescript"; language = "typescript";
} }
if (options.javascript) { if (options.javascript) {
language = "javascript"; language = "javascript";
} }
@@ -52,23 +54,18 @@ export async function twCreate(
if (options.next) { if (options.next) {
framework = "next"; framework = "next";
} }
if (options.cra) { if (options.cra) {
framework = "cra"; framework = "cra";
} }
if (options.vite) { if (options.vite) {
framework = "vite"; framework = "vite";
} }
if (options.node) { if (options.node) {
framework = "node"; framework = "node";
} }
if (options.express) { if (options.express) {
framework = "express"; framework = "express";
} }
if (options.reactNative) { if (options.reactNative) {
framework = "react-native"; framework = "react-native";
} }
@@ -76,7 +73,6 @@ export async function twCreate(
if (options.solana) { if (options.solana) {
chain = "solana"; chain = "solana";
} }
if (options.evm) { if (options.evm) {
chain = "evm"; chain = "evm";
} }
@@ -86,7 +82,6 @@ export async function twCreate(
if (options.forge) { if (options.forge) {
framework = "forge"; framework = "forge";
} }
if (options.hardhat) { if (options.hardhat) {
framework = "hardhat"; framework = "hardhat";
} }
@@ -104,6 +99,7 @@ export async function twCreate(
choices: [ choices: [
{ title: "App", value: "app" }, { title: "App", value: "app" },
{ title: "Contract", value: "contract" }, { title: "Contract", value: "contract" },
{ title: "Dynamic Contract Extension", value: "extension" },
], ],
}); });
@@ -116,9 +112,20 @@ export async function twCreate(
projectType = "app"; projectType = "app";
} }
if (projectType === "extension") {
createExtension = true;
if (options.forge) {
framework = "forge";
}
if (options.hardhat) {
framework = "hardhat";
}
}
// Whether to only create a new contract without the project // Whether to only create a new contract without the project
let onlyContract = false; let onlyContract = false;
if (projectType === "contract") { if (projectType === "contract" || projectType === "extension") {
const resolvedProjectPath = path.resolve(projectPath); const resolvedProjectPath = path.resolve(projectPath);
const contractProjectType = await detect(resolvedProjectPath, {}); const contractProjectType = await detect(resolvedProjectPath, {});
@@ -154,7 +161,9 @@ export async function twCreate(
if (!onlyContract) { if (!onlyContract) {
if (!projectPath) { if (!projectPath) {
const defaultName = const defaultName =
projectType === "contract" ? "thirdweb-contracts" : "thirdweb-app"; projectType === "contract" || projectType === "extension"
? "thirdweb-contracts"
: "thirdweb-app";
const res = await prompts({ const res = await prompts({
type: "text", type: "text",
name: "path", name: "path",
@@ -165,10 +174,10 @@ export async function twCreate(
const validation = validateNpmName( const validation = validateNpmName(
path.basename(path.resolve(name.toLowerCase())), path.basename(path.resolve(name.toLowerCase())),
); );
if (validation.valid) { return (
return true; validation.valid ||
} "Invalid project name: " + validation.problems?.[0]
return "Invalid project name: " + validation.problems?.[0]; );
}, },
}); });
@@ -258,7 +267,7 @@ export async function twCreate(
} }
if ( if (
projectType === "contract" && (projectType === "contract" || projectType === "extension") &&
framework !== "forge" && framework !== "forge" &&
framework !== "hardhat" framework !== "hardhat"
) { ) {
@@ -289,7 +298,7 @@ export async function twCreate(
} }
} }
if (projectType === "contract") { if (projectType === "contract" || projectType === "extension") {
// Select contract name // Select contract name
if (!contractName) { if (!contractName) {
const defaultName = "MyContract"; const defaultName = "MyContract";
@@ -329,7 +338,7 @@ export async function twCreate(
} }
// Select base contract // Select base contract
if (projectType === "contract" && !baseContract) { if (projectType === "contract" && !baseContract && !createExtension) {
let standard = "none"; let standard = "none";
const standardPrompt = await prompts({ const standardPrompt = await prompts({
type: "select", type: "select",
@@ -424,7 +433,7 @@ export async function twCreate(
: getPkgManager(); : getPkgManager();
const template = const template =
typeof options.template === "string" && options.template.trim(); typeof options.template === "string" ? options.template.trim() : undefined;
try { try {
if (projectType === "app") { if (projectType === "app") {
await createApp({ await createApp({
@@ -443,6 +452,7 @@ export async function twCreate(
contractName, contractName,
baseContract, baseContract,
onlyContract, onlyContract,
createExtension,
}); });
} }
} catch (reason) { } catch (reason) {
@@ -1,5 +1,6 @@
import { hasBaseContract, readBaseContract } from "./base-contracts"; import { hasBaseContract, readBaseContract } from "./base-contracts";
import { DownloadError } from "./create-app"; import { DownloadError } from "./create-app";
import { readExtensionBoilerPlate } from "./extension-contract-boilerplate";
import { PackageManager } from "./get-pkg-manager"; import { PackageManager } from "./get-pkg-manager";
import { tryGitInit } from "./git"; import { tryGitInit } from "./git";
import { hasForge } from "./has-forge"; import { hasForge } from "./has-forge";
@@ -23,6 +24,15 @@ interface ICreateContractProject {
framework?: string; framework?: string;
baseContract?: string; baseContract?: string;
onlyContract: boolean; onlyContract: boolean;
createExtension: boolean;
}
function isErrorLike(err: unknown): err is { message: string } {
return (
typeof err === "object" &&
err !== null &&
typeof (err as { message?: unknown }).message === "string"
);
} }
export async function createContractProject({ export async function createContractProject({
@@ -32,6 +42,7 @@ export async function createContractProject({
contractName, contractName,
baseContract, baseContract,
onlyContract, onlyContract,
createExtension,
}: ICreateContractProject) { }: ICreateContractProject) {
// Check that the selected base contract is valid // Check that the selected base contract is valid
if (baseContract) { if (baseContract) {
@@ -70,7 +81,8 @@ export async function createContractProject({
} }
// Clean the contract name // Clean the contract name
contractName = contractName.replace(/\.sol$/, "") + ".sol"; const contractObjectName = contractName.replace(/\.sol$/, "");
contractName = contractObjectName + ".sol";
const useYarn = packageManager === "yarn"; const useYarn = packageManager === "yarn";
@@ -99,6 +111,23 @@ export async function createContractProject({
`${chalk.green("Success!")} Created ${contractName} at ${contractPath}`, `${chalk.green("Success!")} Created ${contractName} at ${contractPath}`,
); );
} }
if (!baseContract && createExtension) {
const extensionBoilerplate = readExtensionBoilerPlate(contractObjectName);
// Set the contents of the Contract.sol file to the extension contract storage library boilerplate
let contractFile = "";
contractFile = path.join(root, contractName);
// Write the extension storage library to the MyContract.sol file
await writeFile(contractFile, extensionBoilerplate);
console.log(
`${chalk.green(
"Success!",
)} Created your ${contractName} extension at ${contractPath}`,
);
}
} else { } else {
// Otherwise, create a new contracts project // Otherwise, create a new contracts project
const projectName = path.basename(root); const projectName = path.basename(root);
@@ -118,14 +147,6 @@ export async function createContractProject({
process.chdir(root); process.chdir(root);
function isErrorLike(err: unknown): err is { message: string } {
return (
typeof err === "object" &&
err !== null &&
typeof (err as { message?: unknown }).message === "string"
);
}
try { try {
console.log(`Downloading files. This might take a moment.`); console.log(`Downloading files. This might take a moment.`);
@@ -164,6 +185,26 @@ export async function createContractProject({
// Write the base contract to the new file // Write the base contract to the new file
await writeFile(contractFile, baseContractText); await writeFile(contractFile, baseContractText);
} }
if (!baseContract && createExtension) {
const extensionBoilerplate =
readExtensionBoilerPlate(contractObjectName);
// Set the contents of the Contract.sol file to the extension contract storage library boilerplate
let contractFile = "";
contractFile = path.join(root, contractName);
if (framework === "hardhat") {
fs.unlinkSync(path.join(root, "contracts", "Contract.sol"));
contractFile = path.join(root, "contracts", contractName);
}
if (framework === "forge") {
fs.unlinkSync(path.join(root, "src", "Contract.sol"));
contractFile = path.join(root, "src", contractName);
}
// Write the extension storage library to the MyContract.sol file
await writeFile(contractFile, extensionBoilerplate);
}
} catch (reason) { } catch (reason) {
throw new DownloadError( throw new DownloadError(
isErrorLike(reason) ? reason.message : String(reason), isErrorLike(reason) ? reason.message : String(reason),
@@ -0,0 +1,58 @@
// Import the extension-contract storage boilerplate
export function readExtensionBoilerPlate(name: string): string {
const snakeCaseName = camelToSnakeCase(name).toUpperCase();
const dotCaseName = camelToDotCase(name);
const boilerplate = `// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
library ${name}Storage {
bytes32 public constant ${snakeCaseName}_STORAGE_POSITION = keccak256("${dotCaseName}.storage");
// Define your contract's state inside the Data struct.
struct Data {
// Example: a uint called "number"
uint256 number;
}
/**
* Access your state variables using the following pattern (example):
* ${name}Storage.Data storage data = ${name}Storage.getStorage();
**/
function getStorage() internal pure returns (Data storage data) {
bytes32 position = ${snakeCaseName}_STORAGE_POSITION;
assembly {
data.slot := position
}
}
}
contract ${name} {
function readContractState() external view returns (uint256) {
${name}Storage.Data storage data = ${name}Storage.getStorage();
return data.number;
}
function writeContractState(uint256 x) external {
${name}Storage.Data storage data = ${name}Storage.getStorage();
data.number = x;
}
}`;
return boilerplate;
}
function camelToSymbolCase(text: string, symbol: string): string {
return text
.replace(/(.)([A-Z][a-z]+)/, `$1${symbol}$2`)
.replace(/([a-z0-9])([A-Z])/, `$1${symbol}$2`)
.toLowerCase();
}
function camelToSnakeCase(text: string): string {
return camelToSymbolCase(text, "_");
}
function camelToDotCase(text: string): string {
return camelToSymbolCase(text, ".");
}
+3 -8
View File
@@ -1,14 +1,9 @@
import { exec } from "child_process"; import { exec } from "child_process";
export async function hasForge() { export async function hasForge() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars return await new Promise((resolve) => {
return await new Promise((resolve, reject) => { exec("forge --version", (error) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars resolve(!error);
exec("forge --version", (error, stdout, stderr) => {
if (error) {
resolve(false);
}
resolve(true);
}); });
}); });
} }
+2 -4
View File
@@ -3,7 +3,6 @@ import ViteDetector from "../core/detection/vite";
import YarnDetector from "../core/detection/yarn"; import YarnDetector from "../core/detection/yarn";
import { runCommand } from "../create/helpers/run-command"; import { runCommand } from "../create/helpers/run-command";
import { upload } from "../storage/command"; import { upload } from "../storage/command";
import { DEFAULT_IPFS_GATEWAY } from "@thirdweb-dev/sdk";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
export async function deployApp(distPath = "dist", projectPath = ".") { export async function deployApp(distPath = "dist", projectPath = ".") {
@@ -33,9 +32,8 @@ export async function deployApp(distPath = "dist", projectPath = ".") {
} }
try { try {
let url = await upload(storage, distPath); const uri = await upload(storage, distPath);
url = url.replace("ipfs://", DEFAULT_IPFS_GATEWAY); return `https://thirdweb.com/app/deploy/${uri.replace("ipfs://", "")}`;
return `${url}/index.html`;
} catch (err) { } catch (err) {
console.error("Can't upload project"); console.error("Can't upload project");
return Promise.reject("Can't upload project"); return Promise.reject("Can't upload project");
@@ -13,9 +13,7 @@ export async function findPackageInstallation(): Promise<
const isLocal = await isInstalledLocally(); const isLocal = await isInstalledLocally();
if (isLocal) { if (isLocal) {
const packageManager = await import("detect-package-manager").then( const packageManager = await import("detect-package-manager").then(
({ detect }) => { ({ detect }) => detect(),
return detect();
},
); );
return { packageManager, isGlobal: false }; return { packageManager, isGlobal: false };
@@ -29,10 +29,8 @@ export default function generateDashboardUrl(
const foundMapping = mapping[name as keyof typeof mapping]; const foundMapping = mapping[name as keyof typeof mapping];
if (!foundMapping) { return foundMapping
return undefined; ? `https://thirdweb.com/dashboard/${foundMapping}`
} : undefined;
return `https://thirdweb.com/thirdweb.eth/${foundMapping}`;
} }
} }
+1 -1
View File
@@ -63,7 +63,7 @@ export async function upload(
"Uploading file to IPFS. This may take a while depending on file sizes.", "Uploading file to IPFS. This may take a while depending on file sizes.",
); );
uri = await storage.upload(file, { uploadWithoutDirectory: true }); uri = await storage.upload(file, { uploadWithoutDirectory: true });
spin.succeed("Succesfully uploaded file to IPFS."); spin.succeed("Successfully uploaded file to IPFS.");
} else { } else {
return Promise.reject("Invalid path provided"); return Promise.reject("Invalid path provided");
} }
+1 -1
View File
@@ -8,7 +8,7 @@
"@typescript-eslint/parser": "^5.33.0", "@typescript-eslint/parser": "^5.33.0",
"eslint-config-next": "12.3.1", "eslint-config-next": "12.3.1",
"eslint-config-prettier": "^8.3.0", "eslint-config-prettier": "^8.3.0",
"eslint-config-turbo": "latest", "eslint-config-turbo": "^0.0.8",
"eslint-plugin-react": "^7.28.0" "eslint-plugin-react": "^7.28.0"
}, },
"publishConfig": { "publishConfig": {
-3
View File
@@ -2,9 +2,6 @@ node_modules/
/test-results/ /test-results/
/playwright-report/ /playwright-report/
/playwright/.cache/ /playwright/.cache/
/test-results/
/playwright-report/
/playwright/.cache/
etc/ etc/
temp/ temp/
temp-evm/ temp-evm/
+32
View File
@@ -1,5 +1,37 @@
# @thirdweb-dev/react-core # @thirdweb-dev/react-core
## 3.10.1
### Patch Changes
- [#684](https://github.com/thirdweb-dev/js/pull/684) [`9efeba38`](https://github.com/thirdweb-dev/js/commit/9efeba38f06783b78e2c947ad878350173f4e07a) Thanks [@adam-maj](https://github.com/adam-maj)! - Update auth hooks to include credentials on login
## 3.10.0
### Patch Changes
- [#670](https://github.com/thirdweb-dev/js/pull/670) [`6ae39277`](https://github.com/thirdweb-dev/js/commit/6ae39277a1d2ea507cedcde7ae62439758e4d6e0) Thanks [@jnsdls](https://github.com/jnsdls)! - improve signer resilience
- [#668](https://github.com/thirdweb-dev/js/pull/668) [`8f46a2ee`](https://github.com/thirdweb-dev/js/commit/8f46a2eef59d2b21b68e38338ed2b3a820421501) Thanks [@jnsdls](https://github.com/jnsdls)! - FIX signer being updated
- [#650](https://github.com/thirdweb-dev/js/pull/650) [`8d5b418e`](https://github.com/thirdweb-dev/js/commit/8d5b418e78fcf692f72aed5fe49358e40720d80c) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Fix invariant for appURI hooks
- [#665](https://github.com/thirdweb-dev/js/pull/665) [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75) Thanks [@shift4id](https://github.com/shift4id)! - Fix spelling throughout all packages
- [#672](https://github.com/thirdweb-dev/js/pull/672) [`2676fc01`](https://github.com/thirdweb-dev/js/commit/2676fc01f4d8eabc90e71fad1f14b4b29806d2bd) Thanks [@jnsdls](https://github.com/jnsdls)! - back to use-memo
- [#662](https://github.com/thirdweb-dev/js/pull/662) [`3740a0bf`](https://github.com/thirdweb-dev/js/commit/3740a0bf5db1301dbd93a97ab4c9343429a4e12d) Thanks [@furqanrydhan](https://github.com/furqanrydhan)! - switch appuri -> app
- [#626](https://github.com/thirdweb-dev/js/pull/626) [`91f5a2fd`](https://github.com/thirdweb-dev/js/commit/91f5a2fd5cb2f5aed6498defdb1feeabb283db6c) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Improve comments and examples in the documentation
- [#625](https://github.com/thirdweb-dev/js/pull/625) [`23cd88ec`](https://github.com/thirdweb-dev/js/commit/23cd88ec3a2af86eafeac258fdc8c5b4ce3196f2) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add appURI get/set
- [#660](https://github.com/thirdweb-dev/js/pull/660) [`87a101ad`](https://github.com/thirdweb-dev/js/commit/87a101ad56430e793c9f22b583fea204dfed0554) Thanks [@MananTank](https://github.com/MananTank)! - Fix Wrong Currency symbol in non-default chains
- Updated dependencies [[`7832041c`](https://github.com/thirdweb-dev/js/commit/7832041c0fb25852489c73453c2b26e844d94582), [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75), [`85250cf7`](https://github.com/thirdweb-dev/js/commit/85250cf71190092b61023d56d1e786d395a008a6), [`e33bd2a8`](https://github.com/thirdweb-dev/js/commit/e33bd2a856bbc2e2f6b0c90b46be5166281875ae), [`4355518a`](https://github.com/thirdweb-dev/js/commit/4355518afea68cd8026d3ab8a0144c15d66b9e24)]:
- @thirdweb-dev/chains@0.1.6
- @thirdweb-dev/auth@3.0.7
## 3.9.5 ## 3.9.5
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/react-core", "name": "@thirdweb-dev/react-core",
"version": "3.9.5", "version": "3.10.1",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-core", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-core",
"author": "thirdweb eng <[email protected]>", "author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -1,7 +1,7 @@
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
/** /**
* Makes a parameter required to be passed, but still allowes it to be null or undefined. * Makes a parameter required to be passed, but still allows it to be null or undefined.
* *
* @beta * @beta
*/ */
@@ -0,0 +1,94 @@
import {
RequiredParam,
requiredParamInvariant,
} from "../../../core/query-utils/required-param";
import { useSDKChainId } from "../../providers/thirdweb-sdk-provider";
import {
cacheKeys,
invalidateContractAndBalances,
} from "../../utils/cache-keys";
import { useQueryWithNetwork } from "../query-utils/useQueryWithNetwork";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ValidContractInstance } from "@thirdweb-dev/sdk";
import invariant from "tiny-invariant";
/**
* Get App URI
*
* @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
* @twfeature AppURI
* @beta
*/
export function useAppURI<TContract extends ValidContractInstance>(
contract: RequiredParam<TContract>,
) {
return useQueryWithNetwork<string>(
cacheKeys.contract.app.get(contract?.getAddress()),
async () => {
requiredParamInvariant(contract, "Contract is required");
invariant(contract.app, "Contract does not support app");
return await contract.app.get();
},
{
enabled: !!contract,
},
);
}
/**
* Set App URI
*
* @example
* ```jsx
* const Component = () => {
* const {
* mutate: useSetAppURI,
* isLoading,
* error,
* } = useSetAppURI(contract);
*
* if (error) {
* console.error("failed to update appURI", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => useSetAppURI({ uri })}
* >
* Update App URI
* </button>
* );
* };
* ```
* @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
* @beta
*/
export function useSetAppURI(contract: RequiredParam<ValidContractInstance>) {
const queryClient = useQueryClient();
const contractAddress = contract?.getAddress();
const activeChainId = useSDKChainId();
return useMutation(
(params: { uri: string }) => {
requiredParamInvariant(contract, "Contract is required");
invariant(contract.app, "Contract does not support app");
return contract.app.set(params.uri);
},
{
onSettled: () =>
invalidateContractAndBalances(
queryClient,
contractAddress,
activeChainId,
),
},
);
}
@@ -49,25 +49,17 @@ export type SetClaimConditionsParams = {
/** **********************/ /** **********************/
/** /**
* Use this to get the active claim condition for ERC20, ERC721 or ERC1155 based contracts. They need to extend the `claimCondition` extension for this hook to work. * Get the active claim condition
* *
* @example * @example
* ```javascript * ```javascript
* const { data: activeClaimCondition, isLoading, error } = useActiveClaimCondition(<YourERC20ContractInstance>); * const { data: activeClaimCondition, isLoading, error } = useActiveClaimCondition(contract);
* ```
* @example
* ```javascript
* const { data: activeClaimCondition, isLoading, error } = useActiveClaimCondition(<YourERC721ContractInstance>);
* ```
* @example
* ```javascript
* const { data: activeClaimCondition, isLoading, error } = useActiveClaimCondition(<YourERC1155ContractInstance>, <tokenId>);
* ``` * ```
* *
* @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension. * @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) * @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 * @returns a response object with the currently active claim condition
* @twfeature ERC721ClaimableWithConditions | ERC1155ClaimableWithConditions | ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
* @beta * @beta
*/ */
export function useActiveClaimCondition( export function useActiveClaimCondition(
@@ -110,19 +102,11 @@ export function useActiveClaimCondition(
} }
/** /**
* Use this to get the claimer proofs for an adddress for ERC20, ERC721 or ERC1155 based contracts. They need to extend the `claimCondition` extension for this hook to work. * Get claimer proofs
* *
* @example * @example
* ```javascript * ```javascript
* const { data: claimerProofs, isLoading, error } = useClaimerProofs(<YourERC20ContractInstance>); * const { data: claimerProofs, isLoading, error } = useClaimerProofs(contract);
* ```
* @example
* ```javascript
* const { data: claimerProofs, isLoading, error } = useClaimerProofs(<YourERC721ContractInstance>);
* ```
* @example
* ```javascript
* const { data: claimerProofs, isLoading, error } = useClaimerProofs(<YourERC1155ContractInstance>, <tokenId>);
* ``` * ```
* *
* @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension. * @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension.
@@ -130,7 +114,7 @@ export function useActiveClaimCondition(
* @param tokenId - the id of the token to fetch the claimer proofs for (if the contract is an ERC1155 contract) * @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 * @param claimConditionId - optional the claim condition id to get the proofs for
* @returns a response object with the snapshot for the provided address * @returns a response object with the snapshot for the provided address
* @twfeature ERC721ClaimableWithConditions | ERC1155ClaimableWithConditions | ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
* @beta * @beta
*/ */
export function useClaimerProofs( export function useClaimerProofs(
@@ -183,25 +167,17 @@ export function useClaimerProofs(
} }
/** /**
* Use this to get all claim conditions for ERC20, ERC721 or ERC1155 based contracts. They need to extend the `claimCondition` extension for this hook to work. * Get all claim conditions
* *
* @example * @example
* ```javascript * ```javascript
* const { data: claimConditions, isLoading, error } = useClaimConditions(<YourERC20ContractInstance>); * const { data: claimConditions, isLoading, error } = useClaimConditions(contract);
* ```
* @example
* ```javascript
* const { data: claimConditions, isLoading, error } = useClaimConditions(<YourERC721ContractInstance>);
* ```
* @example
* ```javascript
* const { data: claimConditions, isLoading, error } = useClaimConditions(<YourERC1155ContractInstance>, <tokenId>);
* ``` * ```
* *
* @param contract - an instance of a contract that extends the ERC721, ERC1155 or ERC20 spec and implements the `claimConditions` extension. * @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) * @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 * @returns a response object with the list of claim conditions
* @twfeature ERC721ClaimableWithConditions | ERC1155ClaimableWithConditions | ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
* @beta * @beta
*/ */
export function useClaimConditions( export function useClaimConditions(
@@ -244,25 +220,18 @@ export function useClaimConditions(
} }
/** /**
* Use this to check for reasons that prevent claiming for either ERC20, ERC721 or ERC1155 based contracts. They need to extend the `claimCondition` extension for this hook to work. * Get the reasons why a specific wallet can't claim
*
* @example * @example
* ```javascript * ```javascript
* const { data: activeClaimCondition, isLoading, error } = useClaimIneligibilityReasons(<YourERC20ContractInstance>, { walletAddress: <walletAddress> }); * const { data: claimIneligibilityReasons, isLoading, error } = useClaimIneligibilityReasons(contract, { walletAddress: "{{wallet_address}}" });
* ```
* @example
* ```javascript
* const { data: claimIneligibilityReasons, isLoading, error } = useClaimIneligibilityReasons(<YourERC721ContractInstance>, { quantity: <quantity>, walletAddress: <walletAddress> });
* ```
* @example
* ```javascript
* const { data: claimIneligibilityReasons, isLoading, error } = useClaimIneligibilityReasons(<YourERC1155ContractInstance>, { quantity: <quantity>, walletAddress: <walletAddress> }, <tokenId>);
* ``` * ```
* *
* @param contract - an instance of a contract that extends the ERC20, ERC721 or ERC1155 spec and implements the `claimConditions` extension. * @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 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) * @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 resons for the claim ineligibility * @returns a response object with the reasons for the claim ineligibility
* @twfeature ERC721ClaimableWithConditions | ERC1155ClaimableWithConditions | ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
* @beta * @beta
*/ */
export function useClaimIneligibilityReasons( export function useClaimIneligibilityReasons(
@@ -320,12 +289,18 @@ export function useClaimIneligibilityReasons(
} }
/** /**
* Use this to check the claim condition for a given wallet address (including checking for overrides that may exist for that given wallet address). * Get the active claim condition for a specific wallet
*
* @example
* ```javascript
* const { data: activeClaimConditionForWallet, isLoading, error } = useActiveClaimConditionForWallet(contract, "{{wallet_address}}");
* ```
* *
* @param contract - an instance of a contract that extends the ERC20, ERC721 or ERC1155 spec and implements the `claimConditions` extension. * @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 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) * @param tokenId - the id of the token to fetch the claim conditions for (if the contract is an ERC1155 contract)
* @returns the active claim conditon for the wallet address or null if there is no active claim condition * @returns the active claim conditon 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
* *
* @beta * @beta
*/ */
@@ -454,12 +429,12 @@ export function useActiveClaimConditionForWallet(
/** **********************/ /** **********************/
/** /**
* Use this to set claim conditions on your {@link DropContract} * Set claim conditions
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: setClaimConditions, * mutate: setClaimConditions,
* isLoading, * isLoading,
@@ -473,7 +448,7 @@ export function useActiveClaimConditionForWallet(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => setClaimConditions({ phases: [{ price: 2, maxQuantity: 100 }] })} * onClick={() => setClaimConditions({ phases: [{ price: 2, maxClaimableSupply: 100 }] })}
* > * >
* Set Claim Conditions! * Set Claim Conditions!
* </button> * </button>
@@ -483,7 +458,7 @@ export function useActiveClaimConditionForWallet(
* *
* @param contract - an instance of a {@link DropContract} * @param contract - an instance of a {@link DropContract}
* @returns a mutation object that can be used to set claim conditions * @returns a mutation object that can be used to set claim conditions
* @twfeature ERC721ClaimableWithConditions | ERC1155ClaimableWithConditions | ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
* @beta * @beta
*/ */
export function useSetClaimConditions( export function useSetClaimConditions(
@@ -528,12 +503,12 @@ export function useSetClaimConditions(
} }
/** /**
* Use this to reset claim conditions on your {@link DropContract} * Reset claim conditions
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: resetClaimConditions, * mutate: resetClaimConditions,
* isLoading, * isLoading,
@@ -557,7 +532,7 @@ export function useSetClaimConditions(
* *
* @param contract - an instance of a {@link DropContract} * @param contract - an instance of a {@link DropContract}
* @returns a mutation object that can be used to reset claim conditions * @returns a mutation object that can be used to reset claim conditions
* @twfeature ERC721ClaimableWithConditions | ERC1155ClaimableWithConditions | ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1 | ERC721ClaimPhasesV2 | ERC721ClaimPhasesV1 | ERC721ClaimConditionsV2 | ERC721ClaimConditionsV1 | ERC1155ClaimPhasesV2 | ERC1155ClaimPhasesV1 | ERC1155ClaimConditionsV2 | ERC1155ClaimConditionsV1
* @beta * @beta
*/ */
export function useResetClaimConditions( export function useResetClaimConditions(
@@ -19,10 +19,11 @@ import invariant from "tiny-invariant";
// primary sales // primary sales
/** /**
* Get the primary sale recipient
* *
* @example * @example
* ```jsx * ```jsx
* const { data: recipient, isLoading, error } = usePrimarySalesRecipient(SmartContract); * const { data: primarySaleRecipient, isLoading, error } = usePrimarySalesRecipient(contract);
* ``` * ```
* *
* Use this to get the primary sales recipient of your {@link SmartContract} * Use this to get the primary sales recipient of your {@link SmartContract}
@@ -50,16 +51,17 @@ export function usePrimarySaleRecipient(
} }
/** /**
* Use this to update the primary sales recipient of your {@link SmartContract} * Set the primary sale recipient
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: updatePrimarySalesRecipient, * mutate: updatePrimarySalesRecipient,
* isLoading, * isLoading,
* error, * error,
* } = useUpdatePrimarySaleRecipient(SmartContract); * } = useUpdatePrimarySaleRecipient(contract);
* *
* if (error) { * if (error) {
* console.error("failed to update recipient", error); * console.error("failed to update recipient", error);
@@ -68,7 +70,7 @@ export function usePrimarySaleRecipient(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => updatePrimarySalesRecipient({ newRecipient: "0x123" })} * onClick={() => updatePrimarySalesRecipient({ newRecipient: "{{wallet_address}}" })}
* > * >
* Update Recipient * Update Recipient
* </button> * </button>
@@ -107,16 +109,16 @@ export function useUpdatePrimarySaleRecipient(
); );
} }
// end prinary sales // end primary sales
// royalties // royalties
/** /**
* Use this to get the royalty settings of your {@link SmartContract} * Get the royalty recipient and fee
* *
* @example * @example
* ```jsx * ```jsx
* const { data: settings, isLoading, error } = useRoyaltySettings(SmartContract); * const { data: settings, isLoading, error } = useRoyaltySettings(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
@@ -143,16 +145,17 @@ export function useRoyaltySettings(
} }
/** /**
* Use this to update the royalty settings of your {@link SmartContract} * Set the royalty recipient and fee
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: updateRoyaltySettings, * mutate: updateRoyaltySettings,
* isLoading, * isLoading,
* error, * error,
* } = useUpdateRoyaltySettings(SmartContract); * } = useUpdateRoyaltySettings(contract);
* *
* if (error) { * if (error) {
* console.error("failed to update royalty settings", error); * console.error("failed to update royalty settings", error);
@@ -161,7 +164,7 @@ export function useRoyaltySettings(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => updateRoyaltySettings({ updatePayload: { fee_recipient: "0x123", seller_fee_basis_points: 5_00 } })} * onClick={() => updateRoyaltySettings({ updatePayload: { fee_recipient: "{{wallet_address}}", seller_fee_basis_points: 5_00 } })}
* > * >
* Update Royalty Settings * Update Royalty Settings
* </button> * </button>
@@ -208,11 +211,11 @@ export function useUpdateRoyaltySettings(
// platformFees // platformFees
/** /**
* Use this to get the platform fees settings of your {@link SmartContract} * Get the platform fee recipient and basis points
* *
* @example * @example
* ```jsx * ```jsx
* const { data: platformFees, isLoading, error } = usePlatformFees(SmartContract); * const { data: platformFees, isLoading, error } = usePlatformFees(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
@@ -239,16 +242,17 @@ export function usePlatformFees(
} }
/** /**
* Use this to update the platform fees settings of your {@link SmartContract} * Set the platform fee recipient and basis points
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: updatePlatformFees, * mutate: updatePlatformFees,
* isLoading, * isLoading,
* error, * error,
* } = useUpdatePlatformFees(SmartContract); * } = useUpdatePlatformFees(contract);
* *
* if (error) { * if (error) {
* console.error("failed to update platform fees", error); * console.error("failed to update platform fees", error);
@@ -257,7 +261,7 @@ export function usePlatformFees(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => updatePlatformFees({ updatePayload: { fee_recipient: "0x123", platform_fee_basis_points: 5_00 } })} * onClick={() => updatePlatformFees({ updatePayload: { fee_recipient: "{{wallet_address}}", platform_fee_basis_points: 5_00 } })}
* > * >
* Update Platform fees * Update Platform fees
* </button> * </button>
@@ -303,16 +307,15 @@ export function useUpdatePlatformFees(
// metadata // metadata
/** /**
* Use this to get the metadata of your {@link SmartContract} * Get the metadata of this contract
* *
* @example * @example
* ```jsx * ```jsx
* const { data: metadata, isLoading, error } = useMetadata(SmartContract); * const { data: metadata, isLoading, error } = useMetadata(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
* @returns a {@link CustomContractMetadata} object containing the metadata * @returns a {@link CustomContractMetadata} object containing the metadata
* @twfeature ContractMetadata
* @beta * @beta
*/ */
export function useMetadata(contract: RequiredParam<ValidContractInstance>) { export function useMetadata(contract: RequiredParam<ValidContractInstance>) {
@@ -332,15 +335,17 @@ export function useMetadata(contract: RequiredParam<ValidContractInstance>) {
} }
/** /**
* Use this to update the metadata of your {@link SmartContract} * Set the metadata of this contract
*
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: updateMetadata, * mutate: updateMetadata,
* isLoading, * isLoading,
* error, * error,
* } = useUpdateMetadata(SmartContract); * } = useUpdateMetadata(contract);
* *
* if (error) { * if (error) {
* console.error("failed to update metadata", error); * console.error("failed to update metadata", error);
@@ -349,16 +354,18 @@ export function useMetadata(contract: RequiredParam<ValidContractInstance>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => updateMetadata({ updatePayload: { name: "My Contract", description: "This is my contract" } })} * onClick={() => updateMetadata({
* name: "My Contract",
* description: "This is my contract"
* })}
* > * >
* Update Metadata * Update Contract Metadata
* </button> * </button>
* ); * );
* }; * };
* ``` * ```
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
* @returns a mutation object that can be used to update the metadata * @returns a mutation object that can be used to update the metadata
* @twfeature ContractMetadata
* @beta * @beta
*/ */
export function useUpdateMetadata( export function useUpdateMetadata(
@@ -273,11 +273,11 @@ export function useContract(
} }
/** /**
* Use this to get the contract metadata for a (built-in or custom) contract. * Get the metadata of this contract
* *
* @example * @example
* ```javascript * ```javascript
* const { data: contractMetadata, isLoading, error } = useContractMetadata(>); * const { data: contractMetadata, isLoading } = useContractMetadata(contract);
* ``` * ```
* *
* @param contract - the {@link ValidContractInstance} instance of the contract to get the metadata for * @param contract - the {@link ValidContractInstance} instance of the contract to get the metadata for
@@ -305,7 +305,37 @@ export function useContractMetadata<TContract extends ValidContractInstance>(
} }
/** /**
* @internal * Update the metadata of this contract
*
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const {
* mutate: updateContractMetadata,
* isLoading,
* error,
* } = useContractMetadataUpdate(contract);
*
* if (error) {
* console.error("failed to update contract metadata", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => updateContractMetadata({ name: "New name", description: "New description" })}
* >
* Update contract metadata
* </button>
* );
* };
* ```
*
* @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
* @twfeature ContractMetadata
* @beta
*/ */
export function useContractMetadataUpdate( export function useContractMetadataUpdate(
contract: RequiredParam<ValidContractInstance>, contract: RequiredParam<ValidContractInstance>,
@@ -337,11 +367,16 @@ export function useContractMetadataUpdate(
*/ */
/** /**
* Use this to query (and subscribe) to events or a specific event on a contract. * Get or subscribe to contract events
*
* @example
* ```javascript
* const { data: contractEvents, isLoading } = useContractEvents(contract);
* ```
* *
* @param contract - the {@link ValidContractInstance} instance of the contract to listen to events for * @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 eventName - the name of the event to query for (omit this or pass `undefined` to query for all events)
* @param options - options incldues the filters ({@link QueryAllEvents}) for the query as well as if you want to subscribe to real-time updates (default: true) * @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 * @returns a response object that includes the contract events
* @beta * @beta
*/ */
@@ -428,7 +463,7 @@ export function useContractEvents(
} }
/** /**
* Use this to get data from a contract read-function call. * Get data from a contract read-function call
* *
* @example * @example
* ```javascript * ```javascript
@@ -463,7 +498,7 @@ export function useContractRead(
} }
/** /**
* Use this to get a function to make a write call to your contract * Mke a write call to your contract
* *
* @example * @example
* ```javascript * ```javascript
+88 -12
View File
@@ -31,11 +31,11 @@ import invariant from "tiny-invariant";
/** **********************/ /** **********************/
/** /**
* Use this to get a list of *unclaimed* NFT tokens of your ERC721 Drop contract. * Get all unclaimed NFTs
* *
* @example * @example
* ```javascript * ```javascript
* const { data: unclaimedNfts, isLoading, error } = useUnclaimedNFTs(<YourERC721DropContractInstance>, { start: 0, count: 100 }); * const { data: unclaimedNfts, isLoading, error } = useUnclaimedNFTs(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a contract that extends the Erc721 spec (nft drop, custom contract that follows the Erc721 & drop spec) * @param contract - an instance of a contract that extends the Erc721 spec (nft drop, custom contract that follows the Erc721 & drop spec)
@@ -65,13 +65,13 @@ export function useUnclaimedNFTs(
} }
/** /**
* Use this to get a list of *claimed* (minted) NFT tokens of your ERC721 Drop contract. * Get all claimed NFTs
* *
* @remarks Equivalent to using {@link useNFTs}. * @remarks Equivalent to using {@link useNFTs}.
* *
* @example * @example
* ```javascript * ```javascript
* const { data: claimedNFTs, isLoading, error } = useClaimedNFTs(<YourERC721DropContractInstance>, { start: 0, count: 100 }); * const { data: claimedNFTs, isLoading, error } = useClaimedNFTs(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a {@link DropContract} * @param contract - an instance of a {@link DropContract}
@@ -124,7 +124,7 @@ export function useUnclaimedNFTSupply(contract: RequiredParam<DropContract>) {
} }
/** /**
* Get the total number of claimed NFTs
* *
* @param contract - an instance of a {@link DropContract} * @param contract - an instance of a {@link DropContract}
* @returns a response object that includes the number of NFTs that are claimed * @returns a response object that includes the number of NFTs that are claimed
@@ -147,6 +147,7 @@ export function useClaimedNFTSupply(contract: RequiredParam<DropContract>) {
} }
/** /**
* Get all unrevealed batches
* *
* @param contract - an instance of a {@link RevealableContract} * @param contract - an instance of a {@link RevealableContract}
* @returns a response object that gets the batches to still be revealed * @returns a response object that gets the batches to still be revealed
@@ -176,14 +177,14 @@ export function useBatchesToReveal<TContract extends RevealableContract>(
/** WRITE HOOKS **/ /** WRITE HOOKS **/
/** **********************/ /** **********************/
/** /**
* Use this to claim a NFT on your {@link DropContract} * Claim an NFT to a specific wallet
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: claimNft, * mutate: claimNFT,
* isLoading, * isLoading,
* error, * error,
* } = useClaimNFT(contract); * } = useClaimNFT(contract);
@@ -195,7 +196,7 @@ export function useBatchesToReveal<TContract extends RevealableContract>(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => claimNft({ to: "0x...", quantity: 1 })} * onClick={() => claimNFT({ to: "{{wallet_address}}", quantity: 1 })}
* > * >
* Claim NFT! * Claim NFT!
* </button> * </button>
@@ -264,7 +265,32 @@ export function useClaimNFT<TContract extends DropContract>(
} }
/** /**
* Use this to lazy mint a batch of NFTs on your {@link DropContract} * Lazy mint NFTs
*
* @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);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => lazyMint({ metadatas: [{ name: "My NFT!"}] })}
* >
* Lazy mint NFT!
* </button>
* );
* };
* ```
* *
* @param contract - an instance of a {@link NFTContract} with the drop extension * @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 * @param onProgress - an optional callback that will be called with the progress of the upload
@@ -311,7 +337,32 @@ export function useLazyMint<TContract extends DropContract>(
} }
/** /**
* Use this to lazy mint a batch of delayed reveal NFTs on your {@link DropContract} * Lazy mint NFTs with delayed reveal
*
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const {
* mutate: delayedRevealLazyMint,
* isLoading,
* error,
* } = useDelayedRevealLazyMint(contract);
*
* if (error) {
* console.error("failed to lazy mint NFT", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => delayedRevealLazyMint({ metadatas: [{ name: "My NFT!"}] })}
* >
* Delayed Reveal Lazy mint NFT!
* </button>
* );
* };
* ```
* *
* @param contract - an instance of a {@link DropContract} * @param contract - an instance of a {@link DropContract}
* @param onProgress - an optional callback that will be called with the progress of the upload * @param onProgress - an optional callback that will be called with the progress of the upload
@@ -367,7 +418,32 @@ export function useDelayedRevealLazyMint<TContract extends RevealableContract>(
} }
/** /**
* Use this to reveal a batch of delayed reveal NFTs on your {@link RevealableContract} * Reveal a batch of delayed reveal NFTs
*
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const {
* mutate: 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" })}
* >
* Reveal batch!
* </button>
* );
* };
* ```
* *
* @param contract - an instance of a {@link RevealableContract} * @param contract - an instance of a {@link RevealableContract}
* @returns a mutation object that can be used to reveal a batch of delayed reveal NFTs * @returns a mutation object that can be used to reveal a batch of delayed reveal NFTs
@@ -38,11 +38,12 @@ import invariant from "tiny-invariant";
/** **********************/ /** **********************/
/** /**
* Use this to get a specific listing from the marketplace. * Get a listing
* *
* @example * @example
* ```javascript * ```javascript
* const { data: listing, isLoading, error } = useListing(<YourMarketplaceContractInstance>, <listingId>); * const listingId = 0; // the listing id to check
* const { data: listing, isLoading, error } = useListing(contract, listingId);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
@@ -70,17 +71,18 @@ export function useListing(
} }
/** /**
* Use this to get a specific direct listing from the marketplace v3. * Get a direct listing
* *
* @example * @example
* ```javascript * ```javascript
* const { data: directListing, isLoading, error } = useListing(<YourMarketplaceV3ContractInstance>, <listingId>); * const listingId = 0; // the listing id to check
* const { data: directListing, isLoading, error } = useListing(contract, listingId);
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @param listingId - the listing id to check * @param listingId - the listing id to check
* @returns a response object that includes the desired direct listing * @returns a response object that includes the desired direct listing
* @internal * @twfeature DirectListings
*/ */
export function useDirectListing( export function useDirectListing(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -105,17 +107,18 @@ export function useDirectListing(
} }
/** /**
* Use this to get a specific english auction from the marketplace v3. * Get an english auction
* *
* @example * @example
* ```javascript * ```javascript
* const { data: englishAuction, isLoading, error } = useEnglishAuction(<YourMarketplaceV3ContractInstance>, <auctionId>); * const auctionId = 0; // the listing id to check
* const { data: englishAuction, isLoading, error } = useEnglishAuction(contract, auctionId);
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @param auctionId - the auction id to check * @param auctionId - the auction id to check
* @returns a response object that includes the desired english auction * @returns a response object that includes the desired english auction
* @internal * @twfeature EnglishAuctions
*/ */
export function useEnglishAuction( export function useEnglishAuction(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -140,11 +143,11 @@ export function useEnglishAuction(
} }
/** /**
* Use this to get a list all listings from your marketplace contract. * Get all listings
* *
* @example * @example
* ```javascript * ```javascript
* const { data: listings, isLoading, error } = useListings(<YourMarketplaceContractInstance>, { start: 0, count: 100 }); * const { data: listings, isLoading, error } = useListings(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
@@ -171,17 +174,17 @@ export function useListings(
} }
/** /**
* Use this to get a list all direct listings from your marketplace v3 contract. * Get all direct listings
* *
* @example * @example
* ```javascript * ```javascript
* const { data: directListings, isLoading, error } = useDirectListings(<YourMarketplaceV3ContractInstance>, { start: 0, count: 100 }); * const { data: directListings, isLoading, error } = useDirectListings(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @param filter - filter to pass to the query for the sake of pagination & filtering * @param filter - filter to pass to the query for the sake of pagination & filtering
* @returns a response object that includes an array of direct listings * @returns a response object that includes an array of direct listings
* @internal * @twfeature DirectListings
*/ */
export function useDirectListings( export function useDirectListings(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -205,17 +208,17 @@ export function useDirectListings(
} }
/** /**
* Use this to get a list all valid direct listings from your marketplace v3 contract. * Get all valid direct listings
* *
* @example * @example
* ```javascript * ```javascript
* const { data: directListings, isLoading, error } = useValidDirectListings(<YourMarketplaceV3ContractInstance>, { start: 0, count: 100 }); * const { data: validDirectListings, isLoading, error } = useValidDirectListings(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @param filter - filter to pass to the query for the sake of pagination & filtering * @param filter - filter to pass to the query for the sake of pagination & filtering
* @returns a response object that includes an array of direct listings * @returns a response object that includes an array of direct listings
* @internal * @twfeature DirectListings
*/ */
export function useValidDirectListings( export function useValidDirectListings(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -239,17 +242,17 @@ export function useValidDirectListings(
} }
/** /**
* Use this to get a list all english auctions from your marketplace v3 contract. * Get all english auctions
* *
* @example * @example
* ```javascript * ```javascript
* const { data: englishAuctions, isLoading, error } = useEnglishAuctions(<YourMarketplaceV3ContractInstance>, { start: 0, count: 100 }); * const { data: englishAuctions, isLoading, error } = useEnglishAuctions(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @param filter - filter to pass to the query for the sake of pagination & filtering * @param filter - filter to pass to the query for the sake of pagination & filtering
* @returns a response object that includes an array of english auctions * @returns a response object that includes an array of english auctions
* @internal * @twfeature EnglishAuctions
*/ */
export function useEnglishAuctions( export function useEnglishAuctions(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -273,17 +276,17 @@ export function useEnglishAuctions(
} }
/** /**
* Use this to get a list all valid english auctions from your marketplace v3 contract. * Get all valid english auctions
* *
* @example * @example
* ```javascript * ```javascript
* const { data: englishAuctions, isLoading, error } = useValidEnglishAuctions(<YourMarketplaceV3ContractInstance>, { start: 0, count: 100 }); * const { data: validEnglishAuctions, isLoading, error } = useValidEnglishAuctions(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @param filter - filter to pass to the query for the sake of pagination & filtering * @param filter - filter to pass to the query for the sake of pagination & filtering
* @returns a response object that includes an array of english auctions * @returns a response object that includes an array of english auctions
* @internal * @twfeature EnglishAuctions
*/ */
export function useValidEnglishAuctions( export function useValidEnglishAuctions(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -307,11 +310,11 @@ export function useValidEnglishAuctions(
} }
/** /**
* Use this to get a count of all listings on your marketplace contract. * Get the total count of listings
* *
* @example * @example
* ```javascript * ```javascript
* const { data: listingsCount, isLoading, error } = useListingsCount(<YourMarketplaceContractInstance>); * const { data: listingsCount, isLoading, error } = useListingsCount(contract);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
@@ -333,16 +336,16 @@ export function useListingsCount(contract: RequiredParam<Marketplace>) {
} }
/** /**
* Use this to get a count of all direct listings on your marketplace v3 contract. * Get the total count of direct listings
* *
* @example * @example
* ```javascript * ```javascript
* const { data: listingsCount, isLoading, error } = useListingsCount(<YourMarketplaceV3ContractInstance>); * const { data: directListingsCount, isLoading, error } = useDirectListingsCount(contract);
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @returns a response object that includes the direct listings count * @returns a response object that includes the direct listings count
* @internal * @twfeature DirectListings
*/ */
export function useDirectListingsCount(contract: RequiredParam<MarketplaceV3>) { export function useDirectListingsCount(contract: RequiredParam<MarketplaceV3>) {
const contractAddress = contract?.getAddress(); const contractAddress = contract?.getAddress();
@@ -361,16 +364,16 @@ export function useDirectListingsCount(contract: RequiredParam<MarketplaceV3>) {
} }
/** /**
* Use this to get a count of all direct listings on your marketplace v3 contract. * Get the total count of english auctions
* *
* @example * @example
* ```javascript * ```javascript
* const { data: englishAuctionsCount, isLoading, error } = useEnglishAuctionsCount(<YourMarketplaceV3ContractInstance>); * const { data: englishAuctionsCount, isLoading, error } = useEnglishAuctionsCount(contract);
* ``` * ```
* *
* @param contract - an instance of a marketplace v3 contract * @param contract - an instance of a marketplace v3 contract
* @returns a response object that includes the direct english actions count * @returns a response object that includes the direct english actions count
* @internal * @twfeature EnglishAuctions
*/ */
export function useEnglishAuctionsCount( export function useEnglishAuctionsCount(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -391,11 +394,11 @@ export function useEnglishAuctionsCount(
} }
/** /**
* Use this to get a list active listings from your marketplace contract. * Get all active listings
* *
* @example * @example
* ```javascript * ```javascript
* const { data: listings, isLoading, error } = useActiveListings(<YourMarketplaceContractInstance>, { seller: "0x...", tokenContract: "0x...", tokenId: 1, start: 0, count: 100 }); * const { data: listings, isLoading, error } = useActiveListings(contract, { seller: "{{wallet_adress}}", tokenContract: "0x...", tokenId: 1, start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
@@ -423,11 +426,12 @@ export function useActiveListings(
} }
/** /**
* Use this to get a the winning bid for an auction listing from your marketplace contract. * Get the winning bid for an auction
* *
* @example * @example
* ```javascript * ```javascript
* const { data: winningBid, isLoading, error } = useWinningBid(<YourMarketplaceContractInstance>, <listingId>); * const listingId = 0;
* const { data: winningBid, isLoading, error } = useWinningBid(contract, listingId);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
@@ -461,17 +465,18 @@ export function useWinningBid(
} }
/** /**
* Use this to get a the winning bid for an auction listing from your marketplace v3 contract. * Get the winning bid for an english auction
* *
* @example * @example
* ```javascript * ```javascript
* const { data: winningBid, isLoading, error } = useWinningBid(<YourMarketplaceV3ContractInstance>, <listingId>); * const listingId = 0;
* const { data: winningBid, isLoading, error } = useWinningBid(contract, listingId);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
* @param auctionId - the auction id to check * @param auctionId - the auction id to check
* @returns a response object that includes the {@link Bid} that is winning the auction * @returns a response object that includes the {@link Bid} that is winning the auction
* @beta * @twfeature EnglishAuctions
*/ */
export function useEnglishAuctionWinningBid( export function useEnglishAuctionWinningBid(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -499,17 +504,18 @@ export function useEnglishAuctionWinningBid(
} }
/** /**
* Use this to get the winner of an auction listing from your marketplace contract. * Get the winner of an english auction
* *
* @example * @example
* ```javascript * ```javascript
* const { data: auctionWinner, isLoading, error } = useAuctionWinner(<YourMarketplaceContractInstance>, <listingId>); * const listingId = 0;
* const { data: auctionWinner, isLoading, error } = useAuctionWinner(contract, listingId);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
* @param listingId - the listing id to check * @param listingId - the listing id to check
* @returns a response object that includes the address of the winner of the auction or undefined if there is no winner yet * @returns a response object that includes the address of the winner of the auction or undefined if there is no winner yet
* @beta * @twfeature EnglishAuctions
*/ */
export function useAuctionWinner( export function useAuctionWinner(
contract: RequiredParam<Marketplace | MarketplaceV3>, contract: RequiredParam<Marketplace | MarketplaceV3>,
@@ -549,18 +555,18 @@ export function useAuctionWinner(
} }
/** /**
* Use this to get the buffer in basis points between offers from your marketplace contract. * Get the bid buffer for an english auction
* *
* @example * @example
* ```javascript * ```javascript
* const { data: auctionWinner, isLoading, error } = useBidBuffer(<YourMarketplaceContractInstance>); * const { data: bidBuffer, isLoading, error } = useBidBuffer(contract);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
* @param listingId - the listing id to check (only necessary for marketplace v3) * @param listingId - the listing id to check (only necessary for marketplace v3)
* @returns a response object that includes an array of listings * @returns a response object that includes an array of listings
* @beta * @twfeature EnglishAuctions
*/ */
export function useBidBuffer( export function useBidBuffer(
contract: RequiredParam<Marketplace | MarketplaceV3>, contract: RequiredParam<Marketplace | MarketplaceV3>,
@@ -599,17 +605,18 @@ export function useBidBuffer(
} }
/** /**
* Use this to get the minimum next bid for the auction listing from your marketplace contract. * Get the minimum next bid for an english auction
* *
* @example * @example
* ```javascript * ```javascript
* const { data: minimumNextBid, isLoading, error } = useMinimumNextBid(<YourMarketplaceContractInstance>, <listingId>); * const listingId = 0;
* const { data: minimumNextBid, isLoading, error } = useMinimumNextBid(contract, listingId);
* ``` * ```
* *
* @param contract - an instance of a marketplace contract * @param contract - an instance of a marketplace contract
* @param listingId - the listing id to check * @param listingId - the listing id to check
* @returns a response object that includes the minimum next bid for the auction listing * @returns a response object that includes the minimum next bid for the auction listing
* @beta * @twfeature EnglishAucton
*/ */
export function useMinimumNextBid( export function useMinimumNextBid(
contract: RequiredParam<Marketplace | MarketplaceV3>, contract: RequiredParam<Marketplace | MarketplaceV3>,
@@ -648,21 +655,49 @@ export function useMinimumNextBid(
); );
} }
/**
* Get all the offers for a listing
*
* @remarks Fetch all the offers for a specified direct or auction listing.
* @example
* ```javascript
* const listingId = 0;
* const { data: offers, isLoading, error } = useOffers(contract, listingId);
* ```
*
* @param contract - an instance of a Marketplace contract
* @param listingId - the id of the listing to fetch offers for
* @beta
*/
export function useOffers(
contract: RequiredParam<Marketplace>,
listingId: RequiredParam<BigNumberish>,
) {
const result = useContractEvents(contract, "NewOffer");
return {
...result,
data: result.data
?.filter((ev) => ev.data.listingId.eq(listingId))
?.map((ev) => ev.data),
};
}
/** **********************/ /** **********************/
/** WRITE HOOKS **/ /** WRITE HOOKS **/
/** **********************/ /** **********************/
/** /**
* Use this to create a new Direct Listing on your marketplace contract. * Create a new direct listing
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: createDirectListing, * mutate: createDirectListing,
* isLoading, * isLoading,
* error, * error,
* } = useCreateDirectListing(">>YourMarketplaceContractInstance<<"); * } = useCreateDirectListing(contract);
* *
* if (error) { * if (error) {
* console.error("failed to create direct listing", error); * console.error("failed to create direct listing", error);
@@ -681,7 +716,7 @@ export function useMinimumNextBid(
* *
* @param contract - an instance of a Marketplace contract * @param contract - an instance of a Marketplace contract
* @returns a mutation object that can be used to create a new direct listing * @returns a mutation object that can be used to create a new direct listing
* @beta * @twfeature DirectListings
*/ */
export function useCreateDirectListing< export function useCreateDirectListing<
TMarketplace extends Marketplace | MarketplaceV3, TMarketplace extends Marketplace | MarketplaceV3,
@@ -730,16 +765,17 @@ export function useCreateDirectListing<
} }
/** /**
* Use this to create a new Auction Listing on your marketplace contract. * Create a new english auction
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: createAuctionListing, * mutate: createAuctionListing,
* isLoading, * isLoading,
* error, * error,
* } = useCreateAuctionListing(">>YourMarketplaceContractInstance<<"); * } = useCreateAuctionListing(contract);
* *
* if (error) { * if (error) {
* console.error("failed to create auction listing", error); * console.error("failed to create auction listing", error);
@@ -758,7 +794,7 @@ export function useCreateDirectListing<
* *
* @param contract - an instance of a Marketplace contract * @param contract - an instance of a Marketplace contract
* @returns a mutation object that can be used to create a new auction listing * @returns a mutation object that can be used to create a new auction listing
* @beta * @twfeature EnglishAuctions
*/ */
export function useCreateAuctionListing< export function useCreateAuctionListing<
TMarketplace extends Marketplace | MarketplaceV3, TMarketplace extends Marketplace | MarketplaceV3,
@@ -807,16 +843,17 @@ export function useCreateAuctionListing<
} }
/** /**
* Use this to cancel a listing on your marketplace contract. * Cancel a listing
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: cancelListing, * mutate: cancelListing,
* isLoading, * isLoading,
* error, * error,
* } = useCancelListing(">>YourMarketplaceContractInstance<<"); * } = useCancelListing(contract);
* *
* if (error) { * if (error) {
* console.error("failed to cancel auction listing", error); * console.error("failed to cancel auction listing", error);
@@ -825,7 +862,7 @@ export function useCreateAuctionListing<
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => cancelListing()} * onClick={cancelListing}
* > * >
* Cancel Auction Listing! * Cancel Auction Listing!
* </button> * </button>
@@ -873,16 +910,17 @@ export function useCancelListing(contract: RequiredParam<Marketplace>) {
} }
/** /**
* Use this to cancel a direct listing on your marketplace v3 contract. * Cancel a direct listing
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: cancelDirectListing, * mutate: cancelDirectListing,
* isLoading, * isLoading,
* error, * error,
* } = useCancelDirectListing(">>YourMarketplaceV3ContractInstance<<"); * } = useCancelDirectListing(contract);
* *
* if (error) { * if (error) {
* console.error("failed to cancel direct listing", error); * console.error("failed to cancel direct listing", error);
@@ -891,7 +929,7 @@ export function useCancelListing(contract: RequiredParam<Marketplace>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => cancelListing()} * onClick={cancelDirectListing}
* > * >
* Cancel Direct Listing * Cancel Direct Listing
* </button> * </button>
@@ -901,7 +939,7 @@ export function useCancelListing(contract: RequiredParam<Marketplace>) {
* *
* @param contract - an instance of a Marketplace v3 contract * @param contract - an instance of a Marketplace v3 contract
* @returns a mutation object that can be used to cancel a direct listing * @returns a mutation object that can be used to cancel a direct listing
* @internal * @twfeature DirectListings
*/ */
export function useCancelDirectListing(contract: RequiredParam<MarketplaceV3>) { export function useCancelDirectListing(contract: RequiredParam<MarketplaceV3>) {
const activeChainId = useSDKChainId(); const activeChainId = useSDKChainId();
@@ -932,16 +970,17 @@ export function useCancelDirectListing(contract: RequiredParam<MarketplaceV3>) {
} }
/** /**
* Use this to cancel a direct listing on your marketplace v3 contract. * Cancel an english auction
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: cancelEnglishAuction, * mutate: cancelEnglishAuction,
* isLoading, * isLoading,
* error, * error,
* } = useCancelEnglishAuction(">>YourMarketplaceV3ContractInstance<<"); * } = useCancelEnglishAuction(contract);
* *
* if (error) { * if (error) {
* console.error("failed to cancel english auction", error); * console.error("failed to cancel english auction", error);
@@ -950,7 +989,7 @@ export function useCancelDirectListing(contract: RequiredParam<MarketplaceV3>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => cancelEnglishAuction()} * onClick={cancelEnglishAuction}
* > * >
* Cancel English Auction * Cancel English Auction
* </button> * </button>
@@ -960,7 +999,7 @@ export function useCancelDirectListing(contract: RequiredParam<MarketplaceV3>) {
* *
* @param contract - an instance of a Marketplace v3 contract * @param contract - an instance of a Marketplace v3 contract
* @returns a mutation object that can be used to cancel an english auction * @returns a mutation object that can be used to cancel an english auction
* @internal * @twfeature EnglishAuctions
*/ */
export function useCancelEnglishAuction( export function useCancelEnglishAuction(
contract: RequiredParam<MarketplaceV3>, contract: RequiredParam<MarketplaceV3>,
@@ -993,16 +1032,17 @@ export function useCancelEnglishAuction(
} }
/** /**
* Use this to place a bid on an auction listing from your marketplace contract. * Make a bid on an auction listing
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: makeBid, * mutate: makeBid,
* isLoading, * isLoading,
* error, * error,
* } = useMakeBid(">>YourMarketplaceContractInstance<<"); * } = useMakeBid(contract);
* *
* if (error) { * if (error) {
* console.error("failed to make a bid", error); * console.error("failed to make a bid", error);
@@ -1050,16 +1090,17 @@ export function useMakeBid(contract: RequiredParam<Marketplace>) {
} }
/** /**
* Use this to make an offer on direct or auction listing from your marketplace contract. * Nake an offer on a direct or auction listing
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: makeOffer, * mutate: makeOffer,
* isLoading, * isLoading,
* error, * error,
* } = useMakeOffer(">>YourMarketplaceContractInstance<<"); * } = useMakeOffer(contract);
* *
* if (error) { * if (error) {
* console.error("failed to make a bid", error); * console.error("failed to make a bid", error);
@@ -1107,16 +1148,19 @@ export function useMakeOffer(contract: RequiredParam<Marketplace>) {
} }
/** /**
* Accept an offer on a direct listing from an offeror, will accept the latest offer by the given offeror. * Accept a specific offer on a direct listing
*
* @remarks will accept the latest offer by the given offeror.
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: acceptOffer, * mutate: acceptOffer,
* isLoading, * isLoading,
* error, * error,
* } = useAcceptDirectListingOffer(">>YourMarketplaceContractInstance<<"); * } = useAcceptDirectListingOffer(contract);
* *
* if (error) { * if (error) {
* console.error("failed to accept offer", error); * console.error("failed to accept offer", error);
@@ -1125,7 +1169,7 @@ export function useMakeOffer(contract: RequiredParam<Marketplace>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => acceptOffer({ listingId: 1, addressOfOfferor: "0x..." })} * onClick={() => acceptOffer({ listingId: 1, addressOfOfferor: "{{wallet_address}}" })}
* > * >
* Accept offer * Accept offer
* </button> * </button>
@@ -1135,7 +1179,6 @@ export function useMakeOffer(contract: RequiredParam<Marketplace>) {
* *
* @param contract - an instance of a Marketplace contract * @param contract - an instance of a Marketplace contract
* @returns a mutation object that can be used to accept an offer on a direct listing * @returns a mutation object that can be used to accept an offer on a direct listing
* @beta
*/ */
export function useAcceptDirectListingOffer( export function useAcceptDirectListingOffer(
contract: RequiredParam<Marketplace>, contract: RequiredParam<Marketplace>,
@@ -1170,11 +1213,12 @@ export function useAcceptDirectListingOffer(
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: executeAuctionSale, * mutate: executeAuctionSale,
* isLoading, * isLoading,
* error, * error,
* } = useExecuteAuctionSale(">>YourMarketplaceContractInstance<<"); * } = useExecuteAuctionSale(contract);
* *
* if (error) { * if (error) {
* console.error("failed to execute sale", error); * console.error("failed to execute sale", error);
@@ -1221,42 +1265,17 @@ export function useExecuteAuctionSale(contract: RequiredParam<Marketplace>) {
} }
/** /**
* Get all the offers for a listing * Buy out an auction listing
*
* @remarks Fetch all the offers for a specified direct or auction listing.
* @example
* ```javascript
* const { data: offers, isLoading, error } = useOffers(<YourMarketplaceContractInstance>, <listingId>);
* ```
*
* @param contract - an instance of a Marketplace contract
* @param listingId - the id of the listing to fetch offers for
* @beta
*/
export function useOffers(
contract: RequiredParam<Marketplace>,
listingId: RequiredParam<BigNumberish>,
) {
const result = useContractEvents(contract, "NewOffer");
return {
...result,
data: result.data
?.filter((ev) => ev.data.listingId.eq(listingId))
?.map((ev) => ev.data),
};
}
/**
* Use this to buy out an auction listing from your marketplace contract.
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: buyNow, * mutate: buyNow,
* isLoading, * isLoading,
* error, * error,
* } = useBuyNow(">>YourMarketplaceContractInstance<<"); * } = useBuyNow(contract);
* *
* if (error) { * if (error) {
* console.error("failed to buyout listing", error); * console.error("failed to buyout listing", error);
+48 -114
View File
@@ -29,12 +29,12 @@ import invariant from "tiny-invariant";
/** **********************/ /** **********************/
/** /**
* Use this to get an individual NFT token of your {@link NFTContract}. * Get a single NFT
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const tokenId = 0; // the tokenId to look up
* const { data: nft, isLoading, error } = useNFT(contract, <tokenId>); * const { data: nft, isLoading, error } = useNFT(contract, tokenId);
* ``` * ```
* *
* @param contract - an instance of a {@link NFTContract} * @param contract - an instance of a {@link NFTContract}
@@ -72,18 +72,17 @@ export function useNFT<TContract extends NFTContract>(
} }
/** /**
* Use this to get a list of NFT tokens of your {@link NFTContract}. * Get all NFTs
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>);
* const { data: nfts, isLoading, error } = useNFTs(contract, { start: 0, count: 100 }); * const { data: nfts, isLoading, error } = useNFTs(contract, { start: 0, count: 100 });
* ``` * ```
* *
* @param contract - an instance of a {@link NFTContract} * @param contract - an instance of a {@link NFTContract}
* @param queryParams - query params to pass to the query for the sake of pagination * @param queryParams - query params to pass to the query for pagination
* @returns a response object that includes an array of NFTs * @returns a response object that includes an array of NFTs
* @twfeature ERC721Supply | ERC1155Enumerable * @twfeature ERC721Supply | ERC721Enumerable | ERC1155Enumerable
* @beta * @beta
*/ */
export function useNFTs<TContract extends NFTContract>( export function useNFTs<TContract extends NFTContract>(
@@ -115,11 +114,11 @@ export function useNFTs<TContract extends NFTContract>(
} }
/** /**
* Use this to get the total count of NFT tokens of your {@link NFTContract}. * Get total supply count
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { data: count, isLoading, error } = useTotalCount(contract); * const { data: count, isLoading, error } = useTotalCount(contract);
* ``` * ```
* *
@@ -162,16 +161,17 @@ export function useTotalCount<TContract extends NFTContract>(
} }
/** /**
* Use this to get a the total (minted) supply of your {@link NFTContract}. * Get total minted supply count
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { data: totalCirculatingSupply, isLoading, error } = useTotalCirculatingSupply(contract); * const { data: totalCirculatingSupply, isLoading, error } = useTotalCirculatingSupply(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link NFTContract} * @param contract - an instance of a {@link NFTContract}
* @returns a response object that incudes the total minted supply * @param tokenId - required for ERC1155, the tokenId to look up
* @returns a response object that includes the total minted supply
* @beta * @beta
* @twfeature ERC721Supply | ERC1155Enumerable * @twfeature ERC721Supply | ERC1155Enumerable
*/ */
@@ -211,19 +211,18 @@ export function useTotalCirculatingSupply(
} }
/** /**
* Use this to get a the owned NFTs for a specific {@link Erc721OrErc1155} and wallet address. * Get all NFTs owned by a specific wallet
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { data: ownedNFTs, isLoading, error } = useOwnedNFTs(contract, "{{wallet_address}}");
* const { data: ownedNFTs, isLoading, error } = useOwnedNFTs(contract, <OwnerWalletAddress>);
* ``` * ```
* *
* @param contract - an instance of a {@link NFTContract} * @param contract - an instance of a {@link NFTContract}
* @param ownerWalletAddress - the wallet adress to get owned tokens for * @param ownerWalletAddress - the wallet address to get owned tokens for
* @returns a response object that includes the list of owned tokens * @returns a response object that includes the list of owned tokens
* @beta * @beta
* @twfeature ERC721Enumerable | ERC1155Enumerable * @twfeature ERC721Enumerable | ERC1155Enumerable | ERC721Supply
*/ */
export function useOwnedNFTs<TContract extends NFTContract>( export function useOwnedNFTs<TContract extends NFTContract>(
contract: RequiredParam<TContract>, contract: RequiredParam<TContract>,
@@ -252,16 +251,19 @@ export function useOwnedNFTs<TContract extends NFTContract>(
} }
/** /**
* Use this to get a the total balance of a {@link NFTContract} and wallet address. * Get NFT balance of a specific wallet
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { data: ownerBalance, isLoading, error } = useNFTBalance(contract, "{{wallet_address}}");
* const { data: ownerBalance, isLoading, error } = useNFTBalance(contract, <OwnerWalletAddress>); * // for ERC1155 contracts, you can also pass a tokenId
* const tokenId = 0;
* const { data: ownerBalance, isLoading, error } = useNFTBalance(contract, "{{wallet_address}}", tokenId);
* ``` * ```
* *
* @param contract - an instance of a {@link NFTContract} * @param contract - an instance of a {@link NFTContract}
* @param ownerWalletAddress - the wallet adress to check the balance of * @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 * @returns a response object that includes the total balance of the owner
* @twfeature ERC721 | ERC1155 * @twfeature ERC721 | ERC1155
* @beta * @beta
@@ -311,36 +313,12 @@ export function useNFTBalance(
/** **********************/ /** **********************/
/** /**
* Use this to mint a new NFT on your {@link Erc721OrErc1155} * Mint an NFT to a specific wallet
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const nftDrop = useNFTDrop(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const {
* mutate: mintNft,
* isLoading,
* error,
* } = useMintNFT(nftDrop);
*
* if (error) {
* console.error("failed to mint nft", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => mintNft({ name: "My awesome NFT!", to: "0x..." })}
* >
* Mint!
* </button>
* );
* };
* ```
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const { * const {
* mutate: mintNft, * mutate: mintNft,
* isLoading, * isLoading,
@@ -348,13 +326,13 @@ export function useNFTBalance(
* } = useMintNFT(contract); * } = useMintNFT(contract);
* *
* if (error) { * if (error) {
* console.error("failed to mint nft", error); * console.error("failed to mint NFT", error);
* } * }
* *
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => mintNft({ name: "My awesome NFT!", to: "0x..." })} * onClick={() => mintNft({ name: "My awesome NFT!", to: "{{wallet_address}}" })}
* > * >
* Mint! * Mint!
* </button> * </button>
@@ -407,12 +385,12 @@ export function useMintNFT<TContract extends NFTContract>(
} }
/** /**
* Use this to mint a new NFT on your {@link Erc1155} * Increase the supply of an existing NFT
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: mintNftSupply, * mutate: mintNftSupply,
* isLoading, * isLoading,
@@ -426,7 +404,7 @@ export function useMintNFT<TContract extends NFTContract>(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => mintNftSupply({ tokenId: 0, additionalSupply: 100, to: "0x..."})} * onClick={() => mintNftSupply({ tokenId: 0, additionalSupply: 100, to: "{{wallet_address}}"})}
* > * >
* Mint Additional Supply! * Mint Additional Supply!
* </button> * </button>
@@ -470,12 +448,12 @@ export function useMintNFTSupply(contract: Erc1155) {
} }
/** /**
* Use this to transfer tokens on your {@link NFTContract} * Transfer an NFT
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: transferNFT, * mutate: transferNFT,
* isLoading, * isLoading,
@@ -483,13 +461,16 @@ export function useMintNFTSupply(contract: Erc1155) {
* } = useTransferNFT(contract); * } = useTransferNFT(contract);
* *
* if (error) { * if (error) {
* console.error("failed to transfer nft", error); * console.error("failed to transfer NFT", error);
* } * }
* *
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => transferNFT({ to: "0x...", tokenId: 2 })} * onClick={() => transferNFT({
* to: "{{wallet_address}}",
* tokenId: 2
* })}
* > * >
* Transfer * Transfer
* </button> * </button>
@@ -537,38 +518,12 @@ export function useTransferNFT<TContract extends NFTContract>(
} }
/** /**
* Use this to transfer tokens on your {@link Erc1155} * Airdrop NFTs to a list of wallets
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const editionDrop = useContract(<ContractAddress>, "edition-drop"); * const { contract } = useContract("{{contract_address}}");
* const {
* mutate: airdropNFT,
* isLoading,
* error,
* } = useAirdropNFT(editionDrop);
*
* if (error) {
* console.error("failed to transfer batch NFTs", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => airdropNFT({
* tokenId: 2,
* addresses: [{ address: "0x...", quantity: 2 }, { address: "0x...", quantity: 4 } }]
* )}
* >
* Airdrop NFT
* </button>
* };
* ```
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const { * const {
* mutate: airdropNFT, * mutate: airdropNFT,
* isLoading, * isLoading,
@@ -584,7 +539,10 @@ export function useTransferNFT<TContract extends NFTContract>(
* disabled={isLoading} * disabled={isLoading}
* onClick={() => airdropNFT({ * onClick={() => airdropNFT({
* tokenId: 2, * tokenId: 2,
* addresses: [{ address: "0x...", quantity: 2 }, { address: "0x...", quantity: 4 } }] * addresses: [
* { address: "{{wallet_address}}", quantity: 2 },
* { address: "{{wallet_address}}", quantity: 4 } }
* ]
* )} * )}
* > * >
* Airdrop NFT * Airdrop NFT
@@ -626,50 +584,26 @@ export function useAirdropNFT(contract: Erc1155) {
/** **********************/ /** **********************/
/** /**
* Use this to burn an NFT on your {@link Erc721OrErc1155} * Burn an NFT
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const nftDrop = useNFTDrop(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: burnNft, * mutate: burnNFT,
* isLoading,
* error,
* } = useBurnNFT(nftDrop);
*
* if (error) {
* console.error("failed to burn nft", error);
* }
*
* return (
* <button
* disabled={isLoading}
* onClick={() => burnNft({ tokenId: 0 })}
* >
* Burn!
* </button>
* );
* };
* ```
* @example
* ```jsx
* const Component = () => {
* const { contract } = useContract(<ContractAddress>);
* const {
* mutate: burnNft,
* isLoading, * isLoading,
* error, * error,
* } = useBurnNFT(contract); * } = useBurnNFT(contract);
* *
* if (error) { * if (error) {
* console.error("failed to burn nft", error); * console.error("failed to burn NFT", error);
* } * }
* *
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => burnNft({ tokenId: 0 })} * onClick={() => burnNFT({ tokenId: 0, amount: 1 })}
* > * >
* Burn! * Burn!
* </button> * </button>
@@ -45,11 +45,11 @@ type GetAllReturnType<TContract extends ContractWithRoles> = Promise<
/** **********************/ /** **********************/
/** /**
* Use this to get the roles of a {@link SmartContract} * Get all members of all roles
* *
* @example * @example
* ```jsx * ```jsx
* const { data: roles, isLoading, error } = useAllRoleMembers(SmartContract); * const { data: roles, isLoading, error } = useAllRoleMembers(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
@@ -76,7 +76,7 @@ export function useAllRoleMembers<TContract extends ContractWithRoles>(
} }
/** /**
* Use this to get the members of a role on a {@link SmartContract} * Get all members of a specific role
* *
* @example * @example
* ```jsx * ```jsx
@@ -86,7 +86,7 @@ export function useAllRoleMembers<TContract extends ContractWithRoles>(
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
* @param role - the role to get the members of, see {@link Role} * @param role - the role to get the members of, see {@link Role}
* @returns a list of addresses that are members of the role * @returns a list of addresses that are members of the role
* @twfeature PermissionsEnumerable * @twfeature Permissions
* @beta * @beta
*/ */
export function useRoleMembers<TContract extends ContractWithRoles>( export function useRoleMembers<TContract extends ContractWithRoles>(
@@ -108,18 +108,18 @@ export function useRoleMembers<TContract extends ContractWithRoles>(
} }
/** /**
* Use this to check if a {@link WalletAddress} is a member of a role on a {@link SmartContract} * Check if an address is a member of a specific role
* *
* @example * @example
* ```jsx * ```jsx
* const { data: isMember, isLoading, error } = useIsAddressRole(SmartContract, "admin", "0x123"); * const { data: isMember, isLoading, error } = useIsAddressRole(contract, "admin", "{{wallet_address}}");
* ``` * ```
* *
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
* @param role - the role to check the member against, see {@link Role} * @param role - the role to check the member against, see {@link Role}
* @param walletAddress - the address to check * @param walletAddress - the address to check
* @returns true if the address is a member of the role, or false if not * @returns true if the address is a member of the role, or false if not
* @twfeature Permissions * @twfeature PermissionsEnumerable
* @beta * @beta
*/ */
export function useIsAddressRole<TContract extends ContractWithRoles>( export function useIsAddressRole<TContract extends ContractWithRoles>(
@@ -153,16 +153,17 @@ export function useIsAddressRole<TContract extends ContractWithRoles>(
/** **********************/ /** **********************/
/** /**
* Use this to OVERWRITE the list of addresses that are members of specific roles * Overwrite the list of members for specific roles
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: overwriteRoles, * mutate: overwriteRoles,
* isLoading, * isLoading,
* error, * error,
* } = useSetAllRoleMembers(SmartContract); * } = useSetAllRoleMembers(contract);
* *
* if (error) { * if (error) {
* console.error("failed to overwrite roles", error); * console.error("failed to overwrite roles", error);
@@ -171,7 +172,7 @@ export function useIsAddressRole<TContract extends ContractWithRoles>(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => overwriteRoles({ rolesWithAddresses: { minter: [] } })} * onClick={() => overwriteRoles({ rolesWithAddresses: { minter: ["{{wallet_address}"] } })}
* > * >
* Overwrite Roles * Overwrite Roles
* </button> * </button>
@@ -181,7 +182,7 @@ export function useIsAddressRole<TContract extends ContractWithRoles>(
* *
* @param contract - an instance of a {@link SmartContract} * @param contract - an instance of a {@link SmartContract}
* @returns a mutation object that can be used to overwrite all roles on the contract * @returns a mutation object that can be used to overwrite all roles on the contract
* @twfeature PermissionsEnumerable * @twfeature Permissions
* @beta * @beta
*/ */
export function useSetAllRoleMembers<TContract extends ContractWithRoles>( export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
@@ -210,19 +211,18 @@ export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
); );
} }
// const { mutate } = useSetAllRoleMembers(undefined as unknown as NFTCollection);
/** /**
* Use this to grant a {@link WalletAddress} a specific role on a {@link SmartContract} * Grant a role to a specific address
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: grantRole, * mutate: grantRole,
* isLoading, * isLoading,
* error, * error,
* } = useGrantRole(SmartContract); * } = useGrantRole(contract);
* *
* if (error) { * if (error) {
* console.error("failed to grant role", error); * console.error("failed to grant role", error);
@@ -231,7 +231,7 @@ export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => grantRole({ role: "admin", address: "0x123" })} * onClick={() => grantRole({ role: "admin", address: {{wallet_address}} })}
* > * >
* Grant Role * Grant Role
* </button> * </button>
@@ -241,7 +241,7 @@ export function useSetAllRoleMembers<TContract extends ContractWithRoles>(
* *
* @param contract - an instance of a {@link SmartContract} * @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 * @returns a mutation object that can be used to grant a member of a role on the contract
* @twfeature Permissions * @twfeature Permissions | PermissionsEnumerable
* @beta * @beta
*/ */
export function useGrantRole<TContract extends ContractWithRoles>( export function useGrantRole<TContract extends ContractWithRoles>(
@@ -272,16 +272,17 @@ export function useGrantRole<TContract extends ContractWithRoles>(
} }
/** /**
* Use this to revoke a {@link WalletAddress} a specific role on a {@link SmartContract} * Revoke a role from a specific address
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: revokeRole, * mutate: revokeRole,
* isLoading, * isLoading,
* error, * error,
* } = useRevokeRole(SmartContract); * } = useRevokeRole(contract);
* *
* if (error) { * if (error) {
* console.error("failed to revoke role", error); * console.error("failed to revoke role", error);
@@ -290,7 +291,7 @@ export function useGrantRole<TContract extends ContractWithRoles>(
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => revokeRole({ role: "admin", address: "0x123" })} * onClick={() => revokeRole({ role: "admin", address: {{wallet_address}} })}
* > * >
* Revoke Role * Revoke Role
* </button> * </button>
@@ -300,7 +301,7 @@ export function useGrantRole<TContract extends ContractWithRoles>(
* *
* @param contract - an instance of a {@link SmartContract} * @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 * @returns a mutation object that can be used to revoke a role from a member on the contract
* @twfeature Permissions * @twfeature Permissions | PermissionsEnumerable
* @beta * @beta
*/ */
export function useRevokeRole<TContract extends ContractWithRoles>( export function useRevokeRole<TContract extends ContractWithRoles>(
@@ -24,16 +24,15 @@ import invariant from "tiny-invariant";
/** **********************/ /** **********************/
/** /**
* Use this to get a the total supply of your {@link Erc20} contract. * Get the total supply for this token
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>);
* const { data: totalSupply, isLoading, error } = useTokenSupply(contract); * const { data: totalSupply, isLoading, error } = useTokenSupply(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link TokenContract} * @param contract - an instance of a {@link TokenContract}
* @returns a response object that incudes the total minted supply * @returns a response object that includes the total minted supply
* @twfeature ERC20 * @twfeature ERC20
* @beta * @beta
*/ */
@@ -56,12 +55,11 @@ export function useTokenSupply(contract: RequiredParam<TokenContract>) {
} }
/** /**
* Use this to get the balance of your {@link Erc20} contract for a given address. * Get token balance for a specific wallet
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { data: balance, isLoading, error } = useTokenBalance(contract, "{{wallet_address}}");
* const { data: balance, isLoading, error } = useTokenBalance(contract);
* ``` * ```
* *
* @param contract - an instance of a {@link TokenContract} * @param contract - an instance of a {@link TokenContract}
@@ -93,11 +91,10 @@ export function useTokenBalance(
} }
/** /**
* Use this to get the decimals of your {@link Erc20} contract for a given address. * Get token decimals
* *
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>);
* const { data: decimals, isLoading, error } = useTokenDecimals(contract); * const { data: decimals, isLoading, error } = useTokenDecimals(contract);
* ``` * ```
* *
@@ -130,12 +127,12 @@ export function useTokenDecimals(contract: RequiredParam<TokenContract>) {
/** **********************/ /** **********************/
/** /**
* Use this to mint new tokens on your {@link Erc20} contract * Mint tokens
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: mintTokens, * mutate: mintTokens,
* isLoading, * isLoading,
@@ -149,7 +146,7 @@ export function useTokenDecimals(contract: RequiredParam<TokenContract>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => mintTokens({ to: "0x...", amount: 1000 })} * onClick={() => mintTokens({ to: "{{wallet_address}}", amount: 1000 })}
* > * >
* Mint! * Mint!
* </button> * </button>
@@ -189,12 +186,12 @@ export function useMintToken(contract: RequiredParam<TokenContract>) {
} }
/** /**
* Use this to claim tokens on your {@link Erc20} * Claim tokens to a specific wallet
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: claimTokens, * mutate: claimTokens,
* isLoading, * isLoading,
@@ -208,7 +205,7 @@ export function useMintToken(contract: RequiredParam<TokenContract>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => claimTokens({ to: "0x...", amount: 100 })} * onClick={() => claimTokens({ to: "{{wallet_address}}", amount: 100 })}
* > * >
* Claim Tokens! * Claim Tokens!
* </button> * </button>
@@ -217,8 +214,8 @@ export function useMintToken(contract: RequiredParam<TokenContract>) {
* ``` * ```
* *
* @param contract - an instance of a {@link TokenContract} * @param contract - an instance of a {@link TokenContract}
* @returns a mutation object that can be used to tokens to the wallet specificed in the params * @returns a mutation object that can be used to tokens to the wallet specified in the params
* @twfeature ERC20ClaimableWithConditions * @twfeature ERC20ClaimPhasesV2 | ERC20ClaimPhasesV1 | ERC20ClaimConditionsV2 | ERC20ClaimConditionsV1
* @beta * @beta
*/ */
export function useClaimToken(contract: RequiredParam<TokenContract>) { export function useClaimToken(contract: RequiredParam<TokenContract>) {
@@ -250,12 +247,12 @@ export function useClaimToken(contract: RequiredParam<TokenContract>) {
} }
/** /**
* Use this to transfer tokens on your {@link Erc20} contract * Transfer tokens to a specific wallet
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: transferTokens, * mutate: transferTokens,
* isLoading, * isLoading,
@@ -269,7 +266,7 @@ export function useClaimToken(contract: RequiredParam<TokenContract>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => transferTokens({ to: "0x...", amount: 1000 })} * onClick={() => transferTokens({ to: "{{wallet_address}}", amount: 1000 })}
* > * >
* Transfer * Transfer
* </button> * </button>
@@ -309,12 +306,12 @@ export function useTransferToken(contract: RequiredParam<TokenContract>) {
} }
/** /**
* Use this to transfer batch tokens on your {@link Erc20} contract * Airdrop tokens to a list of wallets
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: transferBatchTokens, * mutate: transferBatchTokens,
* isLoading, * isLoading,
@@ -328,9 +325,9 @@ export function useTransferToken(contract: RequiredParam<TokenContract>) {
* return ( * return (
* <button * <button
* disabled={isLoading} * disabled={isLoading}
* onClick={() => transferBatchTokens([{ to: "0x...", amount: 1000 }, { to: "0x...", amount: 2000 }])} * onClick={() => transferBatchTokens([{ to: "{{wallet_address}}", amount: 1000 }, { to: "{{wallet_address}}", amount: 2000 }])}
* > * >
* Transfer Batch * Airdrop
* </button> * </button>
* ); * );
* }; * };
@@ -375,12 +372,12 @@ export function useTransferBatchToken(contract: RequiredParam<TokenContract>) {
} }
/** /**
* Use this to burn tokens on your {@link Erc20} contract * Burn tokens
* *
* @example * @example
* ```jsx * ```jsx
* const Component = () => { * const Component = () => {
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* const { * const {
* mutate: burnTokens, * mutate: burnTokens,
* isLoading, * isLoading,
@@ -35,6 +35,7 @@ export function useLogin() {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ payload }), body: JSON.stringify({ payload }),
credentials: "include",
}); });
if (!res.ok) { if (!res.ok) {
@@ -3,7 +3,7 @@ import { showDeprecationWarning } from "../../utils/deprecation-warning";
import { useContract } from "../async/contracts"; import { useContract } from "../async/contracts";
/** /**
* Hook for getting an instance of an `EditionDrop` contract. This conract is used to interface with ERC1155 compliant NFTs that can be lazily minted. * 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 * @example
@@ -15,7 +15,7 @@ import { useContract } from "../async/contracts";
* *
* // Now you can use the split contract in the rest of the component * // Now you can use the split contract in the rest of the component
* *
* // For example, this function will retrun all the receipients of the split * // For example, this function will return all the recipients of the split
* async function getRecipients() { * async function getRecipients() {
* const recipients = await contract.getAllRecipients() * const recipients = await contract.getAllRecipients()
* return recipients * return recipients
@@ -5,7 +5,7 @@ import { useChainId } from "./wallet";
* Hook for checking whether the connected wallet is on the correct network specified by the `network` passed to the `<ThirdwebProvider />`. * Hook for checking whether the connected wallet is on the correct network specified by the `network` passed to the `<ThirdwebProvider />`.
* *
* ```javascript * ```javascript
* import { useNetworkMistmatch } from "@thirdweb-dev/react" * 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 /> * @returns `true` if the chainId of the connected wallet is different from the chainId of the network passed into <ThirdwebProvider />
+1
View File
@@ -16,6 +16,7 @@ export * from "./hooks/async/claim-conditions";
export * from "./hooks/async/contract-settings"; export * from "./hooks/async/contract-settings";
export * from "./hooks/async/roles"; export * from "./hooks/async/roles";
export * from "./hooks/async/app";
// thirdweb hooks (work as long as at least `<ThirdwebSdkProvider>` is used) // thirdweb hooks (work as long as at least `<ThirdwebSdkProvider>` is used)
export * from "./hooks/auth"; export * from "./hooks/auth";
@@ -17,7 +17,7 @@ import {
} from "@thirdweb-dev/sdk/evm"; } from "@thirdweb-dev/sdk/evm";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import type { Signer } from "ethers"; import type { Signer } from "ethers";
import { createContext, useContext, useMemo } from "react"; import { createContext, useContext, useEffect, useMemo } from "react";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
interface TWSDKContext { interface TWSDKContext {
@@ -27,28 +27,6 @@ interface TWSDKContext {
const ThirdwebSDKContext = createContext<TWSDKContext>({}); const ThirdwebSDKContext = createContext<TWSDKContext>({});
function resolveChainIdFromNetwork(
network?: number | string,
chains: Readonly<Chain[]> = defaultChains,
): number | undefined {
let chainId: number | undefined = undefined;
// try to resolve the chainId
if (typeof network === "number") {
if (chains.find((c) => c.chainId === network)) {
chainId = network;
}
} else if (typeof network === "string") {
const chain = chains.find((c) => c.slug === network);
if (chain) {
chainId = chain.chainId;
}
}
return chainId;
}
// this allows autocomplete to work for the chainId prop but still allows `number` and `string` to be passed (for dynamically passed chain data)
type ChainIdIsh = (string | number) & { __chainIdIsh: never };
export interface ThirdwebSDKProviderProps< export interface ThirdwebSDKProviderProps<
TChains extends Chain[] = typeof defaultChains, TChains extends Chain[] = typeof defaultChains,
> extends QueryClientProviderProps { > extends QueryClientProviderProps {
@@ -65,11 +43,7 @@ export interface ThirdwebSDKProviderProps<
authConfig?: ThirdwebAuthConfig; authConfig?: ThirdwebAuthConfig;
// the network to use - optional, defaults to undefined // the network to use - optional, defaults to undefined
activeChain?: activeChain?: TChains[number]["chainId"] | TChains[number]["slug"] | Chain;
| TChains[number]["chainId"]
| TChains[number]["slug"]
| ChainIdIsh
| Chain;
// api keys that can be passed // api keys that can be passed
thirdwebApiKey?: string; thirdwebApiKey?: string;
@@ -91,7 +65,7 @@ const WrappedThirdwebSDKProvider = <
activeChain, activeChain,
signer, signer,
children, children,
thirdwebApiKey = DEFAULT_API_KEY, thirdwebApiKey,
infuraApiKey, infuraApiKey,
alchemyApiKey, alchemyApiKey,
}: React.PropsWithChildren< }: React.PropsWithChildren<
@@ -99,25 +73,24 @@ const WrappedThirdwebSDKProvider = <
>) => { >) => {
const activeChainId = useMemo(() => { const activeChainId = useMemo(() => {
if (!activeChain) { if (!activeChain) {
return undefined; return supportedChains[0]?.chainId;
} }
if (typeof activeChain === "string" || typeof activeChain === "number") { if (typeof activeChain === "number") {
return activeChain; return activeChain;
} }
if (typeof activeChain === "string") {
return supportedChains.find((c) => c.slug === activeChain)?.chainId;
}
return activeChain.chainId; return activeChain.chainId;
}, [activeChain]); }, [activeChain, supportedChains]);
const sdk = useMemo(() => { const sdk = useMemo(() => {
// on the server we can't do anything (?) // on the server we can't do anything (?)
if (typeof window === "undefined") { if (typeof window === "undefined") {
return undefined; return undefined;
} }
let chainId = resolveChainIdFromNetwork(activeChainId, supportedChains); let chainId = activeChainId;
if (signer && !chainId) {
try {
chainId = (signer?.provider as any)?._network?.chainId;
} catch (e) {}
}
const supportedChain = supportedChains.find((c) => c.chainId === chainId); const supportedChain = supportedChains.find((c) => c.chainId === chainId);
if (!supportedChain && chainId !== undefined) { if (!supportedChain && chainId !== undefined) {
@@ -147,22 +120,23 @@ const WrappedThirdwebSDKProvider = <
} }
} }
// TODO: find a better way to fix the type error
type ForcedChainType = {
rpc: string[];
chainId: number;
nativeCurrency: { symbol: string; name: string; decimals: number };
slug: string;
};
const mergedOptions = { const mergedOptions = {
readonlySettings, readonlySettings,
...sdkOptions, ...sdkOptions,
chains: supportedChains, supportedChains: supportedChains as any as ForcedChainType[],
}; };
let sdk_: ThirdwebSDK | undefined = undefined; let sdk_: ThirdwebSDK | undefined = undefined;
if (signer) { if (chainId) {
// sdk from signer
sdk_ = new ThirdwebSDK(
signer,
{ ...mergedOptions, infuraApiKey, alchemyApiKey, thirdwebApiKey },
storageInterface,
);
} else if (chainId) {
// sdk from chainId // sdk from chainId
sdk_ = new ThirdwebSDK( sdk_ = new ThirdwebSDK(
chainId, chainId,
@@ -183,6 +157,8 @@ const WrappedThirdwebSDKProvider = <
} }
} }
// set the chainId on the sdk instance to compare things later
(sdk_ as any)._chainId = chainId;
return sdk_; return sdk_;
}, [ }, [
activeChainId, activeChainId,
@@ -190,17 +166,29 @@ const WrappedThirdwebSDKProvider = <
infuraApiKey, infuraApiKey,
supportedChains, supportedChains,
sdkOptions, sdkOptions,
signer,
storageInterface, storageInterface,
thirdwebApiKey, thirdwebApiKey,
]); ]);
useEffect(() => {
// if we have an sdk and a signer update the signer
if (sdk && (sdk as any)._chainId === activeChainId) {
if (signer) {
sdk.updateSignerOrProvider(signer);
} else if (activeChainId) {
sdk.updateSignerOrProvider(activeChainId);
}
}
// we know what we're doing
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sdk, (sdk as any)?._chainId, signer, activeChainId]);
const ctxValue = useMemo( const ctxValue = useMemo(
() => ({ () => ({
sdk, sdk: sdk && (sdk as any)._chainId === activeChainId ? sdk : undefined,
_inProvider: true as const, _inProvider: true as const,
}), }),
[sdk], [activeChainId, sdk],
); );
return ( return (
@@ -229,7 +217,7 @@ export const ThirdwebSDKProvider = <
// @ts-expect-error - different subtype of Chain[] but this works fine // @ts-expect-error - different subtype of Chain[] but this works fine
supportedChains = defaultChains, supportedChains = defaultChains,
activeChain, activeChain,
thirdwebApiKey, thirdwebApiKey = DEFAULT_API_KEY,
alchemyApiKey, alchemyApiKey,
infuraApiKey, infuraApiKey,
...restProps ...restProps
@@ -242,7 +230,14 @@ export const ThirdwebSDKProvider = <
) { ) {
return supportedChains as Readonly<Chain[]>; return supportedChains as Readonly<Chain[]>;
} }
return [...supportedChains, activeChain] as Readonly<Chain[]>; const _mergedChains = [...supportedChains, activeChain] as Readonly<
Chain[]
>;
// return a _mergedChains uniqued by chainId key
return _mergedChains.filter(
(chain, index, self) =>
index === self.findIndex((c) => c.chainId === chain.chainId),
);
}, [supportedChains, activeChain]); }, [supportedChains, activeChain]);
return ( return (
@@ -308,5 +303,5 @@ export function useSDK(): ThirdwebSDK | undefined {
*/ */
export function useSDKChainId(): number | undefined { export function useSDKChainId(): number | undefined {
const sdk = useSDK(); const sdk = useSDK();
return (sdk?.getProvider() as any)?._network?.chainId; return (sdk as any)?._chainId;
} }
+2 -2
View File
@@ -88,7 +88,7 @@ export type TokenBurnParams = {
* The possible NFT contract types. * The possible NFT contract types.
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* ``` * ```
* @beta * @beta
*/ */
@@ -103,7 +103,7 @@ export type NFTContract =
* The possible Token contract types. * The possible Token contract types.
* @example * @example
* ```javascript * ```javascript
* const { contract } = useContract(<ContractAddress>); * const { contract } = useContract("{{contract_address}}");
* ``` * ```
* @beta * @beta
*/ */
@@ -111,6 +111,12 @@ export const cacheKeys = {
args: unknown[], args: unknown[],
) => createContractCacheKey(contractAddress, ["call", functionName, args]), ) => createContractCacheKey(contractAddress, ["call", functionName, args]),
app: {
get: (
contractAddress: RequiredParam<ContractAddress>
) => createContractCacheKey(contractAddress, ["appURI"]),
},
events: { events: {
getEvents: ( getEvents: (
contractAddress: RequiredParam<ContractAddress>, contractAddress: RequiredParam<ContractAddress>,
@@ -47,6 +47,7 @@ export function useLogin() {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ payload }), body: JSON.stringify({ payload }),
credentials: "include",
}); });
if (!res.ok) { if (!res.ok) {
@@ -36,7 +36,7 @@ export function useUser<
"Please specify an authUrl in the authConfig.", "Please specify an authUrl in the authConfig.",
); );
// We include credentials so we can getUser even if API is on different URL // We include credentials, so we can getUser even if API is on different URL
const res = await fetch(`${authConfig.authUrl}/user`, { const res = await fetch(`${authConfig.authUrl}/user`, {
credentials: "include", credentials: "include",
}); });
@@ -28,8 +28,7 @@ export function nftGetOneQuery(
/** /**
* Get the metadata for a minted NFT * Get the metadata for a minted NFT
* @param program - The NFT program to get NFT metadata from * @param program - The NFT program to get NFT metadata from
* @param - tokenAdress - The mint address of the NFT to get the metadata of * @param tokenAddress - The mint address of the NFT to get the metadata of *
*
* @example * @example
* ```jsx * ```jsx
* import { useProgram, useNFT } from "@thirdweb-dev/react/solana"; * import { useProgram, useNFT } from "@thirdweb-dev/react/solana";
@@ -21,7 +21,7 @@ export function nftTotalSupplyQuery(
} }
/** /**
* Get the totaly supply of NFTs on the program * Get the total supply of NFTs on the program
* @param program - The NFT program to get the total supply of * @param program - The NFT program to get the total supply of
* *
* @example * @example
@@ -27,7 +27,7 @@ export function balanceQuery(sdk: RequiredParam<ThirdwebSDK>) {
/** /**
* Get the currently connected wallet balance * Get the currently connected wallet balance
* *
* @returns the balace of the connected wallet * @returns the balance of the connected wallet
*/ */
export function useBalance() { export function useBalance() {
const sdk = useSDK(); const sdk = useSDK();
-3
View File
@@ -60,9 +60,6 @@ buck-out/
android/app/libs android/app/libs
android/keystores/debug.keystore android/keystores/debug.keystore
# Expo
.expo/
# Turborepo # Turborepo
.turbo/ .turbo/
+20
View File
@@ -1,5 +1,25 @@
# @thirdweb-dev/react-native # @thirdweb-dev/react-native
## 0.1.7
### Patch Changes
- Updated dependencies [[`68d52f99`](https://github.com/thirdweb-dev/js/commit/68d52f99b36c6744e45872d0bdebafbbf7d09b59), [`9efeba38`](https://github.com/thirdweb-dev/js/commit/9efeba38f06783b78e2c947ad878350173f4e07a)]:
- @thirdweb-dev/sdk@3.10.1
- @thirdweb-dev/react-core@3.10.1
## 0.1.6
### Patch Changes
- [#665](https://github.com/thirdweb-dev/js/pull/665) [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75) Thanks [@shift4id](https://github.com/shift4id)! - Fix spelling throughout all packages
- Updated dependencies [[`a7e908b5`](https://github.com/thirdweb-dev/js/commit/a7e908b5fe60803e64b418cf42e081ca75123a45), [`61ef6964`](https://github.com/thirdweb-dev/js/commit/61ef69649fb605f6079dd9bbef12b739b02dda30), [`2f4cd928`](https://github.com/thirdweb-dev/js/commit/2f4cd92848a6c8cec4e86654f376a6d15bdd2b52), [`6ae39277`](https://github.com/thirdweb-dev/js/commit/6ae39277a1d2ea507cedcde7ae62439758e4d6e0), [`8a8a37f6`](https://github.com/thirdweb-dev/js/commit/8a8a37f6d3468b2a9c9736834bc39a3eee4754f4), [`8f46a2ee`](https://github.com/thirdweb-dev/js/commit/8f46a2eef59d2b21b68e38338ed2b3a820421501), [`8d5b418e`](https://github.com/thirdweb-dev/js/commit/8d5b418e78fcf692f72aed5fe49358e40720d80c), [`63f552d7`](https://github.com/thirdweb-dev/js/commit/63f552d736a549532eb4d6a05cfe66a771b190b9), [`fb346ffd`](https://github.com/thirdweb-dev/js/commit/fb346ffd45edf9f50cc8c68a0c318eee39a6d9c6), [`e081075b`](https://github.com/thirdweb-dev/js/commit/e081075b2cebc7edad855481366bd9864ddba102), [`7832041c`](https://github.com/thirdweb-dev/js/commit/7832041c0fb25852489c73453c2b26e844d94582), [`d8dec9fc`](https://github.com/thirdweb-dev/js/commit/d8dec9fc19079c79729857c36e45102c90fb7e0a), [`478780f6`](https://github.com/thirdweb-dev/js/commit/478780f6349595c17a7b3cd7de7668973c201d65), [`b83ea525`](https://github.com/thirdweb-dev/js/commit/b83ea5251bcd07feaab02a7ad1be202ccc6147fd), [`541dfeea`](https://github.com/thirdweb-dev/js/commit/541dfeeabaa744880cf78b310a9d61db4dfb32b3), [`6ef52dc9`](https://github.com/thirdweb-dev/js/commit/6ef52dc916251d72416ba5a8b63b428770f54e75), [`0c883044`](https://github.com/thirdweb-dev/js/commit/0c88304464ef4461a660a374198e893c578c8de0), [`85250cf7`](https://github.com/thirdweb-dev/js/commit/85250cf71190092b61023d56d1e786d395a008a6), [`2676fc01`](https://github.com/thirdweb-dev/js/commit/2676fc01f4d8eabc90e71fad1f14b4b29806d2bd), [`0666f37c`](https://github.com/thirdweb-dev/js/commit/0666f37c13ed4b824e238325f9d13b9af785e0b0), [`85250cf7`](https://github.com/thirdweb-dev/js/commit/85250cf71190092b61023d56d1e786d395a008a6), [`e33bd2a8`](https://github.com/thirdweb-dev/js/commit/e33bd2a856bbc2e2f6b0c90b46be5166281875ae), [`b80024c6`](https://github.com/thirdweb-dev/js/commit/b80024c6cca17541c9b5ebb51c1476e9f210d3ab), [`8845bf96`](https://github.com/thirdweb-dev/js/commit/8845bf960e18c89d0e1f2fe1c370f4e2f4e855d0), [`2335f000`](https://github.com/thirdweb-dev/js/commit/2335f000c9023dd47b1a341a4dd40ed674e9bcdb), [`696c384a`](https://github.com/thirdweb-dev/js/commit/696c384a348890202e37cbd8488b1b1eceb4e8c2), [`4355518a`](https://github.com/thirdweb-dev/js/commit/4355518afea68cd8026d3ab8a0144c15d66b9e24), [`3740a0bf`](https://github.com/thirdweb-dev/js/commit/3740a0bf5db1301dbd93a97ab4c9343429a4e12d), [`cc7ce8b1`](https://github.com/thirdweb-dev/js/commit/cc7ce8b1e8f73288b5c00a29e0000bea9867e8c1), [`91f5a2fd`](https://github.com/thirdweb-dev/js/commit/91f5a2fd5cb2f5aed6498defdb1feeabb283db6c), [`23cd88ec`](https://github.com/thirdweb-dev/js/commit/23cd88ec3a2af86eafeac258fdc8c5b4ce3196f2), [`87a101ad`](https://github.com/thirdweb-dev/js/commit/87a101ad56430e793c9f22b583fea204dfed0554), [`537785fe`](https://github.com/thirdweb-dev/js/commit/537785fed0021345b0d1cec37658e43c65931f9f), [`29c1cf7e`](https://github.com/thirdweb-dev/js/commit/29c1cf7eff60221d05e87060f3c96a83343218e6), [`b6b0855b`](https://github.com/thirdweb-dev/js/commit/b6b0855b81854ec3d5dd3c763a1ad2a235837cc9), [`2a8cc289`](https://github.com/thirdweb-dev/js/commit/2a8cc289ac42273800554a247cb9259a8f0329d7), [`1e1a3912`](https://github.com/thirdweb-dev/js/commit/1e1a39123bad2b96c332ebb58b25369b31dd9de7), [`dc08aa73`](https://github.com/thirdweb-dev/js/commit/dc08aa731f92ce3c2dd232378637a3075137367d), [`bd6be0ba`](https://github.com/thirdweb-dev/js/commit/bd6be0bae78511878c2344949bb212dab30ec30c)]:
- @thirdweb-dev/sdk@3.10.0
- @thirdweb-dev/react-core@3.10.0
- @thirdweb-dev/storage@1.1.0
- @thirdweb-dev/chains@0.1.6
## 0.1.5 ## 0.1.5
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/react-native", "name": "@thirdweb-dev/react-native",
"version": "0.1.5", "version": "0.1.7",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native",
"author": "thirdweb eng <[email protected]>", "author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -14,7 +14,7 @@ import UniversalProvider from "@walletconnect/universal-provider/dist/types/Univ
* *
* *
* @example * @example
* We can allows user to connect their mobile wallets as follows: * We can allow user to connect their mobile wallets as follows:
* ```javascript * ```javascript
* import { useWalletConnect } from "@thirdweb-dev/react-native" * import { useWalletConnect } from "@thirdweb-dev/react-native"
* *
@@ -59,20 +59,20 @@ export function useWalletConnect() {
}, [wagmiConnectError]); }, [wagmiConnectError]);
useEffect(() => { useEffect(() => {
// wagmi storage doesn't support async storage on mobile so we need to manually connect // wagmi storage doesn't support async storage on mobile, so we need to manually connect
// https://github.com/wagmi-dev/wagmi/discussions/1630 // https://github.com/wagmi-dev/wagmi/discussions/1630
const getProvider = async () => { const getProvider = async () => {
const provider = await walletConnector.getProvider(); const provider = await walletConnector.getProvider();
const univProvider = provider as unknown as UniversalProvider; const univProvider = provider as unknown as UniversalProvider;
// waiting on wagmi to update to latest universal provider (tag 2.4.2) // waiting on wagmi to update the latest universal provider (tag 2.4.2)
// univProvider.client.on('session_request_sent', ({ topic, request, chainId }) => { // univProvider.client.on('session_request_sent', ({ topic, request, chainId }) => {
// // redirect to wallet // // redirect to wallet
// Linking.openURL(displayUri); // Linking.openURL(displayUri);
// }); // });
if (univProvider.client.session.length > 0) { if (univProvider.client.session.length > 0) {
// wc client does not report a successful initialization // wc client does not report a successful initialization,
// so we need to wait for it to initialize before connecting // so we need to wait for it to initialize before connecting
setTimeout(() => { setTimeout(() => {
connect({ connector: walletConnector }); connect({ connector: walletConnector });

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